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