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