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