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