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