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