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