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