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