change some signatures for some ber helpers from unsigned to signed
[obnox/wireshark/wip.git] / tethereal.c
1 /* tethereal.c
2  *
3  * $Id$
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 /* With MSVC and a libethereal.dll this file needs to import some variables 
28    in a special way. Therefore _NEED_VAR_IMPORT_ is defined. */
29 #define _NEED_VAR_IMPORT_
30
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #endif
34
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <ctype.h>
39 #include <locale.h>
40 #include <limits.h>
41
42 #ifdef HAVE_UNISTD_H
43 #include <unistd.h>
44 #endif
45
46 #include <errno.h>
47
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51
52 #include <signal.h>
53
54 #ifdef HAVE_LIBPCAP
55 #include <pcap.h>
56 #include <setjmp.h>
57 #endif
58
59 #ifdef HAVE_SYS_STAT_H
60 # include <sys/stat.h>
61 #endif
62
63 #ifdef NEED_SNPRINTF_H
64 # include "snprintf.h"
65 #endif
66
67 #ifdef NEED_STRERROR_H
68 #include "strerror.h"
69 #endif
70
71 #ifdef NEED_GETOPT_H
72 #include "getopt.h"
73 #endif
74
75 #include "svnversion.h"
76
77 #include <glib.h>
78 #include <epan/epan.h>
79 #include <epan/filesystem.h>
80
81 #include "globals.h"
82 #include <epan/timestamp.h>
83 #include <epan/packet.h>
84 #include "file.h"
85 #include "disabled_protos.h"
86 #include <epan/prefs.h>
87 #include <epan/column.h>
88 #include "print.h"
89 #include <epan/addr_resolv.h>
90 #include "util.h"
91 #include "clopts_common.h"
92 #include "version_info.h"
93 #ifdef HAVE_LIBPCAP
94 #include "pcap-util.h"
95 #endif
96 #include <epan/conversation.h>
97 #include <epan/plugins.h>
98 #include "register.h"
99 #include "conditions.h"
100 #include "capture_stop_conditions.h"
101 #include "ringbuffer.h"
102 #include <epan/epan_dissect.h>
103 #include <epan/tap.h>
104 #include <epan/timestamp.h>
105
106 #ifdef HAVE_LIBPCAP
107 #include <wiretap/wtap-capture.h>
108 #include <wiretap/libpcap.h>
109 #endif
110
111 #ifdef _WIN32
112 #include "capture-wpcap.h"
113 #endif
114
115 /*
116  * This is the template for the decode as option; it is shared between the
117  * various functions that output the usage for this parameter.
118  */
119 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
120
121 static guint32 firstsec, firstusec;
122 static guint32 prevsec, prevusec;
123 static GString *comp_info_str, *runtime_info_str;
124 static gboolean quiet;
125
126 static gboolean print_packet_info;      /* TRUE if we're to print packet information */
127 /*
128  * The way the packet decode is to be written.
129  */
130 typedef enum {
131         WRITE_TEXT,     /* summary or detail text */
132         WRITE_XML       /* PDML or PSML */
133         /* Add CSV and the like here */
134 } output_action_e;
135 static output_action_e output_action;
136 static gboolean do_dissection;  /* TRUE if we have to dissect each packet */
137 static gboolean verbose;
138 static gboolean print_hex;
139 static gboolean line_buffered;
140 static guint32 cum_bytes = 0;
141 static print_format_e print_format = PR_FMT_TEXT;
142 static print_stream_t *print_stream;
143
144 #ifdef HAVE_LIBPCAP
145 typedef struct _loop_data {
146   gboolean       go;           /* TRUE as long as we're supposed to keep capturing */
147   gint           linktype;
148   gboolean       from_pipe;    /* TRUE if we are capturing data from a pipe */
149   pcap_t        *pch;
150   wtap_dumper   *pdh;
151   jmp_buf        stopenv;
152   gboolean       output_to_pipe;
153   int            packet_count;
154 #ifndef _WIN32
155   gboolean       modified;     /* TRUE if data in the pipe uses modified pcap headers */
156   gboolean       byte_swapped; /* TRUE if data in the pipe is byte swapped */
157   unsigned int   bytes_to_read, bytes_read; /* Used by pipe_dispatch */
158   enum {
159          STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
160          STATE_EXPECT_DATA,     STATE_READ_DATA
161        } pipe_state;
162
163   enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
164 #endif
165 } loop_data;
166
167 static loop_data ld;
168
169 static int capture(int);
170 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
171   const guchar *);
172 static void report_counts(void);
173 #ifdef _WIN32
174 static BOOL WINAPI capture_cleanup(DWORD);
175 #else /* _WIN32 */
176 static void capture_cleanup(int);
177 #ifdef SIGINFO
178 static void report_counts_siginfo(int);
179 #endif /* SIGINFO */
180 #endif /* _WIN32 */
181 #endif /* HAVE_LIBPCAP */
182
183 static int load_cap_file(capture_file *, int);
184 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
185     const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
186     const guchar *pd, int *err);
187 static void show_capture_file_io_error(const char *, int, gboolean);
188 static void show_print_file_io_error(int err);
189 static gboolean write_preamble(capture_file *cf);
190 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
191 static gboolean write_finale(void);
192 static char *cf_open_error_message(int err, gchar *err_info,
193     gboolean for_writing, int file_type);
194 #ifdef HAVE_LIBPCAP
195 #ifndef _WIN32
196 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
197 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
198 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
199                 struct pcaprec_modified_hdr *, guchar *, char *, int);
200 #endif /* _WIN32 */
201 #endif
202
203 static void open_failure_message(const char *filename, int err,
204     gboolean for_writing);
205 static void failure_message(const char *msg_format, va_list ap);
206 static void read_failure_message(const char *filename, int err);
207
208 capture_file cfile;
209 #ifdef HAVE_LIBPCAP
210 typedef struct {
211         int snaplen;                    /* Maximum captured packet length */
212         int promisc_mode;               /* Capture in promiscuous mode */
213         int autostop_count;             /* Maximum packet count */
214         gboolean has_autostop_duration; /* TRUE if maximum capture duration
215                                            is specified */
216         gint32 autostop_duration;       /* Maximum capture duration */
217         gboolean has_autostop_filesize; /* TRUE if maximum capture file size
218                                            is specified */
219         gint32 autostop_filesize;       /* Maximum capture file size */
220         gboolean ringbuffer_on;         /* TRUE if ring buffer in use */
221         guint32 ringbuffer_num_files;   /* Number of ring buffer files */
222         gboolean has_ring_duration;     /* TRUE if ring duration specified */
223         gint32 ringbuffer_duration;     /* Switch file after n seconds */
224         int linktype;                   /* Data link type to use, or -1 for
225                                            "use default" */
226 } capture_options;
227
228 static capture_options capture_opts = {
229         WTAP_MAX_PACKET_SIZE,           /* snapshot length - default is
230                                            infinite, in effect */
231         TRUE,                           /* promiscuous mode is the default */
232         0,                              /* max packet count - default is 0,
233                                            meaning infinite */
234         FALSE,                          /* maximum capture duration not
235                                            specified by default */
236         0,                              /* maximum capture duration */
237         FALSE,                          /* maximum capture file size not
238                                            specified by default */
239         0,                              /* maximum capture file size */
240         FALSE,                          /* ring buffer off by default */
241         RINGBUFFER_MIN_NUM_FILES,       /* default number of ring buffer
242                                            files */
243         FALSE,                          /* Switch ring file after some */
244         0,                              /* specified time is off by default */
245         -1                              /* Default to not change link type */
246 };
247
248 static gboolean list_link_layer_types;
249
250 #ifdef SIGINFO
251 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
252 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
253 #endif /* SIGINFO */
254 #endif /* HAVE_LIBPCAP */
255
256 static void
257 print_usage(gboolean print_ver)
258 {
259   int i;
260   FILE *output;
261
262   if (print_ver) {
263     output = stdout;
264     fprintf(output, "This is GNU t" PACKAGE " " VERSION
265 #ifdef SVNVERSION
266         " (" SVNVERSION ")"
267 #endif
268         "\n (C) 1998-2004 Gerald Combs <gerald@ethereal.com>"
269         "\n%s\n%s\n",
270
271         comp_info_str->str, runtime_info_str->str);
272   } else {
273     output = stderr;
274   }
275 #ifdef HAVE_LIBPCAP
276   fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
277           PACKAGE);
278   fprintf(output, "\t[ -b <number of ring buffer files>[:<duration>] ] [ -c <count> ]\n");
279   fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
280   fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ] [ -i <interface> ]\n");
281   fprintf(output, "\t[ -N <resolving> ] [ -o <preference setting> ] ... [ -r <infile> ]\n");
282   fprintf(output, "\t[ -R <read filter> ] [ -s <snaplen> ] [ -t <time stamp format> ]\n");
283   fprintf(output, "\t[ -T pdml|ps|psml|text ] [ -w <savefile> ] [ -y <link type> ]\n");
284   fprintf(output, "\t[ -z <statistics string> ]\n");
285 #else
286   fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
287   fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
288   fprintf(output, "\t[ -F <output file type> ] [ -N <resolving> ]\n");
289   fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
290   fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|psml|text ] [ -w <savefile> ]\n");
291   fprintf(output, "\t[ -z <statistics string> ]\n");
292 #endif
293   fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
294   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
295     if (wtap_dump_can_open(i))
296       fprintf(output, "\t%s - %s\n",
297         wtap_file_type_short_string(i), wtap_file_type_string(i));
298   }
299   fprintf(output, "\tdefault is libpcap\n");
300 }
301
302 #ifdef HAVE_LIBPCAP
303 static int
304 get_natural_int(const char *string, const char *name)
305 {
306   long number;
307   char *p;
308
309   number = strtol(string, &p, 10);
310   if (p == string || *p != '\0') {
311     fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
312             name, string);
313     exit(1);
314   }
315   if (number < 0) {
316     fprintf(stderr, "tethereal: The specified %s is a negative number\n",
317             name);
318     exit(1);
319   }
320   if (number > INT_MAX) {
321     fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
322             name, INT_MAX);
323     exit(1);
324   }
325   return number;
326 }
327
328 static int
329 get_positive_int(const char *string, const char *name)
330 {
331   long number;
332
333   number = get_natural_int(string, name);
334
335   if (number == 0) {
336     fprintf(stderr, "tethereal: The specified %s is zero\n",
337             name);
338     exit(1);
339   }
340
341   return number;
342 }
343
344 /*
345  * Given a string of the form "<autostop criterion>:<value>", as might appear
346  * as an argument to a "-a" option, parse it and set the criterion in
347  * question.  Return an indication of whether it succeeded or failed
348  * in some fashion.
349  */
350 static gboolean
351 set_autostop_criterion(const char *autostoparg)
352 {
353   guchar *p, *colonp;
354
355   colonp = strchr(autostoparg, ':');
356   if (colonp == NULL)
357     return FALSE;
358
359   p = colonp;
360   *p++ = '\0';
361
362   /*
363    * Skip over any white space (there probably won't be any, but
364    * as we allow it in the preferences file, we might as well
365    * allow it here).
366    */
367   while (isspace(*p))
368     p++;
369   if (*p == '\0') {
370     /*
371      * Put the colon back, so if our caller uses, in an
372      * error message, the string they passed us, the message
373      * looks correct.
374      */
375     *colonp = ':';
376     return FALSE;
377   }
378   if (strcmp(autostoparg,"duration") == 0) {
379     capture_opts.has_autostop_duration = TRUE;
380     capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
381   } else if (strcmp(autostoparg,"filesize") == 0) {
382     capture_opts.has_autostop_filesize = TRUE;
383     capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
384   } else {
385     return FALSE;
386   }
387   *colonp = ':';        /* put the colon back */
388   return TRUE;
389 }
390
391 /*
392  * Given a string of the form "<ring buffer file>:<duration>", as might appear
393  * as an argument to a "-b" option, parse it and set the arguments in
394  * question.  Return an indication of whether it succeeded or failed
395  * in some fashion.
396  */
397 static gboolean
398 get_ring_arguments(const char *arg)
399 {
400   guchar *p = NULL, *colonp;
401
402   colonp = strchr(arg, ':');
403
404   if (colonp != NULL) {
405     p = colonp;
406     *p++ = '\0';
407   }
408
409   capture_opts.ringbuffer_num_files = 
410     get_natural_int(arg, "number of ring buffer files");
411
412   if (colonp == NULL)
413     return TRUE;
414
415   /*
416    * Skip over any white space (there probably won't be any, but
417    * as we allow it in the preferences file, we might as well
418    * allow it here).
419    */
420   while (isspace(*p))
421     p++;
422   if (*p == '\0') {
423     /*
424      * Put the colon back, so if our caller uses, in an
425      * error message, the string they passed us, the message
426      * looks correct.
427      */
428     *colonp = ':';
429     return FALSE;
430   }
431
432   capture_opts.has_ring_duration = TRUE;
433   capture_opts.ringbuffer_duration = get_positive_int(p,
434                                                       "ring buffer duration");
435
436   *colonp = ':';        /* put the colon back */
437   return TRUE;
438 }
439 #endif
440
441 /* structure to keep track of what tap listeners have been registered.
442  */
443 typedef struct _ethereal_tap_list {
444         struct _ethereal_tap_list *next;
445         char *cmd;
446         void (*func)(char *arg);
447 } ethereal_tap_list;
448 static ethereal_tap_list *tap_list=NULL;
449
450 void
451 register_ethereal_tap(char *cmd, void (*func)(char *arg))
452 {
453         ethereal_tap_list *newtl;
454
455         newtl=malloc(sizeof(ethereal_tap_list));
456         newtl->next=tap_list;
457         tap_list=newtl;
458         newtl->cmd=cmd;
459         newtl->func=func;
460
461 }
462
463 /*
464  * For a dissector table, print on the stream described by output,
465  * its short name (which is what's used in the "-d" option) and its
466  * descriptive name.
467  */
468 static void
469 display_dissector_table_names(char *table_name, char *ui_name, gpointer output)
470 {
471   fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
472 }
473
474 /*
475  * For a dissector handle, print on the stream described by output,
476  * the filter name (which is what's used in the "-d" option) and the full
477  * name for the protocol that corresponds to this handle.
478  */
479 static void
480 display_dissector_names(gchar *table _U_, gpointer handle, gpointer output)
481 {
482   int                proto_id;
483   const gchar*       proto_filter_name;
484   const gchar*       proto_ui_name;
485
486   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
487
488   if (proto_id != -1) {
489     proto_filter_name = proto_get_protocol_filter_name(proto_id);
490     proto_ui_name =  proto_get_protocol_name(proto_id);
491     g_assert(proto_filter_name != NULL);
492     g_assert(proto_ui_name != NULL);
493
494     fprintf((FILE *)output, "\t%s (%s)\n",
495             proto_filter_name,
496             proto_ui_name);
497   }
498 }
499
500 /*
501  * The protocol_name_search structure is used by find_protocol_name_func()
502  * to pass parameters and store results
503  */
504 struct protocol_name_search{
505   gchar              *searched_name;  /* Protocol filter name we are looking for */
506   dissector_handle_t  matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
507   guint               nb_match;       /* How many dissectors matched searched_name */
508 };
509 typedef struct protocol_name_search *protocol_name_search_t;
510
511 /*
512  * This function parses all dissectors associated with a table to find the
513  * one whose protocol has the specified filter name.  It is called
514  * as a reference function in a call to dissector_table_foreach_handle.
515  * The name we are looking for, as well as the results, are stored in the
516  * protocol_name_search struct pointed to by user_data.
517  * If called using dissector_table_foreach_handle, we actually parse the
518  * whole list of dissectors.
519  */
520 static void
521 find_protocol_name_func(gchar *table _U_, gpointer handle, gpointer user_data)
522
523 {
524   int                         proto_id;
525   const gchar                *protocol_filter_name;
526   protocol_name_search_t      search_info;
527
528   g_assert(handle);
529
530   search_info = (protocol_name_search_t)user_data;
531
532   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
533   if (proto_id != -1) {
534     protocol_filter_name = proto_get_protocol_filter_name(proto_id);
535     g_assert(protocol_filter_name != NULL);
536     if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
537       /* Found a match */
538       if (search_info->nb_match == 0) {
539         /* Record this handle only if this is the first match */
540         search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
541       }
542       search_info->nb_match++;
543     }
544   }
545 }
546
547 /*
548  * Print all layer type names supported.
549  * We send the output to the stream described by the handle output.
550  */
551
552 static void
553 fprint_all_layer_types(FILE *output)
554
555 {
556   dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
557 }
558
559 /*
560  * Print all protocol names supported for a specific layer type.
561  * table_name contains the layer type name in which the search is performed.
562  * We send the output to the stream described by the handle output.
563  */
564
565 static void
566 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
567
568 {
569   dissector_table_foreach_handle(table_name,
570                                  display_dissector_names,
571                                  (gpointer)output);
572 }
573
574 /*
575  * The function below parses the command-line parameters for the decode as
576  * feature (a string pointer by cl_param).
577  * It checks the format of the command-line, searches for a matching table
578  * and dissector.  If a table/dissector match is not found, we display a
579  * summary of the available tables/dissectors (on stderr) and return FALSE.
580  * If everything is fine, we get the "Decode as" preference activated,
581  * then we return TRUE.
582  */
583 static gboolean
584 add_decode_as(const gchar *cl_param)
585 {
586   gchar                        *table_name;
587   guint32                       selector;
588   gchar                        *decoded_param;
589   gchar                        *remaining_param;
590   gchar                        *selector_str;
591   gchar                        *dissector_str;
592   dissector_handle_t            dissector_matching;
593   dissector_table_t             table_matching;
594   ftenum_t                      dissector_table_selector_type;
595   struct protocol_name_search   user_protocol_name;
596
597 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
598
599   g_assert(cl_param);
600   decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
601   g_assert(decoded_param);
602   strcpy(decoded_param, cl_param);
603
604
605   /* The lines below will parse this string (modifying it) to extract all
606     necessary information.  Note that decoded_param is still needed since
607     strings are not copied - we just save pointers. */
608
609   /* This section extracts a layer type (table_name) from decoded_param */
610   table_name = decoded_param; /* Layer type string starts from beginning */
611
612   remaining_param = strchr(table_name, '=');
613   if (remaining_param == NULL) {
614     fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
615     /* If the argument does not follow the template, carry on anyway to check
616        if the table name is at least correct.  If remaining_param is NULL,
617        we'll exit anyway further down */
618   }
619   else {
620     *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
621   }
622
623   /* Remove leading and trailing spaces from the table name */
624   while ( table_name[0] == ' ' )
625     table_name++; 
626   while ( table_name[strlen(table_name) - 1] == ' ' )
627     table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
628
629 /* The following part searches a table matching with the layer type specified */
630   table_matching = NULL;
631
632 /* Look for the requested table */
633   if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
634     fprintf(stderr, "tethereal: No layer type specified\n"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
635   }
636   else {
637     table_matching = find_dissector_table(table_name);
638     if (!table_matching) {
639       fprintf(stderr, "tethereal: Unknown layer type -- %s\n", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
640     }
641   }
642
643   if (!table_matching) {
644     /* Display a list of supported layer types to help the user, if the 
645        specified layer type was not found */
646     fprintf(stderr, "tethereal: Valid layer types are:\n");
647     fprint_all_layer_types(stderr);
648   }
649   if (remaining_param == NULL || !table_matching) {
650     /* Exit if the layer type was not found, or if no '=' separator was found
651        (see above) */
652     g_free(decoded_param); 
653     return FALSE;
654   }
655   
656   if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
657     fprintf(stderr, "tethereal: WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"\n", table_name, remaining_param + 1);
658   }
659   else {
660     remaining_param++; /* Move to the second '=' */
661     *remaining_param = '\0'; /* Remove the second '=' */
662   }
663   remaining_param++; /* Position after the layer type string */
664
665   /* This section extracts a selector value (selector_str) from decoded_param */
666
667   selector_str = remaining_param; /* Next part starts with the selector number */
668
669   remaining_param = strchr(selector_str, ',');
670   if (remaining_param == NULL) {
671     fprintf(stderr, "tethereal: Parameter \"%s\" doesn't follow the template \"%s\"\n", cl_param, decode_as_arg_template);
672     /* If the argument does not follow the template, carry on anyway to check
673        if the selector value is at least correct.  If remaining_param is NULL,
674        we'll exit anyway further down */
675   }
676   else {
677     *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
678   }
679
680   dissector_table_selector_type = get_dissector_table_selector_type(table_name);
681
682   switch (dissector_table_selector_type) {
683
684   case FT_UINT8:
685   case FT_UINT16:
686   case FT_UINT24:
687   case FT_UINT32:
688     /* The selector for this table is an unsigned number.  Parse it as such.
689        There's no need to remove leading and trailing spaces from the
690        selector number string, because sscanf will do that for us. */
691     if ( sscanf(selector_str, "%u", &selector) != 1 ) {
692       fprintf(stderr, "tethereal: Invalid selector number \"%s\"\n", selector_str);
693       g_free(decoded_param);
694       return FALSE;
695     }
696     break;
697
698   case FT_STRING:
699   case FT_STRINGZ:
700     /* The selector for this table is a string. */
701     break;
702
703   default:
704     /* There are currently no dissector tables with any types other
705        than the ones listed above. */
706     g_assert_not_reached();
707   }
708
709   if (remaining_param == NULL) {
710     /* Exit if no ',' separator was found (see above) */
711     fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
712     fprint_all_protocols_for_layer_types(stderr, table_name);
713     g_free(decoded_param); 
714     return FALSE;
715   }
716
717   remaining_param++; /* Position after the selector number string */
718
719   /* This section extracts a protocol filter name (dissector_str) from decoded_param */
720
721   dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
722   
723   /* Remove leading and trailing spaces from the dissector name */
724   while ( dissector_str[0] == ' ' )
725     dissector_str++; 
726   while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
727     dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
728
729   dissector_matching = NULL;
730   
731   /* We now have a pointer to the handle for the requested table inside the variable table_matching */
732   if ( ! (*dissector_str) ) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
733     fprintf(stderr, "tethereal: No protocol name specified\n"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
734   }
735   else {
736     user_protocol_name.nb_match = 0;
737     user_protocol_name.searched_name = dissector_str;
738     user_protocol_name.matched_handle = NULL;
739     
740     dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
741     
742     if (user_protocol_name.nb_match != 0) {
743       dissector_matching = user_protocol_name.matched_handle;
744       if (user_protocol_name.nb_match > 1) {
745         fprintf(stderr, "tethereal: WARNING: Protocol \"%s\" matched %u dissectors, first one will be used\n", dissector_str, user_protocol_name.nb_match);
746       }
747     }
748     else {
749       /* OK, check whether the problem is that there isn't any such
750          protocol, or that there is but it's not specified as a protocol
751          that's valid for that dissector table.
752          Note, we don't exit here, but dissector_matching will remain NULL,
753          so we exit below */
754       if (proto_get_id_by_filter_name(dissector_str) == -1) {
755         /* No such protocol */
756         fprintf(stderr, "tethereal: Unknown protocol -- \"%s\"\n", dissector_str);
757       } else {
758         fprintf(stderr, "tethereal: Protocol \"%s\" isn't valid for layer type \"%s\"\n",
759                 dissector_str, table_name);
760       }
761     }
762   }
763
764   if (!dissector_matching) {
765     fprintf(stderr, "tethereal: Valid protocols for layer type \"%s\" are:\n", table_name);
766     fprint_all_protocols_for_layer_types(stderr, table_name);
767     g_free(decoded_param); 
768     return FALSE;
769   }
770
771 /* This is the end of the code that parses the command-line options.
772    All information is now stored in the variables:
773    table_name
774    selector
775    dissector_matching
776    The above variables that are strings are still pointing to areas within
777    decoded_parm.  decoded_parm thus still needs to be kept allocated in 
778    until we stop needing these variables
779    decoded_param will be deallocated at each exit point of this function */
780
781
782   /* We now have a pointer to the handle for the requested dissector
783      (requested protocol) inside the variable dissector_matching */
784   switch (dissector_table_selector_type) {
785
786   case FT_UINT8:
787   case FT_UINT16:
788   case FT_UINT24:
789   case FT_UINT32:
790     /* The selector for this table is an unsigned number. */
791     dissector_change(table_name, selector, dissector_matching);
792     break;
793
794   case FT_STRING:
795   case FT_STRINGZ:
796     /* The selector for this table is a string. */
797     dissector_change_string(table_name, selector_str, dissector_matching);
798     break;
799
800   default:
801     /* There are currently no dissector tables with any types other
802        than the ones listed above. */
803     g_assert_not_reached();
804   }
805   g_free(decoded_param); /* "Decode As" rule has been succesfully added */
806   return TRUE;
807 }
808
809 int
810 main(int argc, char *argv[])
811 {
812   int                  opt, i;
813   extern char         *optarg;
814   gboolean             arg_error = FALSE;
815
816 #ifdef _WIN32
817   WSADATA               wsaData;
818 #endif  /* _WIN32 */
819
820   char                *gpf_path, *pf_path;
821   char                *gdp_path, *dp_path;
822   int                  gpf_open_errno, gpf_read_errno;
823   int                  pf_open_errno, pf_read_errno;
824   int                  gdp_open_errno, gdp_read_errno;
825   int                  dp_open_errno, dp_read_errno;
826   int                  err;
827 #ifdef HAVE_LIBPCAP
828   gboolean             capture_filter_specified = FALSE;
829   GList               *if_list, *if_entry;
830   if_info_t           *if_info;
831   long                 adapter_index;
832   char                *p;
833   gchar                err_str[PCAP_ERRBUF_SIZE];
834   gchar               *cant_get_if_list_errstr;
835 #else
836   gboolean             capture_option_specified = FALSE;
837 #endif
838   int                  out_file_type = WTAP_FILE_PCAP;
839   gchar               *cf_name = NULL, *rfilter = NULL;
840 #ifdef HAVE_LIBPCAP
841   gchar               *if_text;
842   GList               *lt_list, *lt_entry;
843   data_link_info_t    *data_link_info;
844 #endif
845 #ifdef HAVE_PCAP_OPEN_DEAD
846   struct bpf_program   fcode;
847 #endif
848   dfilter_t           *rfcode = NULL;
849   e_prefs             *prefs;
850   char                 badopt;
851   ethereal_tap_list *tli;
852
853   set_timestamp_setting(TS_RELATIVE);
854
855   /* Register all dissectors; we must do this before checking for the
856      "-G" flag, as the "-G" flag dumps information registered by the
857      dissectors, and we must do it before we read the preferences, in
858      case any dissectors register preferences. */
859   epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
860             failure_message,open_failure_message,read_failure_message);
861
862   /* Register all tap listeners; we do this before we parse the arguments,
863      as the "-z" argument can specify a registered tap. */
864   register_all_tap_listeners();
865
866   /* Now register the preferences for any non-dissector modules.
867      We must do that before we read the preferences as well. */
868   prefs_register_modules();
869
870   /* If invoked with the "-G" flag, we dump out information based on
871      the argument to the "-G" flag; if no argument is specified,
872      for backwards compatibility we dump out a glossary of display
873      filter symbols.
874
875      We do this here to mirror what happens in the GTK+ version, although
876      it's not necessary here. */
877   handle_dashG_option(argc, argv, "tethereal");
878
879   /* Set the C-language locale to the native environment. */
880   setlocale(LC_ALL, "");
881
882   prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
883                      &pf_open_errno, &pf_read_errno, &pf_path);
884   if (gpf_path != NULL) {
885     if (gpf_open_errno != 0) {
886       fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n",
887               pf_path, strerror(gpf_open_errno));
888     }
889     if (gpf_read_errno != 0) {
890       fprintf(stderr, "I/O error reading global preferences file \"%s\": %s.\n",
891               pf_path, strerror(gpf_read_errno));
892     }
893   }
894   if (pf_path != NULL) {
895     if (pf_open_errno != 0) {
896       fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
897               strerror(pf_open_errno));
898     }
899     if (pf_read_errno != 0) {
900       fprintf(stderr, "I/O error reading your preferences file \"%s\": %s.\n",
901               pf_path, strerror(pf_read_errno));
902     }
903     g_free(pf_path);
904     pf_path = NULL;
905   }
906
907   /* Set the name resolution code's flags from the preferences. */
908   g_resolv_flags = prefs->name_resolve;
909
910   /* Read the disabled protocols file. */
911   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
912                             &dp_path, &dp_open_errno, &dp_read_errno);
913   if (gdp_path != NULL) {
914     if (gdp_open_errno != 0) {
915       fprintf(stderr,
916         "Could not open global disabled protocols file\n\"%s\": %s.\n",
917         gdp_path, strerror(gdp_open_errno));
918     }
919     if (gdp_read_errno != 0) {
920       fprintf(stderr,
921         "I/O error reading global disabled protocols file\n\"%s\": %s.\n",
922         gdp_path, strerror(gdp_read_errno));
923     }
924     g_free(gdp_path);
925   }
926   if (dp_path != NULL) {
927     if (dp_open_errno != 0) {
928       fprintf(stderr,
929         "Could not open your disabled protocols file\n\"%s\": %s.\n", dp_path,
930         strerror(dp_open_errno));
931     }
932     if (dp_read_errno != 0) {
933       fprintf(stderr,
934         "I/O error reading your disabled protocols file\n\"%s\": %s.\n", dp_path,
935         strerror(dp_read_errno));
936     }
937     g_free(dp_path);
938   }
939
940 #ifdef _WIN32
941   /* Load Wpcap, if possible */
942   load_wpcap();
943 #endif
944
945   init_cap_file(&cfile);
946
947   /* Assemble the compile-time version information string */
948   comp_info_str = g_string_new("Compiled ");
949   get_compiled_version_info(comp_info_str);
950
951   /* Assemble the run-time version information string */
952   runtime_info_str = g_string_new("Running ");
953   get_runtime_version_info(runtime_info_str);
954
955   /* Print format defaults to this. */
956   print_format = PR_FMT_TEXT;
957
958   /* Now get our args */
959   while ((opt = getopt(argc, argv, "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vw:Vxy:z:")) != -1) {
960     switch (opt) {
961       case 'a':        /* autostop criteria */
962 #ifdef HAVE_LIBPCAP
963         if (set_autostop_criterion(optarg) == FALSE) {
964           fprintf(stderr, "tethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
965           exit(1);
966         }
967 #else
968         capture_option_specified = TRUE;
969         arg_error = TRUE;
970 #endif
971         break;
972       case 'b':        /* Ringbuffer option */
973 #ifdef HAVE_LIBPCAP
974         capture_opts.ringbuffer_on = TRUE;
975         if (get_ring_arguments(optarg) == FALSE) {
976           fprintf(stderr, "tethereal: Invalid or unknown -b arg \"%s\"\n", optarg);
977           exit(1);
978         }
979 #else
980         capture_option_specified = TRUE;
981         arg_error = TRUE;
982 #endif
983         break;
984       case 'c':        /* Capture xxx packets */
985 #ifdef HAVE_LIBPCAP
986         capture_opts.autostop_count =
987             get_positive_int(optarg, "packet count");
988 #else
989         capture_option_specified = TRUE;
990         arg_error = TRUE;
991 #endif
992         break;
993       case 'd':        /* Decode as rule */
994         if (!add_decode_as(optarg))
995           exit(1);
996         break;
997       case 'D':        /* Print a list of capture devices */
998 #ifdef HAVE_LIBPCAP
999         if_list = get_interface_list(&err, err_str);
1000         if (if_list == NULL) {
1001             switch (err) {
1002
1003             case CANT_GET_INTERFACE_LIST:
1004                 cant_get_if_list_errstr =
1005                     cant_get_if_list_error_message(err_str);
1006                 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
1007                 g_free(cant_get_if_list_errstr);
1008                 break;
1009
1010             case NO_INTERFACES_FOUND:
1011                 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1012                 break;
1013             }
1014             exit(2);
1015         }
1016         i = 1;  /* Interface id number */
1017         for (if_entry = g_list_first(if_list); if_entry != NULL;
1018                 if_entry = g_list_next(if_entry)) {
1019           if_info = if_entry->data;
1020           printf("%d. %s", i++, if_info->name);
1021           if (if_info->description != NULL)
1022             printf(" (%s)", if_info->description);
1023           printf("\n");
1024         }
1025         free_interface_list(if_list);
1026         exit(0);
1027 #else
1028         capture_option_specified = TRUE;
1029         arg_error = TRUE;
1030 #endif
1031         break;
1032       case 'f':
1033 #ifdef HAVE_LIBPCAP
1034         capture_filter_specified = TRUE;
1035         if (cfile.cfilter)
1036                 g_free(cfile.cfilter);
1037         cfile.cfilter = g_strdup(optarg);
1038 #else
1039         capture_option_specified = TRUE;
1040         arg_error = TRUE;
1041 #endif
1042         break;
1043       case 'F':
1044         out_file_type = wtap_short_string_to_file_type(optarg);
1045         if (out_file_type < 0) {
1046           fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
1047                         optarg);
1048           exit(1);
1049         }
1050         break;
1051       case 'h':        /* Print help and exit */
1052         print_usage(TRUE);
1053         exit(0);
1054         break;
1055       case 'i':        /* Use interface xxx */
1056 #ifdef HAVE_LIBPCAP
1057         /*
1058          * If the argument is a number, treat it as an index into the list
1059          * of adapters, as printed by "tethereal -D".
1060          *
1061          * This should be OK on UNIX systems, as interfaces shouldn't have
1062          * names that begin with digits.  It can be useful on Windows, where
1063          * more than one interface can have the same name.
1064          */
1065         adapter_index = strtol(optarg, &p, 10);
1066         if (p != NULL && *p == '\0') {
1067           if (adapter_index < 0) {
1068             fprintf(stderr,
1069                 "tethereal: The specified adapter index is a negative number\n");
1070            exit(1);
1071           }
1072           if (adapter_index > INT_MAX) {
1073             fprintf(stderr,
1074                 "tethereal: The specified adapter index is too large (greater than %d)\n",
1075                 INT_MAX);
1076             exit(1);
1077           }
1078           if (adapter_index == 0) {
1079             fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1080             exit(1);
1081           }
1082           if_list = get_interface_list(&err, err_str);
1083           if (if_list == NULL) {
1084             switch (err) {
1085
1086             case CANT_GET_INTERFACE_LIST:
1087                 cant_get_if_list_errstr =
1088                     cant_get_if_list_error_message(err_str);
1089                 fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
1090                 g_free(cant_get_if_list_errstr);
1091                 break;
1092
1093             case NO_INTERFACES_FOUND:
1094                 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1095                 break;
1096             }
1097             exit(2);
1098           }
1099           if_info = g_list_nth_data(if_list, adapter_index - 1);
1100           if (if_info == NULL) {
1101             fprintf(stderr, "tethereal: there is no interface with that adapter index\n");
1102             exit(1);
1103           }
1104           cfile.iface = g_strdup(if_info->name);
1105           free_interface_list(if_list);
1106         } else
1107           cfile.iface = g_strdup(optarg);
1108 #else
1109         capture_option_specified = TRUE;
1110         arg_error = TRUE;
1111 #endif
1112         break;
1113       case 'l':        /* "Line-buffer" standard output */
1114         /* This isn't line-buffering, strictly speaking, it's just
1115            flushing the standard output after the information for
1116            each packet is printed; however, that should be good
1117            enough for all the purposes to which "-l" is put (and
1118            is probably actually better for "-V", as it does fewer
1119            writes).
1120
1121            See the comment in "process_packet()" for an explanation of
1122            why we do that, and why we don't just use "setvbuf()" to
1123            make the standard output line-buffered (short version: in
1124            Windows, "line-buffered" is the same as "fully-buffered",
1125            and the output buffer is only flushed when it fills up). */
1126         line_buffered = TRUE;
1127         break;
1128       case 'L':        /* Print list of link-layer types and exit */
1129 #ifdef HAVE_LIBPCAP
1130         list_link_layer_types = TRUE;
1131         break;
1132 #else
1133         capture_option_specified = TRUE;
1134         arg_error = TRUE;
1135 #endif
1136         break;
1137       case 'n':        /* No name resolution */
1138         g_resolv_flags = RESOLV_NONE;
1139         break;
1140       case 'N':        /* Select what types of addresses/port #s to resolve */
1141         if (g_resolv_flags == RESOLV_ALL)
1142           g_resolv_flags = RESOLV_NONE;
1143         badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1144         if (badopt != '\0') {
1145           fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
1146                         badopt);
1147           exit(1);
1148         }
1149         break;
1150       case 'o':        /* Override preference from command line */
1151         switch (prefs_set_pref(optarg)) {
1152
1153         case PREFS_SET_SYNTAX_ERR:
1154           fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
1155           exit(1);
1156           break;
1157
1158         case PREFS_SET_NO_SUCH_PREF:
1159         case PREFS_SET_OBSOLETE:
1160           fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
1161                         optarg);
1162           exit(1);
1163           break;
1164         }
1165         break;
1166       case 'p':        /* Don't capture in promiscuous mode */
1167 #ifdef HAVE_LIBPCAP
1168         capture_opts.promisc_mode = FALSE;
1169 #else
1170         capture_option_specified = TRUE;
1171         arg_error = TRUE;
1172 #endif
1173         break;
1174       case 'q':        /* Quiet */
1175         quiet = TRUE;
1176         break;
1177       case 'r':        /* Read capture file xxx */
1178         cf_name = g_strdup(optarg);
1179         break;
1180       case 'R':        /* Read file filter */
1181         rfilter = optarg;
1182         break;
1183       case 's':        /* Set the snapshot (capture) length */
1184 #ifdef HAVE_LIBPCAP
1185         capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
1186 #else
1187         capture_option_specified = TRUE;
1188         arg_error = TRUE;
1189 #endif
1190         break;
1191       case 'S':        /* show packets in real time */
1192         print_packet_info = TRUE;
1193         break;
1194       case 't':        /* Time stamp type */
1195         if (strcmp(optarg, "r") == 0)
1196           set_timestamp_setting(TS_RELATIVE);
1197         else if (strcmp(optarg, "a") == 0)
1198           set_timestamp_setting(TS_ABSOLUTE);
1199         else if (strcmp(optarg, "ad") == 0)
1200           set_timestamp_setting(TS_ABSOLUTE_WITH_DATE);
1201         else if (strcmp(optarg, "d") == 0)
1202           set_timestamp_setting(TS_DELTA);
1203         else {
1204           fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
1205             optarg);
1206           fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
1207           fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
1208           exit(1);
1209         }
1210         break;
1211       case 'T':        /* printing Type */
1212         if (strcmp(optarg, "text") == 0) {
1213           output_action = WRITE_TEXT;
1214           print_format = PR_FMT_TEXT;
1215         } else if (strcmp(optarg, "ps") == 0) {
1216           output_action = WRITE_TEXT;
1217           print_format = PR_FMT_PS;
1218         } else if (strcmp(optarg, "pdml") == 0) {
1219           output_action = WRITE_XML;
1220           verbose = TRUE;
1221         } else if (strcmp(optarg, "psml") == 0) {
1222           output_action = WRITE_XML;
1223           verbose = FALSE;
1224         } else {
1225           fprintf(stderr, "tethereal: Invalid -T parameter.\n");
1226           fprintf(stderr, "It must be \"ps\", \"text\", \"pdml\", or \"psml\".\n");
1227           exit(1);
1228         }
1229         break;
1230       case 'v':        /* Show version and exit */
1231         printf("t" PACKAGE " " VERSION
1232 #ifdef SVNVERSION
1233             " (" SVNVERSION ")"
1234 #endif
1235             "\n%s\n%s\n",
1236             comp_info_str->str, runtime_info_str->str);
1237         exit(0);
1238         break;
1239       case 'w':        /* Write to capture file xxx */
1240         cfile.save_file = g_strdup(optarg);
1241         break;
1242       case 'V':        /* Verbose */
1243         verbose = TRUE;
1244         break;
1245       case 'x':        /* Print packet data in hex (and ASCII) */
1246         print_hex = TRUE;
1247         break;
1248       case 'y':        /* Set the pcap data link type */
1249 #ifdef HAVE_LIBPCAP
1250 #ifdef HAVE_PCAP_DATALINK_NAME_TO_VAL
1251         capture_opts.linktype = pcap_datalink_name_to_val(optarg);
1252         if (capture_opts.linktype == -1) {
1253           fprintf(stderr, "tethereal: The specified data link type \"%s\" is not valid\n",
1254                   optarg);
1255           exit(1);
1256         }
1257 #else /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1258         /* XXX - just treat it as a number */
1259         capture_opts.linktype = get_natural_int(optarg, "data link type");
1260 #endif /* HAVE_PCAP_DATALINK_NAME_TO_VAL */
1261 #else
1262         capture_option_specified = TRUE;
1263         arg_error = TRUE;
1264 #endif
1265         break;
1266       case 'z':
1267         for(tli=tap_list;tli;tli=tli->next){
1268           if(!strncmp(tli->cmd,optarg,strlen(tli->cmd))){
1269             (*tli->func)(optarg);
1270             break;
1271           }
1272         }
1273         if(!tli){
1274           fprintf(stderr,"tethereal: invalid -z argument.\n");
1275           fprintf(stderr,"  -z argument must be one of :\n");
1276           for(tli=tap_list;tli;tli=tli->next){
1277             fprintf(stderr,"     %s\n",tli->cmd);
1278           }
1279           exit(1);
1280         }
1281         break;
1282       default:
1283       case '?':        /* Bad flag - print usage message */
1284         arg_error = TRUE;
1285         break;
1286     }
1287   }
1288
1289   /* If no capture filter or read filter has been specified, and there are
1290      still command-line arguments, treat them as the tokens of a capture
1291      filter (if no "-r" flag was specified) or a read filter (if a "-r"
1292      flag was specified. */
1293   if (optind < argc) {
1294     if (cf_name != NULL) {
1295       if (rfilter != NULL) {
1296         fprintf(stderr,
1297 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
1298         exit(2);
1299       }
1300       rfilter = get_args_as_string(argc, argv, optind);
1301     } else {
1302 #ifdef HAVE_LIBPCAP
1303       if (capture_filter_specified) {
1304         fprintf(stderr,
1305 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
1306         exit(2);
1307       }
1308       cfile.cfilter = get_args_as_string(argc, argv, optind);
1309 #else
1310       capture_option_specified = TRUE;
1311 #endif
1312     }
1313   }
1314
1315   /* See if we're writing a capture file and the file is a pipe */
1316 #ifdef HAVE_LIBPCAP
1317   ld.output_to_pipe = FALSE;
1318 #endif
1319   if (cfile.save_file != NULL) {
1320     /* We're writing to a capture file. */
1321     if (strcmp(cfile.save_file, "-") == 0) {
1322       /* Write to the standard output. */
1323       g_free(cfile.save_file);
1324       cfile.save_file = g_strdup("");
1325 #ifdef HAVE_LIBPCAP
1326       /* XXX - should we check whether it's a pipe?  It's arguably
1327          silly to do "-w - >output_file" rather than "-w output_file",
1328          but by not checking we might be violating the Principle Of
1329          Least Astonishment. */
1330       ld.output_to_pipe = TRUE;
1331 #endif
1332     }
1333 #ifdef HAVE_LIBPCAP
1334     else {
1335       err = test_for_fifo(cfile.save_file);
1336       switch (err) {
1337
1338       case ENOENT:      /* it doesn't exist, so we'll be creating it,
1339                            and it won't be a FIFO */
1340       case 0:           /* found it, but it's not a FIFO */
1341         break;
1342
1343       case ESPIPE:      /* it is a FIFO */
1344         ld.output_to_pipe = TRUE;
1345         break;
1346
1347       default:          /* couldn't stat it */
1348         fprintf(stderr,
1349                 "tethereal: Error testing whether capture file is a pipe: %s\n",
1350                 strerror(errno));
1351         exit(2);
1352       }
1353     }
1354 #endif
1355   } else {
1356     /* We're not writing to a file, so we should print packet information
1357        unless "-q" was specified. */
1358     if (!quiet)
1359       print_packet_info = TRUE;
1360   }
1361
1362 #ifndef HAVE_LIBPCAP
1363   if (capture_option_specified)
1364     fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1365 #endif
1366   if (arg_error) {
1367     print_usage(FALSE);
1368     exit(1);
1369   }
1370
1371   /* We don't support capture filters when reading from a capture file
1372      (the BPF compiler doesn't support all link-layer types that we
1373      support in capture files we read). */
1374 #ifdef HAVE_LIBPCAP
1375   if (cf_name != NULL) {
1376     if (capture_filter_specified) {
1377       fprintf(stderr,
1378 "tethereal: Only read filters, not capture filters, can be specified when reading a capture file.\n");
1379       exit(2);
1380     }
1381   }
1382 #endif
1383
1384   if (print_hex) {
1385     if (output_action != WRITE_TEXT) {
1386       fprintf(stderr, "tethereal: Raw packet hex data can only be printed as text or PostScript\n");
1387       exit(1);
1388     }
1389   }
1390
1391 #ifdef HAVE_LIBPCAP
1392   if (list_link_layer_types) {
1393     /* We're supposed to list the link-layer types for an interface;
1394        did the user also specify a capture file to be read? */
1395     if (cf_name) {
1396       /* Yes - that's bogus. */
1397       fprintf(stderr, "tethereal: You cannot specify -L and a capture file to be read.\n");
1398       exit(1);
1399     }
1400     /* No - did they specify a ring buffer option? */
1401     if (capture_opts.ringbuffer_on) {
1402       fprintf(stderr, "tethereal: Ring buffer requested, but a capture is not being done.\n");
1403       exit(1);
1404     }
1405   } else {
1406     /* If they didn't specify a "-w" flag, but specified a maximum capture
1407        file size, tell them that this doesn't work, and exit. */
1408     if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
1409       fprintf(stderr, "tethereal: Maximum capture file size specified, but "
1410         "capture isn't being saved to a file.\n");
1411       exit(1);
1412     }
1413
1414     if (capture_opts.ringbuffer_on) {
1415       /* Ring buffer works only under certain conditions:
1416          a) ring buffer does not work if you're not saving the capture to
1417             a file;
1418          b) ring buffer only works if you're saving in libpcap format;
1419          c) it makes no sense to enable the ring buffer if the maximum
1420             file size is set to "infinite";
1421          d) file must not be a pipe. */
1422       if (cfile.save_file == NULL) {
1423         fprintf(stderr, "tethereal: Ring buffer requested, but "
1424           "capture isn't being saved to a file.\n");
1425         exit(1);
1426       }
1427       if (out_file_type != WTAP_FILE_PCAP) {
1428         fprintf(stderr, "tethereal: Ring buffer requested, but "
1429           "capture isn't being saved in libpcap format.\n");
1430         exit(2);
1431       }
1432       if (!capture_opts.has_autostop_filesize) {
1433         fprintf(stderr, "tethereal: Ring buffer requested, but "
1434           "no maximum capture file size was specified.\n");
1435         exit(2);
1436       }
1437       if (ld.output_to_pipe) {
1438         fprintf(stderr, "tethereal: Ring buffer requested, but "
1439           "capture file is a pipe.\n");
1440         exit(2);
1441       }
1442     }
1443   }
1444 #endif
1445
1446 #ifdef _WIN32
1447   /* Start windows sockets */
1448   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1449 #endif  /* _WIN32 */
1450
1451   /* Notify all registered modules that have had any of their preferences
1452      changed either from one of the preferences file or from the command
1453      line that their preferences have changed. */
1454   prefs_apply_all();
1455
1456   /* disabled protocols as per configuration file */
1457   if (gdp_path == NULL && dp_path == NULL) {
1458     set_disabled_protos_list();
1459   }
1460
1461   /* Build the column format array */
1462   col_setup(&cfile.cinfo, prefs->num_cols);
1463   for (i = 0; i < cfile.cinfo.num_cols; i++) {
1464     cfile.cinfo.col_fmt[i] = get_column_format(i);
1465     cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1466     cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1467       NUM_COL_FMTS);
1468     get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1469     cfile.cinfo.col_data[i] = NULL;
1470     if (cfile.cinfo.col_fmt[i] == COL_INFO)
1471       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1472     else
1473       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1474     cfile.cinfo.col_fence[i] = 0;
1475     cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1476     cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1477   }
1478
1479   for (i = 0; i < cfile.cinfo.num_cols; i++) {
1480       int j;
1481
1482       for (j = 0; j < NUM_COL_FMTS; j++) {
1483          if (!cfile.cinfo.fmt_matx[i][j])
1484              continue;
1485          
1486          if (cfile.cinfo.col_first[j] == -1)
1487              cfile.cinfo.col_first[j] = i;
1488          cfile.cinfo.col_last[j] = i;
1489       }
1490   }
1491
1492 #ifdef HAVE_LIBPCAP
1493   if (capture_opts.snaplen < 1)
1494     capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
1495   else if (capture_opts.snaplen < MIN_PACKET_SIZE)
1496     capture_opts.snaplen = MIN_PACKET_SIZE;
1497
1498   /* Check the value range of the ringbuffer_num_files parameter */
1499   if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
1500     capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
1501 #if RINGBUFFER_MIN_NUM_FILES > 0
1502   else if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
1503     capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
1504 #endif
1505 #endif
1506
1507   if (rfilter != NULL) {
1508     if (!dfilter_compile(rfilter, &rfcode)) {
1509       fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
1510       epan_cleanup();
1511 #ifdef HAVE_PCAP_OPEN_DEAD
1512       {
1513         pcap_t *pc;
1514
1515         pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1516         if (pc != NULL) {
1517           if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1518             fprintf(stderr,
1519               "  Note: That display filter code looks like a valid capture filter;\n"
1520               "        maybe you mixed them up?\n");
1521           }
1522           pcap_close(pc);
1523         }
1524       }
1525 #endif
1526       exit(2);
1527     }
1528   }
1529   cfile.rfcode = rfcode;
1530
1531   if (print_packet_info) {
1532     /* If we're printing as text or PostScript, we have
1533        to create a print stream. */
1534     if (output_action == WRITE_TEXT) {
1535       switch (print_format) {
1536
1537       case PR_FMT_TEXT:
1538         print_stream = print_stream_text_stdio_new(stdout);
1539         break;
1540
1541       case PR_FMT_PS:
1542         print_stream = print_stream_ps_stdio_new(stdout);
1543         break;
1544
1545       default:
1546         g_assert_not_reached();
1547       }
1548     }
1549   }
1550
1551   /* We have to dissect each packet if:
1552
1553         we're printing information about each packet;
1554
1555         we're using a read filter on the packets;
1556
1557         we're using any taps. */
1558   do_dissection = print_packet_info || rfcode || have_tap_listeners();
1559
1560   if (cf_name) {
1561     /*
1562      * We're reading a capture file.
1563      */
1564
1565 #ifndef _WIN32
1566     /*
1567      * Immediately relinquish any set-UID or set-GID privileges we have;
1568      * we must not be allowed to read any capture files the user running
1569      * Tethereal can't open.
1570      */
1571     setuid(getuid());
1572     setgid(getgid());
1573 #endif
1574
1575     err = cf_open(cf_name, FALSE, &cfile);
1576     if (err != 0) {
1577       epan_cleanup();
1578       exit(2);
1579     }
1580     err = load_cap_file(&cfile, out_file_type);
1581     if (err != 0) {
1582       epan_cleanup();
1583       exit(2);
1584     }
1585     cf_name[0] = '\0';
1586   } else {
1587     /* No capture file specified, so we're supposed to do a live capture
1588        (or get a list of link-layer types for a live capture device);
1589        do we have support for live captures? */
1590 #ifdef HAVE_LIBPCAP
1591
1592 #ifdef _WIN32
1593     if (!has_wpcap) {
1594         fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
1595         exit(2);
1596     }
1597 #endif
1598
1599     /* Yes; did the user specify an interface to use? */
1600     if (cfile.iface == NULL) {
1601         /* No - is a default specified in the preferences file? */
1602         if (prefs->capture_device != NULL) {
1603             /* Yes - use it. */
1604             if_text = strrchr(prefs->capture_device, ' ');
1605             if (if_text == NULL) {
1606                 cfile.iface = g_strdup(prefs->capture_device);
1607             } else {
1608                 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
1609             }
1610         } else {
1611             /* No - pick the first one from the list of interfaces. */
1612             if_list = get_interface_list(&err, err_str);
1613             if (if_list == NULL) {
1614                 switch (err) {
1615
1616                 case CANT_GET_INTERFACE_LIST:
1617                     cant_get_if_list_errstr =
1618                         cant_get_if_list_error_message(err_str);
1619                     fprintf(stderr, "tethereal: %s\n", cant_get_if_list_errstr);
1620                     g_free(cant_get_if_list_errstr);
1621                     break;
1622
1623                 case NO_INTERFACES_FOUND:
1624                     fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
1625                     break;
1626                 }
1627                 exit(2);
1628             }
1629             if_info = if_list->data;    /* first interface */
1630             cfile.iface = g_strdup(if_info->name);
1631             free_interface_list(if_list);
1632         }
1633     }
1634
1635     if (list_link_layer_types) {
1636       /* We were asked to list the link-layer types for an interface.
1637          Get the list of link-layer types for the capture device. */
1638       lt_list = get_pcap_linktype_list(cfile.iface, err_str);
1639       if (lt_list == NULL) {
1640         if (err_str[0] != '\0') {
1641           fprintf(stderr, "tethereal: The list of data link types for the capture device could not be obtained (%s).\n"
1642             "Please check to make sure you have sufficient permissions, and that\n"
1643             "you have the proper interface or pipe specified.\n", err_str);
1644         } else
1645           fprintf(stderr, "tethereal: The capture device has no data link types.\n");
1646         exit(2);
1647       }
1648       fprintf(stderr, "Data link types (use option -y to set):\n");
1649       for (lt_entry = lt_list; lt_entry != NULL;
1650            lt_entry = g_list_next(lt_entry)) {
1651         data_link_info = lt_entry->data;
1652         fprintf(stderr, "  %s", data_link_info->name);
1653         if (data_link_info->description != NULL)
1654           fprintf(stderr, " (%s)", data_link_info->description);
1655         else
1656           fprintf(stderr, " (not supported)");
1657         putchar('\n');
1658       }
1659       free_pcap_linktype_list(lt_list);
1660       exit(0);
1661     }
1662
1663     capture(out_file_type);
1664
1665     if (capture_opts.ringbuffer_on) {
1666       ringbuf_free();
1667     }
1668 #else
1669     /* No - complain. */
1670     fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
1671     exit(2);
1672 #endif
1673   }
1674
1675   draw_tap_listeners(TRUE);
1676   epan_cleanup();
1677
1678   return 0;
1679 }
1680
1681 #ifdef HAVE_LIBPCAP
1682 /* Do the low-level work of a capture.
1683    Returns TRUE if it succeeds, FALSE otherwise. */
1684
1685 static condition  *volatile cnd_ring_timeout = NULL; /* this must be visible in process_packet */
1686
1687 static int
1688 capture(int out_file_type)
1689 {
1690   int         pcap_encap;
1691   int         file_snaplen;
1692   gchar       open_err_str[PCAP_ERRBUF_SIZE];
1693   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
1694   bpf_u_int32 netnum, netmask;
1695   struct bpf_program fcode;
1696   const char *set_linktype_err_str;
1697   int         err = 0;
1698   int         volatile volatile_err = 0;
1699   int         volatile inpkts = 0;
1700   int         pcap_cnt;
1701   char        errmsg[1024+1];
1702   condition  *volatile cnd_stop_capturesize = NULL;
1703   condition  *volatile cnd_stop_timeout = NULL;
1704 #ifndef _WIN32
1705   void        (*oldhandler)(int);
1706   static const char ppamsg[] = "can't find PPA for ";
1707   char       *libpcap_warn;
1708   volatile int pipe_fd = -1;
1709   struct pcap_hdr hdr;
1710   struct pcaprec_modified_hdr rechdr;
1711   guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1712 #endif
1713   struct pcap_stat stats;
1714   gboolean    write_err;
1715   gboolean    dump_ok;
1716   dfilter_t   *rfcode = NULL;
1717
1718   /* Initialize all data structures used for dissection. */
1719   init_dissection();
1720
1721   ld.linktype       = WTAP_ENCAP_UNKNOWN;
1722   ld.pdh            = NULL;
1723
1724   /* Open the network interface to capture from it.
1725      Some versions of libpcap may put warnings into the error buffer
1726      if they succeed; to tell if that's happened, we have to clear
1727      the error buffer, and check if it's still a null string.  */
1728   open_err_str[0] = '\0';
1729   ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
1730                           capture_opts.promisc_mode, 1000, open_err_str);
1731
1732   if (ld.pch != NULL) {
1733     /* setting the data link type only works on real interfaces */
1734     if (capture_opts.linktype != -1) {
1735       set_linktype_err_str = set_pcap_linktype(ld.pch, cfile.iface,
1736         capture_opts.linktype);
1737       if (set_linktype_err_str != NULL) {
1738         snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1739           set_linktype_err_str);
1740         goto error;
1741       }
1742     }
1743   } else {
1744     /* We couldn't open "cfile.iface" as a network device. */
1745 #ifdef _WIN32
1746     /* On Windows, we don't support capturing on pipes, so we give up. */
1747
1748     /* On Win32 OSes, the capture devices are probably available to all
1749        users; don't warn about permissions problems.
1750
1751        Do, however, warn that WAN devices aren't supported. */
1752     snprintf(errmsg, sizeof errmsg,
1753         "The capture session could not be initiated (%s).\n"
1754         "Please check that you have the proper interface specified.\n"
1755         "\n"
1756         "Note that the WinPcap 2.x version of the driver Ethereal uses for packet\n"
1757         "capture on Windows doesn't support capturing on PPP/WAN interfaces in\n"
1758         "Windows NT/2000/XP/2003 Server, and that the WinPcap 3.0 and later versions\n"
1759         "don't support capturing on PPP/WAN interfaces at all.\n",
1760         open_err_str);
1761     goto error;
1762 #else
1763     /* try to open cfile.iface as a pipe */
1764     pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1765
1766     if (pipe_fd == -1) {
1767
1768       if (ld.pipe_err == PIPNEXIST) {
1769         /* Pipe doesn't exist, so output message for interface */
1770
1771         /* If we got a "can't find PPA for XXX" message, warn the user (who
1772            is running Tethereal on HP-UX) that they don't have a version
1773            of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1774            versions, which properly handle HP-UX, say "can't find /dev/dlpi
1775            PPA for XXX" rather than "can't find PPA for XXX"). */
1776         if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1777           libpcap_warn =
1778             "\n\n"
1779             "You are running Tethereal with a version of the libpcap library\n"
1780             "that doesn't handle HP-UX network devices well; this means that\n"
1781             "Tethereal may not be able to capture packets.\n"
1782             "\n"
1783             "To fix this, you should install libpcap 0.6.2, or a later version\n"
1784             "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
1785             "packaged binary form from the Software Porting And Archive Centre\n"
1786             "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1787             "at the URL lists a number of mirror sites.";
1788         else
1789           libpcap_warn = "";
1790         snprintf(errmsg, sizeof errmsg,
1791           "The capture session could not be initiated (%s).\n"
1792           "Please check to make sure you have sufficient permissions, and that\n"
1793           "you have the proper interface or pipe specified.%s", open_err_str,
1794           libpcap_warn);
1795       }
1796       /*
1797        * Else pipe (or file) does exist and pipe_open_live() has
1798        * filled in errmsg
1799        */
1800       goto error;
1801     } else
1802       /* pipe_open_live() succeeded; don't want
1803          error message from pcap_open_live() */
1804       open_err_str[0] = '\0';
1805 #endif
1806   }
1807
1808 #ifndef _WIN32
1809   /*
1810    * We've opened the capture device, so, if we're set-UID or set-GID,
1811    * relinquish those privileges.
1812    *
1813    * XXX - if we have saved set-user-ID support, we should give up those
1814    * privileges immediately, and then reclaim them long enough to get
1815    * a list of network interfaces and to open one, and then give them
1816    * up again, so that stuff we do while processing the argument list,
1817    * reading the user's preferences, etc. is done as the real user and
1818    * group, not the effective user and group.
1819    */
1820   setuid(getuid());
1821   setgid(getgid());
1822 #endif
1823
1824   if (cfile.cfilter && !ld.from_pipe) {
1825     /* A capture filter was specified; set it up. */
1826     if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1827       /*
1828        * Well, we can't get the netmask for this interface; it's used
1829        * only for filters that check for broadcast IP addresses, so
1830        * we just warn the user, and punt and use 0.
1831        */
1832       fprintf(stderr,
1833         "Warning:  Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
1834       netmask = 0;
1835     }
1836     if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1837       if (dfilter_compile(cfile.cfilter, &rfcode)) {
1838         snprintf(errmsg, sizeof errmsg,
1839           "Unable to parse capture filter string (%s).\n"
1840           "  Interestingly enough, this looks like a valid display filter\n"
1841           "  Are you sure you didn't mix them up?",
1842           pcap_geterr(ld.pch));
1843       } else {
1844         snprintf(errmsg, sizeof errmsg,
1845           "Unable to parse capture filter string (%s).",
1846           pcap_geterr(ld.pch));
1847       }
1848       goto error;
1849     }
1850     if (pcap_setfilter(ld.pch, &fcode) < 0) {
1851       snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1852         pcap_geterr(ld.pch));
1853       goto error;
1854     }
1855   }
1856
1857   /* Set up to write to the capture file. */
1858 #ifndef _WIN32
1859   if (ld.from_pipe) {
1860     pcap_encap = hdr.network;
1861     file_snaplen = hdr.snaplen;
1862   } else
1863 #endif
1864   {
1865     pcap_encap = get_pcap_linktype(ld.pch, cfile.iface);
1866     file_snaplen = pcap_snapshot(ld.pch);
1867   }
1868   ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1869   if (cfile.save_file != NULL) {
1870     /* Set up to write to the capture file. */
1871     if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1872       strcpy(errmsg, "The network you're capturing from is of a type"
1873                " that Tethereal doesn't support.");
1874       goto error;
1875     }
1876     if (capture_opts.ringbuffer_on) {
1877       cfile.save_file_fd = ringbuf_init(cfile.save_file,
1878         capture_opts.ringbuffer_num_files);
1879       if (cfile.save_file_fd != -1) {
1880         ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
1881           file_snaplen, &err);
1882       } else {
1883         err = errno;    /* "ringbuf_init()" failed */
1884         ld.pdh = NULL;
1885       }
1886     } else {
1887       ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
1888                  ld.linktype, file_snaplen, &err);
1889     }
1890
1891     if (ld.pdh == NULL) {
1892       snprintf(errmsg, sizeof errmsg,
1893                cf_open_error_message(err, NULL, TRUE, out_file_type),
1894                *cfile.save_file == '\0' ? "stdout" : cfile.save_file);
1895       goto error;
1896     }
1897   }
1898
1899   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
1900      returned a warning; print it, but keep capturing. */
1901   if (open_err_str[0] != '\0')
1902     fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1903
1904 #ifdef _WIN32
1905   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1906   SetConsoleCtrlHandler(capture_cleanup, TRUE);
1907 #else /* _WIN32 */
1908   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1909      and exit.
1910      XXX - deal with signal semantics on various UNIX platforms.  Or just
1911      use "sigaction()" and be done with it? */
1912   signal(SIGTERM, capture_cleanup);
1913   signal(SIGINT, capture_cleanup);
1914   if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1915     signal(SIGHUP, oldhandler);
1916
1917 #ifdef SIGINFO
1918   /* Catch SIGINFO and, if we get it and we're capturing to a file in
1919      quiet mode, report the number of packets we've captured. */
1920   signal(SIGINFO, report_counts_siginfo);
1921 #endif /* SIGINFO */
1922 #endif /* _WIN32 */
1923
1924   /* Let the user know what interface was chosen. */
1925   fprintf(stderr, "Capturing on %s\n", cfile.iface);
1926
1927   /* initialize capture stop conditions */
1928   init_capture_stop_conditions();
1929   /* create stop conditions */
1930   if (capture_opts.has_autostop_filesize)
1931     cnd_stop_capturesize = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1932                                    (long)capture_opts.autostop_filesize * 1000);
1933   if (capture_opts.has_autostop_duration)
1934     cnd_stop_timeout = cnd_new((const char*)CND_CLASS_TIMEOUT,
1935                                (gint32)capture_opts.autostop_duration);
1936
1937   if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1938     cnd_ring_timeout = cnd_new(CND_CLASS_TIMEOUT, 
1939                                capture_opts.ringbuffer_duration);
1940
1941   if (!setjmp(ld.stopenv)) {
1942     ld.go = TRUE;
1943     ld.packet_count = 0;
1944   } else
1945     ld.go = FALSE;
1946   while (ld.go) {
1947     /* We need to be careful with automatic variables defined in the
1948        outer scope which are changed inside the loop.  Most compilers
1949        don't try to roll them back to their original values after the
1950        longjmp which causes the loop to finish, but all that the
1951        standards say is that their values are indeterminate.  If we
1952        don't want them to be rolled back, we should define them with the
1953        volatile attribute (paraphrasing W. Richard Stevens, Advanced
1954        Programming in the UNIX Environment, p. 178).
1955
1956        The "err" variable causes a particular problem.  If we give it
1957        the volatile attribute, then when we pass a reference to it (as
1958        in "&err") to a function, GCC warns: "passing arg <n> of
1959        <function> discards qualifiers from pointer target type".
1960        Therefore within the loop and just beyond we don't use "err".
1961        Within the loop we define "loop_err", and assign its value to
1962        "volatile_err", which is in the outer scope and is checked when
1963        the loop finishes.
1964
1965        We also define "packet_count_prev" here to keep things tidy,
1966        since it's used only inside the loop.  If it were defined in the
1967        outer scope, GCC would give a warning (unnecessary in this case)
1968        that it might be clobbered, and we'd need to give it the volatile
1969        attribute to suppress the warning. */
1970
1971     int loop_err = 0;
1972     int packet_count_prev = 0;
1973
1974     if (cnd_stop_capturesize == NULL && cnd_stop_timeout == NULL) {
1975       /* We're not stopping at a particular capture file size, and we're
1976          not stopping after some particular amount of time has expired,
1977          so either we have no stop condition or the only stop condition
1978          is a maximum packet count.
1979
1980          If there's no maximum packet count, pass it -1, meaning "until
1981          you run out of packets in the bufferful you read".  Otherwise,
1982          pass it the number of packets we have left to capture.
1983
1984          We don't call "pcap_loop()" as, if we're saving to a file that's
1985          a FIFO, we want to flush the FIFO after we're done processing
1986          this libpcap bufferful of packets, so that the program
1987          reading the FIFO sees the packets immediately and doesn't get
1988          any partial packet, forcing it to block in the middle of reading
1989          that packet. */
1990       if (capture_opts.autostop_count == 0)
1991         pcap_cnt = -1;
1992       else {
1993         if (ld.packet_count >= capture_opts.autostop_count) {
1994           /* XXX do we need this test here? */
1995           /* It appears there's nothing more to capture. */
1996           break;
1997         }
1998         pcap_cnt = capture_opts.autostop_count - ld.packet_count;
1999       }
2000     } else {
2001       /* We need to check the capture file size or the timeout after
2002          each packet. */
2003       pcap_cnt = 1;
2004     }
2005 #ifndef _WIN32
2006     if (ld.from_pipe) {
2007       inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
2008         errmsg, sizeof errmsg);
2009     } else
2010 #endif
2011       inpkts = pcap_dispatch(ld.pch, pcap_cnt, capture_pcap_cb, (guchar *) &ld);
2012     if (inpkts < 0) {
2013       /* Error from "pcap_dispatch()", or error or "no more packets" from
2014          "pipe_dispatch(). */
2015       ld.go = FALSE;
2016     } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
2017       /* The specified capture time has elapsed; stop the capture. */
2018       ld.go = FALSE;
2019     } else if (inpkts > 0) {
2020       if (capture_opts.autostop_count != 0 &&
2021                  ld.packet_count >= capture_opts.autostop_count) {
2022         /* The specified number of packets have been captured and have
2023            passed both any capture filter in effect and any read filter
2024            in effect. */
2025         ld.go = FALSE;
2026       } else if (cnd_stop_capturesize != NULL &&
2027                     cnd_eval(cnd_stop_capturesize,
2028                               (guint32)wtap_get_bytes_dumped(ld.pdh))) {
2029         /* We're saving the capture to a file, and the capture file reached
2030            its maximum size. */
2031         if (capture_opts.ringbuffer_on) {
2032           /* Switch to the next ringbuffer file */
2033           if (ringbuf_switch_file(&cfile, &ld.pdh, &loop_err)) {
2034             /* File switch succeeded: reset the condition */
2035             cnd_reset(cnd_stop_capturesize);
2036             if (cnd_ring_timeout) {
2037               cnd_reset(cnd_ring_timeout);
2038             }
2039           } else {
2040             /* File switch failed: stop here */
2041             volatile_err = loop_err;
2042             ld.go = FALSE;
2043           }
2044         } else {
2045           /* No ringbuffer - just stop. */
2046           ld.go = FALSE;
2047         }
2048       }
2049       if (ld.output_to_pipe) {
2050         if (ld.packet_count > packet_count_prev) {
2051           if (fflush(wtap_dump_file(ld.pdh))) {
2052             volatile_err = errno;
2053             ld.go = FALSE;
2054           }
2055           packet_count_prev = ld.packet_count;
2056         }
2057       }
2058     } /* inpkts > 0 */
2059   } /* while (ld.go) */
2060
2061   /* delete stop conditions */
2062   if (cnd_stop_capturesize != NULL)
2063     cnd_delete(cnd_stop_capturesize);
2064   if (cnd_stop_timeout != NULL)
2065     cnd_delete(cnd_stop_timeout);
2066   if (cnd_ring_timeout != NULL)
2067     cnd_delete(cnd_ring_timeout);
2068
2069   if ((cfile.save_file != NULL) && !quiet) {
2070     /* We're saving to a file, which means we're printing packet counts
2071        to stderr if we are not running silent and deep.
2072        Send a newline so that we move to the line after the packet count. */
2073     fprintf(stderr, "\n");
2074   }
2075
2076   /* If we got an error while capturing, report it. */
2077   if (inpkts < 0) {
2078 #ifndef _WIN32
2079     if (ld.from_pipe) {
2080       if (ld.pipe_err == PIPERR) {
2081         fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2082           errmsg);
2083       }
2084     } else
2085 #endif
2086     {
2087       fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
2088           pcap_geterr(ld.pch));
2089     }
2090   }
2091
2092   if (volatile_err == 0)
2093     write_err = FALSE;
2094   else {
2095     show_capture_file_io_error(cfile.save_file, volatile_err, FALSE);
2096     write_err = TRUE;
2097   }
2098
2099   if (cfile.save_file != NULL) {
2100     /* We're saving to a file or files; close all files. */
2101     if (capture_opts.ringbuffer_on) {
2102       dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
2103     } else {
2104       dump_ok = wtap_dump_close(ld.pdh, &err);
2105     }
2106     /* If we've displayed a message about a write error, there's no point
2107        in displaying another message about an error on close. */
2108     if (!dump_ok && !write_err)
2109       show_capture_file_io_error(cfile.save_file, err, TRUE);
2110   }
2111
2112 #ifndef _WIN32
2113   if (ld.from_pipe && pipe_fd >= 0)
2114     close(pipe_fd);
2115   else
2116 #endif
2117   {
2118     /* Get the capture statistics, and, if any packets were dropped, report
2119        that. */
2120     if (pcap_stats(ld.pch, &stats) >= 0) {
2121       if (stats.ps_drop != 0) {
2122         fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
2123       }
2124     } else {
2125       fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
2126           pcap_geterr(ld.pch));
2127     }
2128     pcap_close(ld.pch);
2129   }
2130
2131   /* Report the number of captured packets if not reported during capture
2132      and we are saving to a file. */
2133   report_counts();
2134
2135   return TRUE;
2136
2137 error:
2138   if (capture_opts.ringbuffer_on) {
2139     ringbuf_error_cleanup();
2140   }
2141   g_free(cfile.save_file);
2142   cfile.save_file = NULL;
2143   fprintf(stderr, "tethereal: %s\n", errmsg);
2144 #ifndef _WIN32
2145   if (ld.from_pipe) {
2146     if (pipe_fd >= 0)
2147       close(pipe_fd);
2148   } else
2149 #endif
2150   {
2151   if (ld.pch != NULL)
2152     pcap_close(ld.pch);
2153   }
2154
2155   return FALSE;
2156 }
2157
2158 static void
2159 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2160   const guchar *pd)
2161 {
2162   struct wtap_pkthdr whdr;
2163   union wtap_pseudo_header pseudo_header;
2164   loop_data *ldat = (loop_data *) user;
2165   int loop_err;
2166   int err;
2167
2168   /* Convert from libpcap to Wiretap format.
2169      If that fails, ignore the packet (wtap_process_pcap_packet has
2170      written an error message). */
2171   pd = wtap_process_pcap_packet(ldat->linktype, phdr, pd, &pseudo_header,
2172                                 &whdr, &err);
2173   if (pd == NULL)
2174     return;
2175
2176 #ifdef SIGINFO
2177   /*
2178    * Prevent a SIGINFO handler from writing to stdout while we're
2179    * doing so; instead, have it just set a flag telling us to print
2180    * that information when we're done.
2181    */
2182   infodelay = TRUE;
2183 #endif /* SIGINFO */
2184
2185   /* The current packet may have arrived after a very long silence,
2186    * way past the time to switch files.  In order not to have
2187    * the first packet of a new series of events as the last
2188    * [or only] packet in the file, switch before writing!
2189    */
2190   if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
2191     /* time elapsed for this ring file, switch to the next */
2192     if (ringbuf_switch_file(&cfile, &ldat->pdh, &loop_err)) {
2193       /* File switch succeeded: reset the condition */
2194       cnd_reset(cnd_ring_timeout);
2195     } else {
2196       /* File switch failed: stop here */
2197       /* XXX - we should do something with "loop_err" */
2198       ldat->go = FALSE;
2199     }
2200   }
2201
2202   if (!process_packet(&cfile, ldat->pdh, 0, &whdr, &pseudo_header, pd, &err)) {
2203     /* Error writing to a capture file */
2204     if (!quiet) {
2205       /* We're capturing packets, so (if -q not specified) we're printing
2206          a count of packets captured; move to the line after the count. */
2207       fprintf(stderr, "\n");
2208     }
2209     show_capture_file_io_error(cfile.save_file, err, FALSE);
2210     pcap_close(ldat->pch);
2211     wtap_dump_close(ldat->pdh, &err);
2212     exit(2);
2213   }
2214
2215 #ifdef SIGINFO
2216   /*
2217    * Allow SIGINFO handlers to write.
2218    */
2219   infodelay = FALSE;
2220
2221   /*
2222    * If a SIGINFO handler asked us to write out capture counts, do so.
2223    */
2224   if (infoprint)
2225     report_counts();
2226 #endif /* SIGINFO */
2227 }
2228
2229 #ifdef _WIN32
2230 static BOOL WINAPI
2231 capture_cleanup(DWORD ctrltype _U_)
2232 {
2233   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2234      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2235      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2236      like SIGTERM at least when the machine's shutting down.
2237
2238      For now, we handle them all as indications that we should clean up
2239      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2240      way on UNIX.
2241
2242      However, as handlers run in a new thread, we can't just longjmp
2243      out; we have to set "ld.go" to FALSE, and must return TRUE so that
2244      no other handler - such as one that would terminate the process -
2245      gets called.
2246
2247      XXX - for some reason, typing ^C to Tethereal, if you run this in
2248      a Cygwin console window in at least some versions of Cygwin,
2249      causes Tethereal to terminate immediately; this routine gets
2250      called, but the main loop doesn't get a chance to run and
2251      exit cleanly, at least if this is compiled with Microsoft Visual
2252      C++ (i.e., it's a property of the Cygwin console window or Bash;
2253      it happens if Tethereal is not built with Cygwin - for all I know,
2254      building it with Cygwin may make the problem go away). */
2255   ld.go = FALSE;
2256   return TRUE;
2257 }
2258 #else
2259 static void
2260 capture_cleanup(int signum _U_)
2261 {
2262   /* Longjmp back to the starting point; "pcap_dispatch()", on many
2263      UNIX platforms, just keeps looping if it gets EINTR, so if we set
2264      "ld.go" to FALSE and return, we won't break out of it and quit
2265      capturing. */
2266   longjmp(ld.stopenv, 1);
2267 }
2268 #endif /* _WIN32 */
2269
2270 static void
2271 report_counts(void)
2272 {
2273 #ifdef SIGINFO
2274   /* XXX - if we use sigaction, this doesn't have to be done.
2275      (Yes, this isn't necessary on BSD, but just in case a system
2276      where "signal()" has AT&T semantics adopts SIGINFO....) */
2277   signal(SIGINFO, report_counts_siginfo);
2278 #endif /* SIGINFO */
2279
2280   if (quiet || print_packet_info) {
2281     /* Report the count only if we aren't printing a packet count
2282        as packets arrive. */
2283     fprintf(stderr, "%u packets captured\n", ld.packet_count);
2284   }
2285 #ifdef SIGINFO
2286   infoprint = FALSE;    /* we just reported it */
2287 #endif /* SIGINFO */
2288 }
2289
2290 #ifdef SIGINFO
2291 static void
2292 report_counts_siginfo(int signum _U_)
2293 {
2294   int sav_errno = errno;
2295   /* If we've been told to delay printing, just set a flag asking
2296      that we print counts (if we're supposed to), otherwise print
2297      the count of packets captured (if we're supposed to). */
2298   if (infodelay)
2299     infoprint = TRUE;
2300   else
2301     report_counts();
2302   errno = sav_errno;
2303 }
2304 #endif /* SIGINFO */
2305 #endif /* HAVE_LIBPCAP */
2306
2307 static int
2308 load_cap_file(capture_file *cf, int out_file_type)
2309 {
2310   gint         linktype;
2311   int          snapshot_length;
2312   wtap_dumper *pdh;
2313   int          err;
2314   gchar        *err_info;
2315   long         data_offset;
2316
2317   linktype = wtap_file_encap(cf->wth);
2318   if (cf->save_file != NULL) {
2319     /* Set up to write to the capture file. */
2320     snapshot_length = wtap_snapshot_length(cf->wth);
2321     if (snapshot_length == 0) {
2322       /* Snapshot length of input file not known. */
2323       snapshot_length = WTAP_MAX_PACKET_SIZE;
2324     }
2325     pdh = wtap_dump_open(cf->save_file, out_file_type,
2326                 linktype, snapshot_length, &err);
2327
2328     if (pdh == NULL) {
2329       /* We couldn't set up to write to the capture file. */
2330       switch (err) {
2331
2332       case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2333         fprintf(stderr,
2334                 "tethereal: Capture files can't be written in that format.\n");
2335         break;
2336
2337       case WTAP_ERR_UNSUPPORTED_ENCAP:
2338       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2339         fprintf(stderr,
2340           "tethereal: The capture file being read cannot be written in "
2341           "that format.\n");
2342         break;
2343
2344       case WTAP_ERR_CANT_OPEN:
2345         fprintf(stderr,
2346           "tethereal: The file \"%s\" couldn't be created for some "
2347           "unknown reason.\n",
2348             *cf->save_file == '\0' ? "stdout" : cf->save_file);
2349         break;
2350
2351       case WTAP_ERR_SHORT_WRITE:
2352         fprintf(stderr,
2353           "tethereal: A full header couldn't be written to the file \"%s\".\n",
2354                 *cf->save_file == '\0' ? "stdout" : cf->save_file);
2355         break;
2356
2357       default:
2358         fprintf(stderr,
2359           "tethereal: The file \"%s\" could not be created: %s\n.",
2360                 *cf->save_file == '\0' ? "stdout" : cf->save_file,
2361                 wtap_strerror(err));
2362         break;
2363       }
2364       goto out;
2365     }
2366   } else {
2367     if (print_packet_info) {
2368       if (!write_preamble(cf)) {
2369         err = errno;
2370         show_print_file_io_error(err);
2371         goto out;
2372       }
2373     }
2374     pdh = NULL;
2375   }
2376   while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2377     if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
2378                         wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2379                         &err)) {
2380       /* Error writing to a capture file */
2381       show_capture_file_io_error(cf->save_file, err, FALSE);
2382       wtap_dump_close(pdh, &err);
2383       exit(2);
2384     }
2385   }
2386   if (err != 0) {
2387     /* Print a message noting that the read failed somewhere along the line. */
2388     switch (err) {
2389
2390     case WTAP_ERR_UNSUPPORTED_ENCAP:
2391       fprintf(stderr,
2392 "tethereal: \"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)\n",
2393         cf->filename, err_info);
2394       break;
2395
2396     case WTAP_ERR_CANT_READ:
2397       fprintf(stderr,
2398 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2399         cf->filename);
2400       break;
2401
2402     case WTAP_ERR_SHORT_READ:
2403       fprintf(stderr,
2404 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2405         cf->filename);
2406       break;
2407
2408     case WTAP_ERR_BAD_RECORD:
2409       fprintf(stderr,
2410 "tethereal: \"%s\" appears to be damaged or corrupt.\n(%s)\n",
2411         cf->filename, err_info);
2412       break;
2413
2414     default:
2415       fprintf(stderr,
2416 "tethereal: An error occurred while reading \"%s\": %s.\n",
2417         cf->filename, wtap_strerror(err));
2418       break;
2419     }
2420     if (cf->save_file != NULL) {
2421       /* Now close the capture file. */
2422       if (!wtap_dump_close(pdh, &err))
2423         show_capture_file_io_error(cfile.save_file, err, TRUE);
2424     }
2425   } else {
2426     if (cf->save_file != NULL) {
2427       /* Now close the capture file. */
2428       if (!wtap_dump_close(pdh, &err))
2429         show_capture_file_io_error(cfile.save_file, err, TRUE);
2430     } else {
2431       if (print_packet_info) {
2432         if (!write_finale()) {
2433           err = errno;
2434           show_print_file_io_error(err);
2435         }
2436       }
2437     }
2438   }
2439
2440 out:
2441   wtap_close(cf->wth);
2442   cf->wth = NULL;
2443
2444   return err;
2445 }
2446
2447 static void
2448 fill_in_fdata(frame_data *fdata, capture_file *cf,
2449         const struct wtap_pkthdr *phdr, long offset)
2450 {
2451   fdata->next = NULL;
2452   fdata->prev = NULL;
2453   fdata->pfd = NULL;
2454   fdata->num = cf->count;
2455   fdata->pkt_len = phdr->len;
2456   cum_bytes += phdr->len;
2457   fdata->cum_bytes  = cum_bytes;
2458   fdata->cap_len = phdr->caplen;
2459   fdata->file_off = offset;
2460   fdata->lnk_t = phdr->pkt_encap;
2461   fdata->abs_secs  = phdr->ts.tv_sec;
2462   fdata->abs_usecs = phdr->ts.tv_usec;
2463   fdata->flags.passed_dfilter = 0;
2464   fdata->flags.encoding = CHAR_ASCII;
2465   fdata->flags.visited = 0;
2466   fdata->flags.marked = 0;
2467   fdata->flags.ref_time = 0;
2468
2469   /* If we don't have the time stamp of the first packet in the
2470      capture, it's because this is the first packet.  Save the time
2471      stamp of this packet as the time stamp of the first packet. */
2472   if (!firstsec && !firstusec) {
2473     firstsec  = fdata->abs_secs;
2474     firstusec = fdata->abs_usecs;
2475   }
2476
2477   /* If we don't have the time stamp of the previous displayed packet,
2478      it's because this is the first displayed packet.  Save the time
2479      stamp of this packet as the time stamp of the previous displayed
2480      packet. */
2481   if (!prevsec && !prevusec) {
2482     prevsec  = fdata->abs_secs;
2483     prevusec = fdata->abs_usecs;
2484   }
2485
2486   /* Get the time elapsed between the first packet and this packet. */
2487   compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
2488                 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
2489
2490   /* If it's greater than the current elapsed time, set the elapsed time
2491      to it (we check for "greater than" so as not to be confused by
2492      time moving backwards). */
2493   if ((gint32)cf->esec < fdata->rel_secs
2494         || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
2495     cf->esec = fdata->rel_secs;
2496     cf->eusec = fdata->rel_usecs;
2497   }
2498
2499   /* Get the time elapsed between the previous displayed packet and
2500      this packet. */
2501   compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
2502                 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
2503   prevsec = fdata->abs_secs;
2504   prevusec = fdata->abs_usecs;
2505 }
2506
2507 /* Free up all data attached to a "frame_data" structure. */
2508 static void
2509 clear_fdata(frame_data *fdata)
2510 {
2511   if (fdata->pfd)
2512     g_slist_free(fdata->pfd);
2513 }
2514
2515 static gboolean
2516 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2517                const struct wtap_pkthdr *whdr,
2518                union wtap_pseudo_header *pseudo_header, const guchar *pd,
2519                int *err)
2520 {
2521   frame_data fdata;
2522   gboolean create_proto_tree;
2523   epan_dissect_t *edt;
2524   gboolean passed;
2525
2526   /* Count this packet. */
2527   cf->count++;
2528
2529   /* If we're going to print packet information, or we're going to
2530      run a read filter, or we're going to process taps, set up to
2531      do a dissection and do so. */
2532   if (do_dissection) {
2533     fill_in_fdata(&fdata, cf, whdr, offset);
2534
2535     if (print_packet_info) {
2536       /* Grab any resolved addresses */
2537     
2538       if (g_resolv_flags) {
2539         host_name_lookup_process(NULL);
2540       }
2541     }
2542
2543     passed = TRUE;
2544     if (cf->rfcode || verbose || num_tap_filters!=0)
2545       create_proto_tree = TRUE;
2546     else
2547       create_proto_tree = FALSE;
2548     /* The protocol tree will be "visible", i.e., printed, only if we're
2549        printing packet details, which is true if we're printing stuff
2550        ("print_packet_info" is true) and we're in verbose mode ("verbose"
2551        is true). */
2552     edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2553
2554     /* If we're running a read filter, prime the epan_dissect_t with that
2555        filter. */
2556     if (cf->rfcode)
2557       epan_dissect_prime_dfilter(edt, cf->rfcode);
2558
2559     tap_queue_init(edt);
2560
2561     /* We only need the columns if we're printing packet info but we're
2562        *not* verbose; in verbose mode, we print the protocol tree, not
2563        the protocol summary. */
2564     epan_dissect_run(edt, pseudo_header, pd, &fdata,
2565                      (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2566
2567     tap_push_tapped_queue(edt);
2568
2569     /* Run the read filter if we have one. */
2570     if (cf->rfcode)
2571       passed = dfilter_apply_edt(cf->rfcode, edt);
2572     else
2573       passed = TRUE;
2574   } else {
2575     /* We're not running a display filter and we're not printing any
2576        packet information, so we don't need to do a dissection, and all
2577        packets are processed. */
2578     edt = NULL;
2579     passed = TRUE;
2580   }
2581
2582   if (passed) {
2583     /* Count this packet. */
2584 #ifdef HAVE_LIBPCAP
2585     ld.packet_count++;
2586 #endif
2587
2588     /* Process this packet. */
2589     if (pdh != NULL) {
2590       /* We're writing to a capture file; write this packet. */
2591       if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2592         return FALSE;
2593 #ifdef HAVE_LIBPCAP
2594       /* Report packet capture count if not quiet */
2595       if (!quiet && !print_packet_info) {
2596         /* Don't print a packet count if we were asked not to with "-q"
2597            or if we're also printing packet info. */
2598         if (ld.packet_count != 0) {
2599           fprintf(stderr, "\r%u ", ld.packet_count);
2600           /* stderr could be line buffered */
2601           fflush(stderr);
2602         }
2603       }
2604 #endif
2605     }
2606     if (print_packet_info) {
2607       /* We're printing packet information; print the information for
2608          this packet. */
2609       print_packet(cf, edt);
2610
2611       /* The ANSI C standard does not appear to *require* that a line-buffered
2612          stream be flushed to the host environment whenever a newline is
2613          written, it just says that, on such a stream, characters "are
2614          intended to be transmitted to or from the host environment as a
2615          block when a new-line character is encountered".
2616
2617          The Visual C++ 6.0 C implementation doesn't do what is intended;
2618          even if you set a stream to be line-buffered, it still doesn't
2619          flush the buffer at the end of every line.
2620
2621          So, if the "-l" flag was specified, we flush the standard output
2622          at the end of a packet.  This will do the right thing if we're
2623          printing packet summary lines, and, as we print the entire protocol
2624          tree for a single packet without waiting for anything to happen,
2625          it should be as good as line-buffered mode if we're printing
2626          protocol trees.  (The whole reason for the "-l" flag in either
2627          tcpdump or Tethereal is to allow the output of a live capture to
2628          be piped to a program or script and to have that script see the
2629          information for the packet as soon as it's printed, rather than
2630          having to wait until a standard I/O buffer fills up. */
2631       if (line_buffered)
2632         fflush(stdout);
2633
2634       if (ferror(stdout)) {
2635         show_print_file_io_error(errno);
2636         exit(2);
2637       }
2638     }
2639   }
2640
2641   if (do_dissection) {
2642     epan_dissect_free(edt);
2643     clear_fdata(&fdata);
2644   }
2645   return TRUE;
2646 }
2647
2648 static void
2649 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2650 {
2651   if (*fname == '\0')
2652     fname = "stdout";
2653
2654   switch (err) {
2655
2656   case ENOSPC:
2657     fprintf(stderr,
2658 "tethereal: Not all the packets could be written to \"%s\" because there is "
2659 "no space left on the file system.\n",
2660         fname);
2661     break;
2662
2663 #ifdef EDQUOT
2664   case EDQUOT:
2665     fprintf(stderr,
2666 "tethereal: Not all the packets could be written to \"%s\" because you are "
2667 "too close to, or over your disk quota.\n",
2668         fname);
2669   break;
2670 #endif
2671
2672   case WTAP_ERR_CANT_CLOSE:
2673     fprintf(stderr,
2674 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2675         fname);
2676     break;
2677
2678   case WTAP_ERR_SHORT_WRITE:
2679     fprintf(stderr,
2680 "tethereal: Not all the packets could be written to \"%s\".\n",
2681         fname);
2682     break;
2683
2684   default:
2685     if (is_close) {
2686       fprintf(stderr,
2687 "tethereal: \"%s\" could not be closed: %s.\n",
2688         fname, wtap_strerror(err));
2689     } else {
2690       fprintf(stderr,
2691 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2692         fname, wtap_strerror(err));
2693     }
2694     break;
2695   }
2696 }
2697
2698 static gboolean
2699 write_preamble(capture_file *cf)
2700 {
2701   switch (output_action) {
2702
2703   case WRITE_TEXT:
2704     return print_preamble(print_stream, cf->filename);
2705     break;
2706
2707   case WRITE_XML:
2708     if (verbose)
2709       write_pdml_preamble(stdout);
2710     else
2711       write_psml_preamble(stdout);
2712     return !ferror(stdout);
2713
2714   default:
2715     g_assert_not_reached();
2716     return FALSE;
2717   }
2718 }
2719
2720 static char *
2721 get_line_buf(size_t len)
2722 {
2723   static char *line_bufp = NULL;
2724   static size_t line_buf_len = 256;
2725   size_t new_line_buf_len;
2726
2727   for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2728        new_line_buf_len *= 2)
2729     ;
2730   if (line_bufp == NULL) {
2731     line_buf_len = new_line_buf_len;
2732     line_bufp = g_malloc(line_buf_len + 1);
2733   } else {
2734     if (new_line_buf_len > line_buf_len) {
2735       line_buf_len = new_line_buf_len;
2736       line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2737     }
2738   }
2739   return line_bufp;
2740 }
2741
2742 static gboolean
2743 print_columns(capture_file *cf)
2744 {
2745   char *line_bufp;
2746   int i;
2747   size_t buf_offset;
2748   size_t column_len;
2749
2750   line_bufp = get_line_buf(256);
2751   buf_offset = 0;
2752   *line_bufp = '\0';
2753   for (i = 0; i < cf->cinfo.num_cols; i++) {
2754     switch (cf->cinfo.col_fmt[i]) {
2755     case COL_NUMBER:
2756       /*
2757        * Don't print this if we're doing a live capture from a network
2758        * interface - if we're doing a live capture, you won't be
2759        * able to look at the capture in the future (it's not being
2760        * saved anywhere), so the frame numbers are unlikely to be
2761        * useful.
2762        *
2763        * (XXX - it might be nice to be able to save and print at
2764        * the same time, sort of like an "Update list of packets
2765        * in real time" capture in Ethereal.)
2766        */
2767       if (cf->iface != NULL)
2768         continue;
2769       column_len = strlen(cf->cinfo.col_data[i]);
2770       if (column_len < 3)
2771         column_len = 3;
2772       line_bufp = get_line_buf(buf_offset + column_len);
2773       sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2774       break;
2775
2776     case COL_CLS_TIME:
2777     case COL_REL_TIME:
2778     case COL_ABS_TIME:
2779     case COL_ABS_DATE_TIME:     /* XXX - wider */
2780       column_len = strlen(cf->cinfo.col_data[i]);
2781       if (column_len < 10)
2782         column_len = 10;
2783       line_bufp = get_line_buf(buf_offset + column_len);
2784       sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2785       break;
2786
2787     case COL_DEF_SRC:
2788     case COL_RES_SRC:
2789     case COL_UNRES_SRC:
2790     case COL_DEF_DL_SRC:
2791     case COL_RES_DL_SRC:
2792     case COL_UNRES_DL_SRC:
2793     case COL_DEF_NET_SRC:
2794     case COL_RES_NET_SRC:
2795     case COL_UNRES_NET_SRC:
2796       column_len = strlen(cf->cinfo.col_data[i]);
2797       if (column_len < 12)
2798         column_len = 12;
2799       line_bufp = get_line_buf(buf_offset + column_len);
2800       sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2801       break;
2802
2803     case COL_DEF_DST:
2804     case COL_RES_DST:
2805     case COL_UNRES_DST:
2806     case COL_DEF_DL_DST:
2807     case COL_RES_DL_DST:
2808     case COL_UNRES_DL_DST:
2809     case COL_DEF_NET_DST:
2810     case COL_RES_NET_DST:
2811     case COL_UNRES_NET_DST:
2812       column_len = strlen(cf->cinfo.col_data[i]);
2813       if (column_len < 12)
2814         column_len = 12;
2815       line_bufp = get_line_buf(buf_offset + column_len);
2816       sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2817       break;
2818
2819     default:
2820       column_len = strlen(cf->cinfo.col_data[i]);
2821       line_bufp = get_line_buf(buf_offset + column_len);
2822       strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2823       break;
2824     }
2825     buf_offset += column_len;
2826     if (i != cf->cinfo.num_cols - 1) {
2827       /*
2828        * This isn't the last column, so we need to print a
2829        * separator between this column and the next.
2830        *
2831        * If we printed a network source and are printing a
2832        * network destination of the same type next, separate
2833        * them with "->"; if we printed a network destination
2834        * and are printing a network source of the same type
2835        * next, separate them with "<-"; otherwise separate them
2836        * with a space.
2837        *
2838        * We add enough space to the buffer for " <- " or " -> ",
2839        * even if we're only adding " ".
2840        */
2841       line_bufp = get_line_buf(buf_offset + 4);
2842       switch (cf->cinfo.col_fmt[i]) {
2843
2844       case COL_DEF_SRC:
2845       case COL_RES_SRC:
2846       case COL_UNRES_SRC:
2847         switch (cf->cinfo.col_fmt[i + 1]) {
2848
2849         case COL_DEF_DST:
2850         case COL_RES_DST:
2851         case COL_UNRES_DST:
2852           strcat(line_bufp + buf_offset, " -> ");
2853           buf_offset += 4;
2854           break;
2855
2856         default:
2857           strcat(line_bufp + buf_offset, " ");
2858           buf_offset += 1;
2859           break;
2860         }
2861         break;
2862
2863       case COL_DEF_DL_SRC:
2864       case COL_RES_DL_SRC:
2865       case COL_UNRES_DL_SRC:
2866         switch (cf->cinfo.col_fmt[i + 1]) {
2867
2868         case COL_DEF_DL_DST:
2869         case COL_RES_DL_DST:
2870         case COL_UNRES_DL_DST:
2871           strcat(line_bufp + buf_offset, " -> ");
2872           buf_offset += 4;
2873           break;
2874
2875         default:
2876           strcat(line_bufp + buf_offset, " ");
2877           buf_offset += 1;
2878           break;
2879         }
2880         break;
2881
2882       case COL_DEF_NET_SRC:
2883       case COL_RES_NET_SRC:
2884       case COL_UNRES_NET_SRC:
2885         switch (cf->cinfo.col_fmt[i + 1]) {
2886
2887         case COL_DEF_NET_DST:
2888         case COL_RES_NET_DST:
2889         case COL_UNRES_NET_DST:
2890           strcat(line_bufp + buf_offset, " -> ");
2891           buf_offset += 4;
2892           break;
2893
2894         default:
2895           strcat(line_bufp + buf_offset, " ");
2896           buf_offset += 1;
2897           break;
2898         }
2899         break;
2900
2901       case COL_DEF_DST:
2902       case COL_RES_DST:
2903       case COL_UNRES_DST:
2904         switch (cf->cinfo.col_fmt[i + 1]) {
2905
2906         case COL_DEF_SRC:
2907         case COL_RES_SRC:
2908         case COL_UNRES_SRC:
2909           strcat(line_bufp + buf_offset, " <- ");
2910           buf_offset += 4;
2911           break;
2912
2913         default:
2914           strcat(line_bufp + buf_offset, " ");
2915           buf_offset += 1;
2916           break;
2917         }
2918         break;
2919
2920       case COL_DEF_DL_DST:
2921       case COL_RES_DL_DST:
2922       case COL_UNRES_DL_DST:
2923         switch (cf->cinfo.col_fmt[i + 1]) {
2924
2925         case COL_DEF_DL_SRC:
2926         case COL_RES_DL_SRC:
2927         case COL_UNRES_DL_SRC:
2928           strcat(line_bufp + buf_offset, " <- ");
2929           buf_offset += 4;
2930           break;
2931
2932         default:
2933           strcat(line_bufp + buf_offset, " ");
2934           buf_offset += 1;
2935           break;
2936         }
2937         break;
2938
2939       case COL_DEF_NET_DST:
2940       case COL_RES_NET_DST:
2941       case COL_UNRES_NET_DST:
2942         switch (cf->cinfo.col_fmt[i + 1]) {
2943
2944         case COL_DEF_NET_SRC:
2945         case COL_RES_NET_SRC:
2946         case COL_UNRES_NET_SRC:
2947           strcat(line_bufp + buf_offset, " <- ");
2948           buf_offset += 4;
2949           break;
2950
2951         default:
2952           strcat(line_bufp + buf_offset, " ");
2953           buf_offset += 1;
2954           break;
2955         }
2956         break;
2957
2958       default:
2959         strcat(line_bufp + buf_offset, " ");
2960         buf_offset += 1;
2961         break;
2962       }
2963     }
2964   }
2965   return print_line(print_stream, 0, line_bufp);
2966 }
2967
2968 static gboolean
2969 print_packet(capture_file *cf, epan_dissect_t *edt)
2970 {
2971   print_args_t  print_args;
2972
2973   if (verbose) {
2974     /* Print the information in the protocol tree. */
2975     switch (output_action) {
2976
2977     case WRITE_TEXT:
2978       print_args.to_file = TRUE;
2979       print_args.format = print_format;
2980       print_args.print_summary = !verbose;
2981       print_args.print_hex = verbose && print_hex;
2982       print_args.print_formfeed = FALSE;
2983       print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2984
2985       /* init the packet range */
2986       packet_range_init(&print_args.range);
2987
2988       if (!proto_tree_print(&print_args, edt, print_stream))
2989         return FALSE;
2990       if (!print_hex) {
2991         /* "print_hex_data()" will put out a leading blank line, as well
2992          as a trailing one; print one here, to separate the packets,
2993          only if "print_hex_data()" won't be called. */
2994         if (!print_line(print_stream, 0, ""))
2995           return FALSE;
2996       }
2997       break;
2998
2999     case WRITE_XML:
3000       proto_tree_write_pdml(edt, stdout);
3001       printf("\n");
3002       return !ferror(stdout);
3003     }
3004   } else {
3005     /* Just fill in the columns. */
3006     epan_dissect_fill_in_columns(edt);
3007
3008     /* Now print them. */
3009     switch (output_action) {
3010
3011     case WRITE_TEXT:
3012         if (!print_columns(cf))
3013           return FALSE;
3014         break;
3015
3016     case WRITE_XML:
3017         proto_tree_write_psml(edt, stdout);
3018         return !ferror(stdout);
3019     }
3020   }
3021   if (print_hex) {
3022     if (!print_hex_data(print_stream, edt))
3023       return FALSE;
3024     if (!print_line(print_stream, 0, ""))
3025       return FALSE;
3026   }
3027   return TRUE;
3028 }
3029
3030 static gboolean
3031 write_finale(void)
3032 {
3033   switch (output_action) {
3034
3035   case WRITE_TEXT:
3036     return print_finale(print_stream);
3037     break;
3038
3039   case WRITE_XML:
3040     if (verbose)
3041       write_pdml_finale(stdout);
3042     else
3043       write_psml_finale(stdout);
3044     return !ferror(stdout);
3045
3046   default:
3047     g_assert_not_reached();
3048     return FALSE;
3049   }
3050 }
3051
3052 static void
3053 show_print_file_io_error(int err)
3054 {
3055   switch (err) {
3056
3057   case ENOSPC:
3058     fprintf(stderr,
3059 "tethereal: Not all the packets could be printed because there is "
3060 "no space left on the file system.\n");
3061     break;
3062
3063 #ifdef EDQUOT
3064   case EDQUOT:
3065     fprintf(stderr,
3066 "tethereal: Not all the packets could be printed because you are "
3067 "too close to, or over your disk quota.\n");
3068   break;
3069 #endif
3070
3071   default:
3072     fprintf(stderr,
3073 "tethereal: An error occurred while printing packets: %s.\n",
3074       strerror(err));
3075     break;
3076   }
3077 }
3078
3079 static char *
3080 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3081                       int file_type)
3082 {
3083   char *errmsg;
3084   static char errmsg_errno[1024+1];
3085
3086   if (err < 0) {
3087     /* Wiretap error. */
3088     switch (err) {
3089
3090     case WTAP_ERR_NOT_REGULAR_FILE:
3091       errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3092       break;
3093
3094     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3095       /* Seen only when opening a capture file for reading. */
3096       errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
3097       break;
3098
3099     case WTAP_ERR_UNSUPPORTED:
3100       /* Seen only when opening a capture file for reading. */
3101       snprintf(errmsg_errno, sizeof(errmsg_errno),
3102                "The file \"%%s\" is not a capture file in a format Tethereal understands.\n"
3103                "(%s)", err_info);
3104       g_free(err_info);
3105       errmsg = errmsg_errno;
3106       break;
3107
3108     case WTAP_ERR_CANT_WRITE_TO_PIPE:
3109       /* Seen only when opening a capture file for writing. */
3110       snprintf(errmsg_errno, sizeof(errmsg_errno),
3111                "The file \"%%s\" is a pipe, and %s capture files cannot be "
3112                "written to a pipe.", wtap_file_type_string(file_type));
3113       errmsg = errmsg_errno;
3114       break;
3115
3116     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3117       /* Seen only when opening a capture file for writing. */
3118       errmsg = "Tethereal does not support writing capture files in that format.";
3119       break;
3120
3121     case WTAP_ERR_UNSUPPORTED_ENCAP:
3122       if (for_writing)
3123         errmsg = "Tethereal cannot save this capture in that format.";
3124       else {
3125         snprintf(errmsg_errno, sizeof(errmsg_errno),
3126                  "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
3127                  "(%s)", err_info);
3128         g_free(err_info);
3129         errmsg = errmsg_errno;
3130       }
3131       break;
3132
3133     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3134       if (for_writing)
3135         errmsg = "Tethereal cannot save this capture in that format.";
3136       else
3137         errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
3138       break;
3139
3140     case WTAP_ERR_BAD_RECORD:
3141       /* Seen only when opening a capture file for reading. */
3142       snprintf(errmsg_errno, sizeof(errmsg_errno),
3143                "The file \"%%s\" appears to be damaged or corrupt.\n"
3144                "(%s)", err_info);
3145       g_free(err_info);
3146       errmsg = errmsg_errno;
3147       break;
3148
3149     case WTAP_ERR_CANT_OPEN:
3150       if (for_writing)
3151         errmsg = "The file \"%s\" could not be created for some unknown reason.";
3152       else
3153         errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3154       break;
3155
3156     case WTAP_ERR_SHORT_READ:
3157       errmsg = "The file \"%s\" appears to have been cut short"
3158                " in the middle of a packet or other data.";
3159       break;
3160
3161     case WTAP_ERR_SHORT_WRITE:
3162       errmsg = "A full header couldn't be written to the file \"%s\".";
3163       break;
3164
3165     default:
3166       snprintf(errmsg_errno, sizeof(errmsg_errno),
3167                "The file \"%%s\" could not be %s: %s.",
3168                for_writing ? "created" : "opened",
3169                wtap_strerror(err));
3170       errmsg = errmsg_errno;
3171       break;
3172     }
3173   } else
3174     errmsg = file_open_error_message(err, for_writing);
3175   return errmsg;
3176 }
3177
3178 /*
3179  * Open/create errors are reported with an console message in Tethereal.
3180  */
3181 static void
3182 open_failure_message(const char *filename, int err, gboolean for_writing)
3183 {
3184   fprintf(stderr, "tethereal: ");
3185   fprintf(stderr, file_open_error_message(err, for_writing), filename);
3186   fprintf(stderr, "\n");
3187 }
3188
3189 int
3190 cf_open(char *fname, gboolean is_tempfile, capture_file *cf)
3191 {
3192   wtap       *wth;
3193   int         err;
3194   gchar       *err_info;
3195   char        err_msg[2048+1];
3196
3197   wth = wtap_open_offline(fname, &err, &err_info, FALSE);
3198   if (wth == NULL)
3199     goto fail;
3200
3201   /* The open succeeded.  Fill in the information for this file. */
3202
3203   /* Initialize all data structures used for dissection. */
3204   init_dissection();
3205
3206   cf->wth = wth;
3207   cf->filed = -1;       /* not used, but set it anyway */
3208   cf->f_len = 0;        /* not used, but set it anyway */
3209
3210   /* Set the file name because we need it to set the follow stream filter.
3211      XXX - is that still true?  We need it for other reasons, though,
3212      in any case. */
3213   cf->filename = g_strdup(fname);
3214
3215   /* Indicate whether it's a permanent or temporary file. */
3216   cf->is_tempfile = is_tempfile;
3217
3218   /* If it's a temporary capture buffer file, mark it as not saved. */
3219   cf->user_saved = !is_tempfile;
3220
3221   cf->cd_t      = wtap_file_type(cf->wth);
3222   cf->count     = 0;
3223   cf->drops_known = FALSE;
3224   cf->drops     = 0;
3225   cf->esec      = 0;
3226   cf->eusec     = 0;
3227   cf->snap      = wtap_snapshot_length(cf->wth);
3228   if (cf->snap == 0) {
3229     /* Snapshot length not known. */
3230     cf->has_snap = FALSE;
3231     cf->snap = WTAP_MAX_PACKET_SIZE;
3232   } else
3233     cf->has_snap = TRUE;
3234   firstsec = 0, firstusec = 0;
3235   prevsec = 0, prevusec = 0;
3236
3237   return (0);
3238
3239 fail:
3240   snprintf(err_msg, sizeof err_msg,
3241            cf_open_error_message(err, err_info, FALSE, 0), fname);
3242   fprintf(stderr, "tethereal: %s\n", err_msg);
3243   return (err);
3244 }
3245
3246 #ifdef HAVE_LIBPCAP
3247 #ifndef _WIN32
3248 /* Take care of byte order in the libpcap headers read from pipes.
3249  * (function taken from wiretap/libpcap.c) */
3250 static void
3251 adjust_header(loop_data *ldat, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
3252 {
3253   if (ldat->byte_swapped) {
3254     /* Byte-swap the record header fields. */
3255     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
3256     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
3257     rechdr->incl_len = BSWAP32(rechdr->incl_len);
3258     rechdr->orig_len = BSWAP32(rechdr->orig_len);
3259   }
3260
3261   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
3262      swapped, in order to match the BPF header layout.
3263
3264      Unfortunately, some files were, according to a comment in the "libpcap"
3265      source, written with version 2.3 in their headers but without the
3266      interchanged fields, so if "incl_len" is greater than "orig_len" - which
3267      would make no sense - we assume that we need to swap them.  */
3268   if (hdr->version_major == 2 &&
3269       (hdr->version_minor < 3 ||
3270        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
3271     guint32 temp;
3272
3273     temp = rechdr->orig_len;
3274     rechdr->orig_len = rechdr->incl_len;
3275     rechdr->incl_len = temp;
3276   }
3277 }
3278
3279 /* Mimic pcap_open_live() for pipe captures
3280  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
3281  * header.
3282  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
3283  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
3284 static int
3285 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ldat,
3286                  char *errmsg, int errmsgl)
3287 {
3288   struct stat pipe_stat;
3289   int         fd;
3290   guint32     magic;
3291   int         b;
3292   unsigned int bytes_read;
3293
3294   /*
3295    * XXX Tethereal blocks until we return
3296    */
3297   if (strcmp(pipename, "-") == 0)
3298     fd = 0; /* read from stdin */
3299   else {
3300     if (stat(pipename, &pipe_stat) < 0) {
3301       if (errno == ENOENT || errno == ENOTDIR)
3302         ldat->pipe_err = PIPNEXIST;
3303       else {
3304         snprintf(errmsg, errmsgl,
3305           "The capture session could not be initiated "
3306           "due to error on pipe: %s", strerror(errno));
3307         ldat->pipe_err = PIPERR;
3308       }
3309       return -1;
3310     }
3311     if (! S_ISFIFO(pipe_stat.st_mode)) {
3312       if (S_ISCHR(pipe_stat.st_mode)) {
3313         /*
3314          * Assume the user specified an interface on a system where
3315          * interfaces are in /dev.  Pretend we haven't seen it.
3316          */
3317          ldat->pipe_err = PIPNEXIST;
3318       } else {
3319         snprintf(errmsg, errmsgl,
3320             "The capture session could not be initiated because\n"
3321             "\"%s\" is neither an interface nor a pipe", pipename);
3322         ldat->pipe_err = PIPERR;
3323       }
3324       return -1;
3325     }
3326     fd = open(pipename, O_RDONLY);
3327     if (fd == -1) {
3328       snprintf(errmsg, errmsgl,
3329           "The capture session could not be initiated "
3330           "due to error on pipe open: %s", strerror(errno));
3331       ldat->pipe_err = PIPERR;
3332       return -1;
3333     }
3334   }
3335
3336   ldat->from_pipe = TRUE;
3337
3338   /* read the pcap header */
3339   bytes_read = 0;
3340   while (bytes_read < sizeof magic) {
3341     b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
3342     if (b <= 0) {
3343       if (b == 0)
3344         snprintf(errmsg, errmsgl, "End of file on pipe during open");
3345       else
3346         snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3347           strerror(errno));
3348       goto error;
3349     }
3350     bytes_read += b;
3351   }
3352
3353   switch (magic) {
3354   case PCAP_MAGIC:
3355     /* Host that wrote it has our byte order, and was running
3356        a program using either standard or ss990417 libpcap. */
3357     ldat->byte_swapped = FALSE;
3358     ldat->modified = FALSE;
3359     break;
3360   case PCAP_MODIFIED_MAGIC:
3361     /* Host that wrote it has our byte order, but was running
3362        a program using either ss990915 or ss991029 libpcap. */
3363     ldat->byte_swapped = FALSE;
3364     ldat->modified = TRUE;
3365     break;
3366   case PCAP_SWAPPED_MAGIC:
3367     /* Host that wrote it has a byte order opposite to ours,
3368        and was running a program using either standard or
3369        ss990417 libpcap. */
3370     ldat->byte_swapped = TRUE;
3371     ldat->modified = FALSE;
3372     break;
3373   case PCAP_SWAPPED_MODIFIED_MAGIC:
3374     /* Host that wrote it out has a byte order opposite to
3375        ours, and was running a program using either ss990915
3376        or ss991029 libpcap. */
3377     ldat->byte_swapped = TRUE;
3378     ldat->modified = TRUE;
3379     break;
3380   default:
3381     /* Not a "libpcap" type we know about. */
3382     snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
3383     goto error;
3384   }
3385
3386   /* Read the rest of the header */
3387   bytes_read = 0;
3388   while (bytes_read < sizeof(struct pcap_hdr)) {
3389     b = read(fd, ((char *)hdr)+bytes_read,
3390           sizeof(struct pcap_hdr) - bytes_read);
3391     if (b <= 0) {
3392       if (b == 0)
3393         snprintf(errmsg, errmsgl, "End of file on pipe during open");
3394       else
3395         snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3396           strerror(errno));
3397       goto error;
3398     }
3399     bytes_read += b;
3400   }
3401
3402   if (ldat->byte_swapped) {
3403     /* Byte-swap the header fields about which we care. */
3404     hdr->version_major = BSWAP16(hdr->version_major);
3405     hdr->version_minor = BSWAP16(hdr->version_minor);
3406     hdr->snaplen = BSWAP32(hdr->snaplen);
3407     hdr->network = BSWAP32(hdr->network);
3408   }
3409
3410   if (hdr->version_major < 2) {
3411     snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
3412     goto error;
3413   }
3414
3415   ldat->pipe_state = STATE_EXPECT_REC_HDR;
3416   ldat->pipe_err = PIPOK;
3417   return fd;
3418
3419 error:
3420   ldat->pipe_err = PIPERR;
3421   close(fd);
3422   return -1;
3423
3424 }
3425 /* We read one record from the pipe, take care of byte order in the record
3426  * header, write the record in the capture file, and update capture statistics. */
3427
3428 static int
3429 pipe_dispatch(int fd, loop_data *ldat, struct pcap_hdr *hdr,
3430                 struct pcaprec_modified_hdr *rechdr, guchar *data,
3431                 char *errmsg, int errmsgl)
3432 {
3433   struct pcap_pkthdr phdr;
3434   int b;
3435   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
3436           PD_ERR } result;
3437
3438   switch (ldat->pipe_state) {
3439
3440   case STATE_EXPECT_REC_HDR:
3441     ldat->bytes_to_read = ldat->modified ?
3442       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
3443     ldat->bytes_read = 0;
3444     ldat->pipe_state = STATE_READ_REC_HDR;
3445     /* Fall through */
3446
3447   case STATE_READ_REC_HDR:
3448     b = read(fd, ((char *)rechdr)+ldat->bytes_read,
3449       ldat->bytes_to_read - ldat->bytes_read);
3450     if (b <= 0) {
3451       if (b == 0)
3452         result = PD_PIPE_EOF;
3453       else
3454         result = PD_PIPE_ERR;
3455       break;
3456     }
3457     if ((ldat->bytes_read += b) < ldat->bytes_to_read)
3458         return 0;
3459     result = PD_REC_HDR_READ;
3460     break;
3461
3462   case STATE_EXPECT_DATA:
3463     ldat->bytes_read = 0;
3464     ldat->pipe_state = STATE_READ_DATA;
3465     /* Fall through */
3466
3467   case STATE_READ_DATA:
3468     b = read(fd, data+ldat->bytes_read, rechdr->hdr.incl_len - ldat->bytes_read);
3469     if (b <= 0) {
3470       if (b == 0)
3471         result = PD_PIPE_EOF;
3472       else
3473         result = PD_PIPE_ERR;
3474       break;
3475     }
3476     if ((ldat->bytes_read += b) < rechdr->hdr.incl_len)
3477       return 0;
3478     result = PD_DATA_READ;
3479     break;
3480
3481   default:
3482     snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
3483     result = PD_ERR;
3484
3485   } /* switch (ldat->pipe_state) */
3486
3487   /*
3488    * We've now read as much data as we were expecting, so process it.
3489    */
3490   switch (result) {
3491
3492   case PD_REC_HDR_READ:
3493     /* We've read the header. Take care of byte order. */
3494     adjust_header(ldat, hdr, &rechdr->hdr);
3495     if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
3496       snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
3497         ldat->packet_count+1, rechdr->hdr.incl_len);
3498       break;
3499     }
3500     ldat->pipe_state = STATE_EXPECT_DATA;
3501     return 0;
3502
3503   case PD_DATA_READ:
3504     /* Fill in a "struct pcap_pkthdr", and process the packet. */
3505     phdr.ts.tv_sec = rechdr->hdr.ts_sec;
3506     phdr.ts.tv_usec = rechdr->hdr.ts_usec;
3507     phdr.caplen = rechdr->hdr.incl_len;
3508     phdr.len = rechdr->hdr.orig_len;
3509
3510     capture_pcap_cb((guchar *)ldat, &phdr, data);
3511
3512     ldat->pipe_state = STATE_EXPECT_REC_HDR;
3513     return 1;
3514
3515   case PD_PIPE_EOF:
3516     ldat->pipe_err = PIPEOF;
3517     return -1;
3518
3519   case PD_PIPE_ERR:
3520     snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3521       strerror(errno));
3522     /* Fall through */
3523   case PD_ERR:
3524     break;
3525   }
3526
3527   ldat->pipe_err = PIPERR;
3528   /* Return here rather than inside the switch to prevent GCC warning */
3529   return -1;
3530 }
3531 #endif /* _WIN32 */
3532 #endif /* HAVE_LIBPCAP */
3533
3534 /*
3535  * General errors are reported with an console message in Tethereal.
3536  */
3537 static void
3538 failure_message(const char *msg_format, va_list ap)
3539 {
3540   fprintf(stderr, "tethereal: ");
3541   vfprintf(stderr, msg_format, ap);
3542   fprintf(stderr, "\n");
3543 }
3544
3545 /*
3546  * Read errors are reported with an console message in Tethereal.
3547  */
3548 static void
3549 read_failure_message(const char *filename, int err)
3550 {
3551   fprintf(stderr, "tethereal: An error occurred while reading from the file \"%s\": %s.\n",
3552           filename, strerror(err));
3553 }