Hoist the code for handling "-G" into a common module.
[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 "prefs.h"
87 #include "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 "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 *p;
1514
1515         p = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1516         if (p != NULL) {
1517           if (pcap_compile(p, &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(p);
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 *ld = (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(ld->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, &ld->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       ld->go = FALSE;
2199     }
2200   }
2201
2202   if (!process_packet(&cfile, ld->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(ld->pch);
2211     wtap_dump_close(ld->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 (!write_preamble(cf)) {
2368       err = errno;
2369       show_print_file_io_error(err);
2370       goto out;
2371     }
2372     pdh = NULL;
2373   }
2374   while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2375     if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
2376                         wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2377                         &err)) {
2378       /* Error writing to a capture file */
2379       show_capture_file_io_error(cf->save_file, err, FALSE);
2380       wtap_dump_close(pdh, &err);
2381       exit(2);
2382     }
2383   }
2384   if (err != 0) {
2385     /* Print a message noting that the read failed somewhere along the line. */
2386     switch (err) {
2387
2388     case WTAP_ERR_UNSUPPORTED_ENCAP:
2389       fprintf(stderr,
2390 "tethereal: \"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)\n",
2391         cf->filename, err_info);
2392       break;
2393
2394     case WTAP_ERR_CANT_READ:
2395       fprintf(stderr,
2396 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
2397         cf->filename);
2398       break;
2399
2400     case WTAP_ERR_SHORT_READ:
2401       fprintf(stderr,
2402 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
2403         cf->filename);
2404       break;
2405
2406     case WTAP_ERR_BAD_RECORD:
2407       fprintf(stderr,
2408 "tethereal: \"%s\" appears to be damaged or corrupt.\n(%s)\n",
2409         cf->filename, err_info);
2410       break;
2411
2412     default:
2413       fprintf(stderr,
2414 "tethereal: An error occurred while reading \"%s\": %s.\n",
2415         cf->filename, wtap_strerror(err));
2416       break;
2417     }
2418     if (cf->save_file != NULL) {
2419       /* Now close the capture file. */
2420       if (!wtap_dump_close(pdh, &err))
2421         show_capture_file_io_error(cfile.save_file, err, TRUE);
2422     }
2423   } else {
2424     if (cf->save_file != NULL) {
2425       /* Now close the capture file. */
2426       if (!wtap_dump_close(pdh, &err))
2427         show_capture_file_io_error(cfile.save_file, err, TRUE);
2428     } else {
2429       if (!write_finale()) {
2430         err = errno;
2431         show_print_file_io_error(err);
2432       }
2433     }
2434   }
2435
2436 out:
2437   wtap_close(cf->wth);
2438   cf->wth = NULL;
2439
2440   return err;
2441 }
2442
2443 static void
2444 fill_in_fdata(frame_data *fdata, capture_file *cf,
2445         const struct wtap_pkthdr *phdr, long offset)
2446 {
2447   fdata->next = NULL;
2448   fdata->prev = NULL;
2449   fdata->pfd = NULL;
2450   fdata->num = cf->count;
2451   fdata->pkt_len = phdr->len;
2452   cum_bytes += phdr->len;
2453   fdata->cum_bytes  = cum_bytes;
2454   fdata->cap_len = phdr->caplen;
2455   fdata->file_off = offset;
2456   fdata->lnk_t = phdr->pkt_encap;
2457   fdata->abs_secs  = phdr->ts.tv_sec;
2458   fdata->abs_usecs = phdr->ts.tv_usec;
2459   fdata->flags.passed_dfilter = 0;
2460   fdata->flags.encoding = CHAR_ASCII;
2461   fdata->flags.visited = 0;
2462   fdata->flags.marked = 0;
2463   fdata->flags.ref_time = 0;
2464
2465   /* If we don't have the time stamp of the first packet in the
2466      capture, it's because this is the first packet.  Save the time
2467      stamp of this packet as the time stamp of the first packet. */
2468   if (!firstsec && !firstusec) {
2469     firstsec  = fdata->abs_secs;
2470     firstusec = fdata->abs_usecs;
2471   }
2472
2473   /* If we don't have the time stamp of the previous displayed packet,
2474      it's because this is the first displayed packet.  Save the time
2475      stamp of this packet as the time stamp of the previous displayed
2476      packet. */
2477   if (!prevsec && !prevusec) {
2478     prevsec  = fdata->abs_secs;
2479     prevusec = fdata->abs_usecs;
2480   }
2481
2482   /* Get the time elapsed between the first packet and this packet. */
2483   compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
2484                 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
2485
2486   /* If it's greater than the current elapsed time, set the elapsed time
2487      to it (we check for "greater than" so as not to be confused by
2488      time moving backwards). */
2489   if ((gint32)cf->esec < fdata->rel_secs
2490         || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
2491     cf->esec = fdata->rel_secs;
2492     cf->eusec = fdata->rel_usecs;
2493   }
2494
2495   /* Get the time elapsed between the previous displayed packet and
2496      this packet. */
2497   compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
2498                 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
2499   prevsec = fdata->abs_secs;
2500   prevusec = fdata->abs_usecs;
2501 }
2502
2503 /* Free up all data attached to a "frame_data" structure. */
2504 static void
2505 clear_fdata(frame_data *fdata)
2506 {
2507   if (fdata->pfd)
2508     g_slist_free(fdata->pfd);
2509 }
2510
2511 static gboolean
2512 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2513                const struct wtap_pkthdr *whdr,
2514                union wtap_pseudo_header *pseudo_header, const guchar *pd,
2515                int *err)
2516 {
2517   frame_data fdata;
2518   gboolean create_proto_tree;
2519   epan_dissect_t *edt;
2520   gboolean passed;
2521
2522   /* Count this packet. */
2523   cf->count++;
2524
2525   /* If we're going to print packet information, or we're going to
2526      run a read filter, or we're going to process taps, set up to
2527      do a dissection and do so. */
2528   if (do_dissection) {
2529     fill_in_fdata(&fdata, cf, whdr, offset);
2530
2531     if (print_packet_info) {
2532       /* Grab any resolved addresses */
2533     
2534       if (g_resolv_flags) {
2535         host_name_lookup_process(NULL);
2536       }
2537     }
2538
2539     passed = TRUE;
2540     if (cf->rfcode || verbose || num_tap_filters!=0)
2541       create_proto_tree = TRUE;
2542     else
2543       create_proto_tree = FALSE;
2544     /* The protocol tree will be "visible", i.e., printed, only if we're
2545        printing packet details, which is true if we're printing stuff
2546        ("print_packet_info" is true) and we're in verbose mode ("verbose"
2547        is true). */
2548     edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2549
2550     /* If we're running a read filter, prime the epan_dissect_t with that
2551        filter. */
2552     if (cf->rfcode)
2553       epan_dissect_prime_dfilter(edt, cf->rfcode);
2554
2555     tap_queue_init(edt);
2556
2557     /* We only need the columns if we're printing packet info but we're
2558        *not* verbose; in verbose mode, we print the protocol tree, not
2559        the protocol summary. */
2560     epan_dissect_run(edt, pseudo_header, pd, &fdata,
2561                      (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2562
2563     tap_push_tapped_queue(edt);
2564
2565     /* Run the read filter if we have one. */
2566     if (cf->rfcode)
2567       passed = dfilter_apply_edt(cf->rfcode, edt);
2568     else
2569       passed = TRUE;
2570   } else {
2571     /* We're not running a display filter and we're not printing any
2572        packet information, so we don't need to do a dissection, and all
2573        packets are processed. */
2574     edt = NULL;
2575     passed = TRUE;
2576   }
2577
2578   if (passed) {
2579     /* Count this packet. */
2580 #ifdef HAVE_LIBPCAP
2581     ld.packet_count++;
2582 #endif
2583
2584     /* Process this packet. */
2585     if (pdh != NULL) {
2586       /* We're writing to a capture file; write this packet. */
2587       if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2588         return FALSE;
2589       /* Report packet capture count if not quiet */
2590       if (!quiet && !print_packet_info) {
2591         /* Don't print a packet count if we were asked not to with "-q"
2592            or if we're also printing packet info. */
2593         if (ld.packet_count != 0) {
2594           fprintf(stderr, "\r%u ", ld.packet_count);
2595           /* stderr could be line buffered */
2596           fflush(stderr);
2597         }
2598       }
2599     }
2600     if (print_packet_info) {
2601       /* We're printing packet information; print the information for
2602          this packet. */
2603       print_packet(cf, edt);
2604
2605       /* The ANSI C standard does not appear to *require* that a line-buffered
2606          stream be flushed to the host environment whenever a newline is
2607          written, it just says that, on such a stream, characters "are
2608          intended to be transmitted to or from the host environment as a
2609          block when a new-line character is encountered".
2610
2611          The Visual C++ 6.0 C implementation doesn't do what is intended;
2612          even if you set a stream to be line-buffered, it still doesn't
2613          flush the buffer at the end of every line.
2614
2615          So, if the "-l" flag was specified, we flush the standard output
2616          at the end of a packet.  This will do the right thing if we're
2617          printing packet summary lines, and, as we print the entire protocol
2618          tree for a single packet without waiting for anything to happen,
2619          it should be as good as line-buffered mode if we're printing
2620          protocol trees.  (The whole reason for the "-l" flag in either
2621          tcpdump or Tethereal is to allow the output of a live capture to
2622          be piped to a program or script and to have that script see the
2623          information for the packet as soon as it's printed, rather than
2624          having to wait until a standard I/O buffer fills up. */
2625       if (line_buffered)
2626         fflush(stdout);
2627
2628       if (ferror(stdout)) {
2629         show_print_file_io_error(errno);
2630         exit(2);
2631       }
2632     }
2633   }
2634
2635   if (do_dissection) {
2636     epan_dissect_free(edt);
2637     clear_fdata(&fdata);
2638   }
2639   return TRUE;
2640 }
2641
2642 static void
2643 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2644 {
2645   if (*fname == '\0')
2646     fname = "stdout";
2647
2648   switch (err) {
2649
2650   case ENOSPC:
2651     fprintf(stderr,
2652 "tethereal: Not all the packets could be written to \"%s\" because there is "
2653 "no space left on the file system.\n",
2654         fname);
2655     break;
2656
2657 #ifdef EDQUOT
2658   case EDQUOT:
2659     fprintf(stderr,
2660 "tethereal: Not all the packets could be written to \"%s\" because you are "
2661 "too close to, or over your disk quota.\n",
2662         fname);
2663   break;
2664 #endif
2665
2666   case WTAP_ERR_CANT_CLOSE:
2667     fprintf(stderr,
2668 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
2669         fname);
2670     break;
2671
2672   case WTAP_ERR_SHORT_WRITE:
2673     fprintf(stderr,
2674 "tethereal: Not all the packets could be written to \"%s\".\n",
2675         fname);
2676     break;
2677
2678   default:
2679     if (is_close) {
2680       fprintf(stderr,
2681 "tethereal: \"%s\" could not be closed: %s.\n",
2682         fname, wtap_strerror(err));
2683     } else {
2684       fprintf(stderr,
2685 "tethereal: An error occurred while writing to \"%s\": %s.\n",
2686         fname, wtap_strerror(err));
2687     }
2688     break;
2689   }
2690 }
2691
2692 static gboolean
2693 write_preamble(capture_file *cf)
2694 {
2695   switch (output_action) {
2696
2697   case WRITE_TEXT:
2698     return print_preamble(print_stream, cf->filename);
2699     break;
2700
2701   case WRITE_XML:
2702     if (verbose)
2703       write_pdml_preamble(stdout);
2704     else
2705       write_psml_preamble(stdout);
2706     return !ferror(stdout);
2707
2708   default:
2709     g_assert_not_reached();
2710     return FALSE;
2711   }
2712 }
2713
2714 static gboolean
2715 print_columns(capture_file *cf)
2716 {
2717   static char *line_bufp = NULL;
2718   static size_t line_buf_len = 0;
2719   int i;
2720   size_t buf_offset;
2721   size_t column_len;
2722
2723   if (line_bufp == NULL) {
2724     line_buf_len = 256;
2725     line_bufp = g_malloc(line_buf_len + 1);
2726   }
2727   buf_offset = 0;
2728   *line_bufp = '\0';
2729   for (i = 0; i < cf->cinfo.num_cols; i++) {
2730     switch (cf->cinfo.col_fmt[i]) {
2731     case COL_NUMBER:
2732       /*
2733        * Don't print this if we're doing a live capture from a network
2734        * interface - if we're doing a live capture, you won't be
2735        * able to look at the capture in the future (it's not being
2736        * saved anywhere), so the frame numbers are unlikely to be
2737        * useful.
2738        *
2739        * (XXX - it might be nice to be able to save and print at
2740        * the same time, sort of like an "Update list of packets
2741        * in real time" capture in Ethereal.)
2742        */
2743       if (cf->iface != NULL)
2744         continue;
2745       column_len = strlen(cf->cinfo.col_data[i]);
2746       if (column_len < 3)
2747         column_len = 3;
2748       if (buf_offset + column_len > line_buf_len) {
2749         line_buf_len *= 2;
2750         line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2751       }
2752       snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%3s", cf->cinfo.col_data[i]);
2753       break;
2754
2755     case COL_CLS_TIME:
2756     case COL_REL_TIME:
2757     case COL_ABS_TIME:
2758     case COL_ABS_DATE_TIME:     /* XXX - wider */
2759       column_len = strlen(cf->cinfo.col_data[i]);
2760       if (column_len < 10)
2761         column_len = 10;
2762       if (buf_offset + column_len > line_buf_len) {
2763         line_buf_len *= 2;
2764         line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2765       }
2766       snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%10s", cf->cinfo.col_data[i]);
2767       break;
2768
2769     case COL_DEF_SRC:
2770     case COL_RES_SRC:
2771     case COL_UNRES_SRC:
2772     case COL_DEF_DL_SRC:
2773     case COL_RES_DL_SRC:
2774     case COL_UNRES_DL_SRC:
2775     case COL_DEF_NET_SRC:
2776     case COL_RES_NET_SRC:
2777     case COL_UNRES_NET_SRC:
2778       column_len = strlen(cf->cinfo.col_data[i]);
2779       if (column_len < 12)
2780         column_len = 12;
2781       if (buf_offset + column_len > line_buf_len) {
2782         line_buf_len *= 2;
2783         line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2784       }
2785       snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%12s", cf->cinfo.col_data[i]);
2786       break;
2787
2788     case COL_DEF_DST:
2789     case COL_RES_DST:
2790     case COL_UNRES_DST:
2791     case COL_DEF_DL_DST:
2792     case COL_RES_DL_DST:
2793     case COL_UNRES_DL_DST:
2794     case COL_DEF_NET_DST:
2795     case COL_RES_NET_DST:
2796     case COL_UNRES_NET_DST:
2797       column_len = strlen(cf->cinfo.col_data[i]);
2798       if (column_len < 12)
2799         column_len = 12;
2800       if (buf_offset + column_len > line_buf_len) {
2801         line_buf_len *= 2;
2802         line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2803       }
2804       snprintf(line_bufp + buf_offset, COL_MAX_LEN+1, "%-12s", cf->cinfo.col_data[i]);
2805       break;
2806
2807     default:
2808       column_len = strlen(cf->cinfo.col_data[i]);
2809       if (buf_offset + column_len > line_buf_len) {
2810         line_buf_len *= 2;
2811         line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2812       }
2813       strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2814       break;
2815     }
2816     buf_offset += column_len;
2817     if (i != cf->cinfo.num_cols - 1) {
2818       /*
2819        * This isn't the last column, so we need to print a
2820        * separator between this column and the next.
2821        *
2822        * If we printed a network source and are printing a
2823        * network destination of the same type next, separate
2824        * them with "->"; if we printed a network destination
2825        * and are printing a network source of the same type
2826        * next, separate them with "<-"; otherwise separate them
2827        * with a space.
2828        *
2829        * We add enough space to the buffer for " <- " or " -> ",
2830        * even if we're only adding " ".
2831        */
2832       if (buf_offset + 4 > line_buf_len) {
2833         line_buf_len *= 2;
2834         line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2835       }
2836       switch (cf->cinfo.col_fmt[i]) {
2837
2838       case COL_DEF_SRC:
2839       case COL_RES_SRC:
2840       case COL_UNRES_SRC:
2841         switch (cf->cinfo.col_fmt[i + 1]) {
2842
2843         case COL_DEF_DST:
2844         case COL_RES_DST:
2845         case COL_UNRES_DST:
2846           strcat(line_bufp + buf_offset, " -> ");
2847           buf_offset += 4;
2848           break;
2849
2850         default:
2851           strcat(line_bufp + buf_offset, " ");
2852           buf_offset += 1;
2853           break;
2854         }
2855         break;
2856
2857       case COL_DEF_DL_SRC:
2858       case COL_RES_DL_SRC:
2859       case COL_UNRES_DL_SRC:
2860         switch (cf->cinfo.col_fmt[i + 1]) {
2861
2862         case COL_DEF_DL_DST:
2863         case COL_RES_DL_DST:
2864         case COL_UNRES_DL_DST:
2865           strcat(line_bufp + buf_offset, " -> ");
2866           buf_offset += 4;
2867           break;
2868
2869         default:
2870           strcat(line_bufp + buf_offset, " ");
2871           buf_offset += 1;
2872           break;
2873         }
2874         break;
2875
2876       case COL_DEF_NET_SRC:
2877       case COL_RES_NET_SRC:
2878       case COL_UNRES_NET_SRC:
2879         switch (cf->cinfo.col_fmt[i + 1]) {
2880
2881         case COL_DEF_NET_DST:
2882         case COL_RES_NET_DST:
2883         case COL_UNRES_NET_DST:
2884           strcat(line_bufp + buf_offset, " -> ");
2885           buf_offset += 4;
2886           break;
2887
2888         default:
2889           strcat(line_bufp + buf_offset, " ");
2890           buf_offset += 1;
2891           break;
2892         }
2893         break;
2894
2895       case COL_DEF_DST:
2896       case COL_RES_DST:
2897       case COL_UNRES_DST:
2898         switch (cf->cinfo.col_fmt[i + 1]) {
2899
2900         case COL_DEF_SRC:
2901         case COL_RES_SRC:
2902         case COL_UNRES_SRC:
2903           strcat(line_bufp + buf_offset, " <- ");
2904           buf_offset += 4;
2905           break;
2906
2907         default:
2908           strcat(line_bufp + buf_offset, " ");
2909           buf_offset += 1;
2910           break;
2911         }
2912         break;
2913
2914       case COL_DEF_DL_DST:
2915       case COL_RES_DL_DST:
2916       case COL_UNRES_DL_DST:
2917         switch (cf->cinfo.col_fmt[i + 1]) {
2918
2919         case COL_DEF_DL_SRC:
2920         case COL_RES_DL_SRC:
2921         case COL_UNRES_DL_SRC:
2922           strcat(line_bufp + buf_offset, " <- ");
2923           buf_offset += 4;
2924           break;
2925
2926         default:
2927           strcat(line_bufp + buf_offset, " ");
2928           buf_offset += 1;
2929           break;
2930         }
2931         break;
2932
2933       case COL_DEF_NET_DST:
2934       case COL_RES_NET_DST:
2935       case COL_UNRES_NET_DST:
2936         switch (cf->cinfo.col_fmt[i + 1]) {
2937
2938         case COL_DEF_NET_SRC:
2939         case COL_RES_NET_SRC:
2940         case COL_UNRES_NET_SRC:
2941           strcat(line_bufp + buf_offset, " <- ");
2942           buf_offset += 4;
2943           break;
2944
2945         default:
2946           strcat(line_bufp + buf_offset, " ");
2947           buf_offset += 1;
2948           break;
2949         }
2950         break;
2951
2952       default:
2953         strcat(line_bufp + buf_offset, " ");
2954         buf_offset += 1;
2955         break;
2956       }
2957     }
2958   }
2959   return print_line(print_stream, 0, line_bufp);
2960 }
2961
2962 static gboolean
2963 print_packet(capture_file *cf, epan_dissect_t *edt)
2964 {
2965   print_args_t  print_args;
2966
2967   if (verbose) {
2968     /* Print the information in the protocol tree. */
2969     switch (output_action) {
2970
2971     case WRITE_TEXT:
2972       print_args.to_file = TRUE;
2973       print_args.format = print_format;
2974       print_args.print_summary = !verbose;
2975       print_args.print_hex = verbose && print_hex;
2976       print_args.print_formfeed = FALSE;
2977       print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2978
2979       /* init the packet range */
2980       packet_range_init(&print_args.range);
2981
2982       if (!proto_tree_print(&print_args, edt, print_stream))
2983         return FALSE;
2984       if (!print_hex) {
2985         /* "print_hex_data()" will put out a leading blank line, as well
2986          as a trailing one; print one here, to separate the packets,
2987          only if "print_hex_data()" won't be called. */
2988         if (!print_line(print_stream, 0, ""))
2989           return FALSE;
2990       }
2991       break;
2992
2993     case WRITE_XML:
2994       proto_tree_write_pdml(edt, stdout);
2995       printf("\n");
2996       return !ferror(stdout);
2997     }
2998   } else {
2999     /* Just fill in the columns. */
3000     epan_dissect_fill_in_columns(edt);
3001
3002     /* Now print them. */
3003     switch (output_action) {
3004
3005     case WRITE_TEXT:
3006         if (!print_columns(cf))
3007           return FALSE;
3008         break;
3009
3010     case WRITE_XML:
3011         proto_tree_write_psml(edt, stdout);
3012         return !ferror(stdout);
3013     }
3014   }
3015   if (print_hex) {
3016     if (!print_hex_data(print_stream, edt))
3017       return FALSE;
3018     if (!print_line(print_stream, 0, ""))
3019       return FALSE;
3020   }
3021   return TRUE;
3022 }
3023
3024 static gboolean
3025 write_finale(void)
3026 {
3027   switch (output_action) {
3028
3029   case WRITE_TEXT:
3030     return print_finale(print_stream);
3031     break;
3032
3033   case WRITE_XML:
3034     if (verbose)
3035       write_pdml_finale(stdout);
3036     else
3037       write_psml_finale(stdout);
3038     return !ferror(stdout);
3039
3040   default:
3041     g_assert_not_reached();
3042     return FALSE;
3043   }
3044 }
3045
3046 static void
3047 show_print_file_io_error(int err)
3048 {
3049   switch (err) {
3050
3051   case ENOSPC:
3052     fprintf(stderr,
3053 "tethereal: Not all the packets could be printed because there is "
3054 "no space left on the file system.\n");
3055     break;
3056
3057 #ifdef EDQUOT
3058   case EDQUOT:
3059     fprintf(stderr,
3060 "tethereal: Not all the packets could be printed because you are "
3061 "too close to, or over your disk quota.\n");
3062   break;
3063 #endif
3064
3065   default:
3066     fprintf(stderr,
3067 "tethereal: An error occurred while printing packets: %s.\n",
3068       strerror(err));
3069     break;
3070   }
3071 }
3072
3073 static char *
3074 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3075                       int file_type)
3076 {
3077   char *errmsg;
3078   static char errmsg_errno[1024+1];
3079
3080   if (err < 0) {
3081     /* Wiretap error. */
3082     switch (err) {
3083
3084     case WTAP_ERR_NOT_REGULAR_FILE:
3085       errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3086       break;
3087
3088     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3089       /* Seen only when opening a capture file for reading. */
3090       errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
3091       break;
3092
3093     case WTAP_ERR_UNSUPPORTED:
3094       /* Seen only when opening a capture file for reading. */
3095       snprintf(errmsg_errno, sizeof(errmsg_errno),
3096                "The file \"%%s\" is not a capture file in a format Tethereal understands.\n"
3097                "(%s)", err_info);
3098       g_free(err_info);
3099       errmsg = errmsg_errno;
3100       break;
3101
3102     case WTAP_ERR_CANT_WRITE_TO_PIPE:
3103       /* Seen only when opening a capture file for writing. */
3104       snprintf(errmsg_errno, sizeof(errmsg_errno),
3105                "The file \"%%s\" is a pipe, and %s capture files cannot be "
3106                "written to a pipe.", wtap_file_type_string(file_type));
3107       errmsg = errmsg_errno;
3108       break;
3109
3110     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3111       /* Seen only when opening a capture file for writing. */
3112       errmsg = "Tethereal does not support writing capture files in that format.";
3113       break;
3114
3115     case WTAP_ERR_UNSUPPORTED_ENCAP:
3116       if (for_writing)
3117         errmsg = "Tethereal cannot save this capture in that format.";
3118       else {
3119         snprintf(errmsg_errno, sizeof(errmsg_errno),
3120                  "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
3121                  "(%s)", err_info);
3122         g_free(err_info);
3123         errmsg = errmsg_errno;
3124       }
3125       break;
3126
3127     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3128       if (for_writing)
3129         errmsg = "Tethereal cannot save this capture in that format.";
3130       else
3131         errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
3132       break;
3133
3134     case WTAP_ERR_BAD_RECORD:
3135       /* Seen only when opening a capture file for reading. */
3136       snprintf(errmsg_errno, sizeof(errmsg_errno),
3137                "The file \"%%s\" appears to be damaged or corrupt.\n"
3138                "(%s)", err_info);
3139       g_free(err_info);
3140       errmsg = errmsg_errno;
3141       break;
3142
3143     case WTAP_ERR_CANT_OPEN:
3144       if (for_writing)
3145         errmsg = "The file \"%s\" could not be created for some unknown reason.";
3146       else
3147         errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3148       break;
3149
3150     case WTAP_ERR_SHORT_READ:
3151       errmsg = "The file \"%s\" appears to have been cut short"
3152                " in the middle of a packet or other data.";
3153       break;
3154
3155     case WTAP_ERR_SHORT_WRITE:
3156       errmsg = "A full header couldn't be written to the file \"%s\".";
3157       break;
3158
3159     default:
3160       snprintf(errmsg_errno, sizeof(errmsg_errno),
3161                "The file \"%%s\" could not be %s: %s.",
3162                for_writing ? "created" : "opened",
3163                wtap_strerror(err));
3164       errmsg = errmsg_errno;
3165       break;
3166     }
3167   } else
3168     errmsg = file_open_error_message(err, for_writing);
3169   return errmsg;
3170 }
3171
3172 /*
3173  * Open/create errors are reported with an console message in Tethereal.
3174  */
3175 static void
3176 open_failure_message(const char *filename, int err, gboolean for_writing)
3177 {
3178   fprintf(stderr, "tethereal: ");
3179   fprintf(stderr, file_open_error_message(err, for_writing), filename);
3180   fprintf(stderr, "\n");
3181 }
3182
3183 int
3184 cf_open(char *fname, gboolean is_tempfile, capture_file *cf)
3185 {
3186   wtap       *wth;
3187   int         err;
3188   gchar       *err_info;
3189   char        err_msg[2048+1];
3190
3191   wth = wtap_open_offline(fname, &err, &err_info, FALSE);
3192   if (wth == NULL)
3193     goto fail;
3194
3195   /* The open succeeded.  Fill in the information for this file. */
3196
3197   /* Initialize all data structures used for dissection. */
3198   init_dissection();
3199
3200   cf->wth = wth;
3201   cf->filed = -1;       /* not used, but set it anyway */
3202   cf->f_len = 0;        /* not used, but set it anyway */
3203
3204   /* Set the file name because we need it to set the follow stream filter.
3205      XXX - is that still true?  We need it for other reasons, though,
3206      in any case. */
3207   cf->filename = g_strdup(fname);
3208
3209   /* Indicate whether it's a permanent or temporary file. */
3210   cf->is_tempfile = is_tempfile;
3211
3212   /* If it's a temporary capture buffer file, mark it as not saved. */
3213   cf->user_saved = !is_tempfile;
3214
3215   cf->cd_t      = wtap_file_type(cf->wth);
3216   cf->count     = 0;
3217   cf->drops_known = FALSE;
3218   cf->drops     = 0;
3219   cf->esec      = 0;
3220   cf->eusec     = 0;
3221   cf->snap      = wtap_snapshot_length(cf->wth);
3222   if (cf->snap == 0) {
3223     /* Snapshot length not known. */
3224     cf->has_snap = FALSE;
3225     cf->snap = WTAP_MAX_PACKET_SIZE;
3226   } else
3227     cf->has_snap = TRUE;
3228   firstsec = 0, firstusec = 0;
3229   prevsec = 0, prevusec = 0;
3230
3231   return (0);
3232
3233 fail:
3234   snprintf(err_msg, sizeof err_msg,
3235            cf_open_error_message(err, err_info, FALSE, 0), fname);
3236   fprintf(stderr, "tethereal: %s\n", err_msg);
3237   return (err);
3238 }
3239
3240 #ifdef HAVE_LIBPCAP
3241 #ifndef _WIN32
3242 /* Take care of byte order in the libpcap headers read from pipes.
3243  * (function taken from wiretap/libpcap.c) */
3244 static void
3245 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
3246 {
3247   if (ld->byte_swapped) {
3248     /* Byte-swap the record header fields. */
3249     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
3250     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
3251     rechdr->incl_len = BSWAP32(rechdr->incl_len);
3252     rechdr->orig_len = BSWAP32(rechdr->orig_len);
3253   }
3254
3255   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
3256      swapped, in order to match the BPF header layout.
3257
3258      Unfortunately, some files were, according to a comment in the "libpcap"
3259      source, written with version 2.3 in their headers but without the
3260      interchanged fields, so if "incl_len" is greater than "orig_len" - which
3261      would make no sense - we assume that we need to swap them.  */
3262   if (hdr->version_major == 2 &&
3263       (hdr->version_minor < 3 ||
3264        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
3265     guint32 temp;
3266
3267     temp = rechdr->orig_len;
3268     rechdr->orig_len = rechdr->incl_len;
3269     rechdr->incl_len = temp;
3270   }
3271 }
3272
3273 /* Mimic pcap_open_live() for pipe captures
3274  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
3275  * header.
3276  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
3277  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
3278 static int
3279 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
3280                  char *errmsg, int errmsgl)
3281 {
3282   struct stat pipe_stat;
3283   int         fd;
3284   guint32     magic;
3285   int         b;
3286   unsigned int bytes_read;
3287
3288   /*
3289    * XXX Tethereal blocks until we return
3290    */
3291   if (strcmp(pipename, "-") == 0)
3292     fd = 0; /* read from stdin */
3293   else {
3294     if (stat(pipename, &pipe_stat) < 0) {
3295       if (errno == ENOENT || errno == ENOTDIR)
3296         ld->pipe_err = PIPNEXIST;
3297       else {
3298         snprintf(errmsg, errmsgl,
3299           "The capture session could not be initiated "
3300           "due to error on pipe: %s", strerror(errno));
3301         ld->pipe_err = PIPERR;
3302       }
3303       return -1;
3304     }
3305     if (! S_ISFIFO(pipe_stat.st_mode)) {
3306       if (S_ISCHR(pipe_stat.st_mode)) {
3307         /*
3308          * Assume the user specified an interface on a system where
3309          * interfaces are in /dev.  Pretend we haven't seen it.
3310          */
3311          ld->pipe_err = PIPNEXIST;
3312       } else {
3313         snprintf(errmsg, errmsgl,
3314             "The capture session could not be initiated because\n"
3315             "\"%s\" is neither an interface nor a pipe", pipename);
3316         ld->pipe_err = PIPERR;
3317       }
3318       return -1;
3319     }
3320     fd = open(pipename, O_RDONLY);
3321     if (fd == -1) {
3322       snprintf(errmsg, errmsgl,
3323           "The capture session could not be initiated "
3324           "due to error on pipe open: %s", strerror(errno));
3325       ld->pipe_err = PIPERR;
3326       return -1;
3327     }
3328   }
3329
3330   ld->from_pipe = TRUE;
3331
3332   /* read the pcap header */
3333   bytes_read = 0;
3334   while (bytes_read < sizeof magic) {
3335     b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
3336     if (b <= 0) {
3337       if (b == 0)
3338         snprintf(errmsg, errmsgl, "End of file on pipe during open");
3339       else
3340         snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3341           strerror(errno));
3342       goto error;
3343     }
3344     bytes_read += b;
3345   }
3346
3347   switch (magic) {
3348   case PCAP_MAGIC:
3349     /* Host that wrote it has our byte order, and was running
3350        a program using either standard or ss990417 libpcap. */
3351     ld->byte_swapped = FALSE;
3352     ld->modified = FALSE;
3353     break;
3354   case PCAP_MODIFIED_MAGIC:
3355     /* Host that wrote it has our byte order, but was running
3356        a program using either ss990915 or ss991029 libpcap. */
3357     ld->byte_swapped = FALSE;
3358     ld->modified = TRUE;
3359     break;
3360   case PCAP_SWAPPED_MAGIC:
3361     /* Host that wrote it has a byte order opposite to ours,
3362        and was running a program using either standard or
3363        ss990417 libpcap. */
3364     ld->byte_swapped = TRUE;
3365     ld->modified = FALSE;
3366     break;
3367   case PCAP_SWAPPED_MODIFIED_MAGIC:
3368     /* Host that wrote it out has a byte order opposite to
3369        ours, and was running a program using either ss990915
3370        or ss991029 libpcap. */
3371     ld->byte_swapped = TRUE;
3372     ld->modified = TRUE;
3373     break;
3374   default:
3375     /* Not a "libpcap" type we know about. */
3376     snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
3377     goto error;
3378   }
3379
3380   /* Read the rest of the header */
3381   bytes_read = 0;
3382   while (bytes_read < sizeof(struct pcap_hdr)) {
3383     b = read(fd, ((char *)hdr)+bytes_read,
3384           sizeof(struct pcap_hdr) - bytes_read);
3385     if (b <= 0) {
3386       if (b == 0)
3387         snprintf(errmsg, errmsgl, "End of file on pipe during open");
3388       else
3389         snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
3390           strerror(errno));
3391       goto error;
3392     }
3393     bytes_read += b;
3394   }
3395
3396   if (ld->byte_swapped) {
3397     /* Byte-swap the header fields about which we care. */
3398     hdr->version_major = BSWAP16(hdr->version_major);
3399     hdr->version_minor = BSWAP16(hdr->version_minor);
3400     hdr->snaplen = BSWAP32(hdr->snaplen);
3401     hdr->network = BSWAP32(hdr->network);
3402   }
3403
3404   if (hdr->version_major < 2) {
3405     snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
3406     goto error;
3407   }
3408
3409   ld->pipe_state = STATE_EXPECT_REC_HDR;
3410   ld->pipe_err = PIPOK;
3411   return fd;
3412
3413 error:
3414   ld->pipe_err = PIPERR;
3415   close(fd);
3416   return -1;
3417
3418 }
3419 /* We read one record from the pipe, take care of byte order in the record
3420  * header, write the record in the capture file, and update capture statistics. */
3421
3422 static int
3423 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
3424                 struct pcaprec_modified_hdr *rechdr, guchar *data,
3425                 char *errmsg, int errmsgl)
3426 {
3427   struct pcap_pkthdr phdr;
3428   int b;
3429   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
3430           PD_ERR } result;
3431
3432   switch (ld->pipe_state) {
3433
3434   case STATE_EXPECT_REC_HDR:
3435     ld->bytes_to_read = ld->modified ?
3436       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
3437     ld->bytes_read = 0;
3438     ld->pipe_state = STATE_READ_REC_HDR;
3439     /* Fall through */
3440
3441   case STATE_READ_REC_HDR:
3442     b = read(fd, ((char *)rechdr)+ld->bytes_read,
3443       ld->bytes_to_read - ld->bytes_read);
3444     if (b <= 0) {
3445       if (b == 0)
3446         result = PD_PIPE_EOF;
3447       else
3448         result = PD_PIPE_ERR;
3449       break;
3450     }
3451     if ((ld->bytes_read += b) < ld->bytes_to_read)
3452         return 0;
3453     result = PD_REC_HDR_READ;
3454     break;
3455
3456   case STATE_EXPECT_DATA:
3457     ld->bytes_read = 0;
3458     ld->pipe_state = STATE_READ_DATA;
3459     /* Fall through */
3460
3461   case STATE_READ_DATA:
3462     b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
3463     if (b <= 0) {
3464       if (b == 0)
3465         result = PD_PIPE_EOF;
3466       else
3467         result = PD_PIPE_ERR;
3468       break;
3469     }
3470     if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
3471       return 0;
3472     result = PD_DATA_READ;
3473     break;
3474
3475   default:
3476     snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
3477     result = PD_ERR;
3478
3479   } /* switch (ld->pipe_state) */
3480
3481   /*
3482    * We've now read as much data as we were expecting, so process it.
3483    */
3484   switch (result) {
3485
3486   case PD_REC_HDR_READ:
3487     /* We've read the header. Take care of byte order. */
3488     adjust_header(ld, hdr, &rechdr->hdr);
3489     if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
3490       snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
3491         ld->packet_count+1, rechdr->hdr.incl_len);
3492       break;
3493     }
3494     ld->pipe_state = STATE_EXPECT_DATA;
3495     return 0;
3496
3497   case PD_DATA_READ:
3498     /* Fill in a "struct pcap_pkthdr", and process the packet. */
3499     phdr.ts.tv_sec = rechdr->hdr.ts_sec;
3500     phdr.ts.tv_usec = rechdr->hdr.ts_usec;
3501     phdr.caplen = rechdr->hdr.incl_len;
3502     phdr.len = rechdr->hdr.orig_len;
3503
3504     capture_pcap_cb((guchar *)ld, &phdr, data);
3505
3506     ld->pipe_state = STATE_EXPECT_REC_HDR;
3507     return 1;
3508
3509   case PD_PIPE_EOF:
3510     ld->pipe_err = PIPEOF;
3511     return -1;
3512
3513   case PD_PIPE_ERR:
3514     snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3515       strerror(errno));
3516     /* Fall through */
3517   case PD_ERR:
3518     break;
3519   }
3520
3521   ld->pipe_err = PIPERR;
3522   /* Return here rather than inside the switch to prevent GCC warning */
3523   return -1;
3524 }
3525 #endif /* _WIN32 */
3526 #endif /* HAVE_LIBPCAP */
3527
3528 /*
3529  * General errors are reported with an console message in Tethereal.
3530  */
3531 static void
3532 failure_message(const char *msg_format, va_list ap)
3533 {
3534   fprintf(stderr, "tethereal: ");
3535   vfprintf(stderr, msg_format, ap);
3536   fprintf(stderr, "\n");
3537 }
3538
3539 /*
3540  * Read errors are reported with an console message in Tethereal.
3541  */
3542 static void
3543 read_failure_message(const char *filename, int err)
3544 {
3545   fprintf(stderr, "tethereal: An error occurred while reading from the file \"%s\": %s.\n",
3546           filename, strerror(err));
3547 }