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