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