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