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