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