Fix r35690: tvb_get_unicode_string() takes length in 8-bit bytes, not
[obnox/wireshark/wip.git] / tshark.c
1 /* tshark.c
2  *
3  * Text-mode variant of Wireshark, along the lines of tcpdump and snoop,
4  * by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris <guy@alum.mit.edu>.
5  *
6  * $Id$
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
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 "wsutil/strerror.h"
56 #endif
57
58 #ifdef HAVE_GETOPT_H
59 #include <getopt.h>
60 #else
61 #include "wsutil/wsgetopt.h"
62 #endif
63
64 #include <glib.h>
65 #include <epan/epan.h>
66 #include <epan/filesystem.h>
67 #include <wsutil/privileges.h>
68 #include <wsutil/file_util.h>
69
70 #include "globals.h"
71 #include <epan/timestamp.h>
72 #include <epan/packet.h>
73 #include "file.h"
74 #include "disabled_protos.h"
75 #include <epan/prefs.h>
76 #include <epan/column.h>
77 #include "print.h"
78 #include <epan/addr_resolv.h>
79 #include "util.h"
80 #include "clopts_common.h"
81 #include "console_io.h"
82 #include "cmdarg_err.h"
83 #include "version_info.h"
84 #include <epan/plugins.h>
85 #include "register.h"
86 #include <epan/epan_dissect.h>
87 #include <epan/tap.h>
88 #include <epan/stat_cmd_args.h>
89 #include <epan/timestamp.h>
90 #include <epan/ex-opt.h>
91
92 #ifdef HAVE_LIBPCAP
93 #include "capture_ui_utils.h"
94 #include "capture_ifinfo.h"
95 #include "capture-pcap-util.h"
96 #ifdef _WIN32
97 #include "capture-wpcap.h"
98 #include "capture_errs.h"
99 #include <shellapi.h>
100 #endif /* _WIN32 */
101 #include "capture_sync.h"
102 #endif /* HAVE_LIBPCAP */
103 #include "log.h"
104 #include <epan/funnel.h>
105
106
107 /*
108  * This is the template for the decode as option; it is shared between the
109  * various functions that output the usage for this parameter.
110  */
111 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
112
113 static guint32 cum_bytes;
114 static nstime_t first_ts;
115 static nstime_t prev_dis_ts;
116 static nstime_t prev_cap_ts;
117
118 static gboolean print_packet_info;      /* TRUE if we're to print packet information */
119
120 static gboolean perform_two_pass_analysis;
121
122 /*
123  * The way the packet decode is to be written.
124  */
125 typedef enum {
126   WRITE_TEXT,   /* summary or detail text */
127   WRITE_XML,    /* PDML or PSML */
128   WRITE_FIELDS  /* User defined list of fields */
129   /* Add CSV and the like here */
130 } output_action_e;
131
132 static output_action_e output_action;
133 static gboolean do_dissection;  /* TRUE if we have to dissect each packet */
134 static gboolean verbose;
135 static gboolean print_hex;
136 static gboolean line_buffered;
137
138 static print_format_e print_format = PR_FMT_TEXT;
139 static print_stream_t *print_stream;
140
141 static output_fields_t* output_fields  = NULL;
142
143 #ifdef HAVE_LIBPCAP
144 /*
145  * TRUE if we're to print packet counts to keep track of captured packets.
146  */
147 static gboolean print_packet_counts;
148
149
150 static capture_options global_capture_opts;
151
152 #ifdef SIGINFO
153 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
154 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
155 #endif /* SIGINFO */
156
157 static gboolean capture(void);
158 static void report_counts(void);
159 #ifdef _WIN32
160 static BOOL WINAPI capture_cleanup(DWORD);
161 #else /* _WIN32 */
162 static void capture_cleanup(int);
163 #ifdef SIGINFO
164 static void report_counts_siginfo(int);
165 #endif /* SIGINFO */
166 #endif /* _WIN32 */
167 #endif /* HAVE_LIBPCAP */
168
169 static int load_cap_file(capture_file *, char *, int, int, gint64);
170 static gboolean process_packet(capture_file *cf, gint64 offset,
171     const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
172     const guchar *pd, gboolean filtering_tap_listeners, guint tap_flags);
173 static void show_capture_file_io_error(const char *, int, gboolean);
174 static void show_print_file_io_error(int err);
175 static gboolean write_preamble(capture_file *cf);
176 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
177 static gboolean write_finale(void);
178 static const char *cf_open_error_message(int err, gchar *err_info,
179     gboolean for_writing, int file_type);
180
181 static void open_failure_message(const char *filename, int err,
182     gboolean for_writing);
183 static void failure_message(const char *msg_format, va_list ap);
184 static void read_failure_message(const char *filename, int err);
185 static void write_failure_message(const char *filename, int err);
186
187 capture_file cfile;
188
189 static void list_capture_types(void) {
190   int i;
191
192   fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
193   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
194     if (wtap_dump_can_open(i))
195       fprintf(stderr, "    %s - %s\n",
196               wtap_file_type_short_string(i), wtap_file_type_string(i));
197   }
198 }
199
200 static void
201 print_usage(gboolean print_ver)
202 {
203   FILE *output;
204
205   if (print_ver) {
206     output = stdout;
207     fprintf(output,
208         "TShark " VERSION "%s\n"
209         "Dump and analyze network traffic.\n"
210         "See http://www.wireshark.org for more information.\n"
211         "\n"
212         "%s",
213          wireshark_svnversion, get_copyright_info());
214   } else {
215     output = stderr;
216   }
217   fprintf(output, "\n");
218   fprintf(output, "Usage: tshark [options] ...\n");
219   fprintf(output, "\n");
220
221 #ifdef HAVE_LIBPCAP
222   fprintf(output, "Capture interface:\n");
223   fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback)\n");
224   fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
225   fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
226   fprintf(output, "  -p                       don't capture in promiscuous mode\n");
227 #ifdef HAVE_PCAP_CREATE
228   fprintf(output, "  -I                       capture in monitor mode, if available\n");
229 #endif
230 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
231   fprintf(output, "  -B <buffer size>         size of kernel buffer (def: 1MB)\n");
232 #endif
233   fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
234   fprintf(output, "  -D                       print list of interfaces and exit\n");
235   fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
236   fprintf(output, "\n");
237   fprintf(output, "Capture stop conditions:\n");
238   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
239   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
240   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
241   fprintf(output, "                              files:NUM - stop after NUM files\n");
242   /*fprintf(output, "\n");*/
243   fprintf(output, "Capture output:\n");
244   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
245   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
246   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
247 #endif  /* HAVE_LIBPCAP */
248
249   /*fprintf(output, "\n");*/
250   fprintf(output, "Input file:\n");
251   fprintf(output, "  -r <infile>              set the filename to read from (no pipes or stdin!)\n");
252
253   fprintf(output, "\n");
254   fprintf(output, "Processing:\n");
255   fprintf(output, "  -R <read filter>         packet filter in Wireshark display filter syntax\n");
256   fprintf(output, "  -n                       disable all name resolutions (def: all enabled)\n");
257   fprintf(output, "  -N <name resolve flags>  enable specific name resolution(s): \"mntC\"\n");
258   fprintf(output, "  -d %s ...\n", decode_as_arg_template);
259   fprintf(output, "                           \"Decode As\", see the man page for details\n");
260   fprintf(output, "                           Example: tcp.port==8888,http\n");
261
262   /*fprintf(output, "\n");*/
263   fprintf(output, "Output:\n");
264   fprintf(output, "  -w <outfile|->           write packets to a pcap-format file named \"outfile\"\n");
265   fprintf(output, "                           (or to the standard output for \"-\")\n");
266   fprintf(output, "  -C <config profile>      start with specified configuration profile\n");
267   fprintf(output, "  -F <output file type>    set the output file type, default is libpcap\n");
268   fprintf(output, "                           an empty \"-F\" option will list the file types\n");
269   fprintf(output, "  -V                       add output of packet tree        (Packet Details)\n");
270   fprintf(output, "  -S                       display packets even when writing to a file\n");
271   fprintf(output, "  -x                       add output of hex and ASCII dump (Packet Bytes)\n");
272   fprintf(output, "  -T pdml|ps|psml|text|fields\n");
273   fprintf(output, "                           format of text output (def: text)\n");
274   fprintf(output, "  -e <field>               field to print if -Tfields selected (e.g. tcp.port);\n");
275   fprintf(output, "                           this option can be repeated to print multiple fields\n");
276   fprintf(output, "  -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
277   fprintf(output, "     header=y|n            switch headers on and off\n");
278   fprintf(output, "     separator=/t|/s|<char> select tab, space, printable character as separator\n");
279   fprintf(output, "     occurrence=f|l|a      print first, last or all occurrences of each field\n");
280   fprintf(output, "     aggregator=,|/s|<char> select comma, space, printable character as aggregator\n");
281   fprintf(output, "     quote=d|s|n           select double, single, no quotes for values\n");
282   fprintf(output, "  -t ad|a|r|d|dd|e         output format of time stamps (def: r: rel. to first)\n");
283   fprintf(output, "  -u s|hms                 output format of seconds (def: s: seconds)\n");
284   fprintf(output, "  -l                       flush standard output after each packet\n");
285   fprintf(output, "  -q                       be more quiet on stdout (e.g. when using statistics)\n");
286   fprintf(output, "  -X <key>:<value>         eXtension options, see the man page for details\n");
287   fprintf(output, "  -z <statistics>          various statistics, see the man page for details\n");
288
289   fprintf(output, "\n");
290   fprintf(output, "Miscellaneous:\n");
291   fprintf(output, "  -h                       display this help and exit\n");
292   fprintf(output, "  -v                       display version info and exit\n");
293   fprintf(output, "  -o <name>:<value> ...    override preference setting\n");
294   fprintf(output, "  -K <keytab>              keytab file to use for kerberos decryption\n");
295   fprintf(output, "  -G [report]              dump one of several available reports and exit\n");
296   fprintf(output, "                           default report=\"fields\"\n");
297   fprintf(output, "                           use \"-G ?\" for more help\n");
298 }
299
300 static void
301 glossary_option_help(void)
302 {
303   FILE *output;
304
305   output = stdout;
306
307   fprintf(output, "TShark " VERSION "%s\n", wireshark_svnversion);
308
309   fprintf(output, "\n");
310   fprintf(output, "Usage: tshark -G [report]\n");
311   fprintf(output, "\n");
312   fprintf(output, "Glossary table reports:\n");
313   fprintf(output, "  -G [fields]              dump glossary in original format and exit\n");
314   fprintf(output, "  -G fields2               dump glossary in format 2 and exit\n");
315   fprintf(output, "  -G fields3               dump glossary in format 3 and exit\n");
316   fprintf(output, "  -G protocols             dump protocols in registration database and exit\n");
317   fprintf(output, "  -G values                dump value, range, true/false strings and exit\n");
318   fprintf(output, "  -G decodes               dump \"layer type\"/\"decode as\" associations and exit\n");
319   fprintf(output, "\n");
320   fprintf(output, "Preference reports:\n");
321   fprintf(output, "  -G defaultprefs          dump default preferences and exit\n");
322   fprintf(output, "  -G currentprefs          dump current preferences and exit\n");
323   fprintf(output, "\n");
324
325 }
326
327 /*
328  * For a dissector table, print on the stream described by output,
329  * its short name (which is what's used in the "-d" option) and its
330  * descriptive name.
331  */
332 static void
333 display_dissector_table_names(const char *table_name, const char *ui_name,
334                               gpointer output)
335 {
336   fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
337 }
338
339 /*
340  * For a dissector handle, print on the stream described by output,
341  * the filter name (which is what's used in the "-d" option) and the full
342  * name for the protocol that corresponds to this handle.
343  */
344 static void
345 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
346 {
347   int                proto_id;
348   const gchar*       proto_filter_name;
349   const gchar*       proto_ui_name;
350
351   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
352
353   if (proto_id != -1) {
354     proto_filter_name = proto_get_protocol_filter_name(proto_id);
355     proto_ui_name =  proto_get_protocol_name(proto_id);
356     g_assert(proto_filter_name != NULL);
357     g_assert(proto_ui_name != NULL);
358
359     fprintf((FILE *)output, "\t%s (%s)\n",
360             proto_filter_name,
361             proto_ui_name);
362   }
363 }
364
365 /*
366  * The protocol_name_search structure is used by find_protocol_name_func()
367  * to pass parameters and store results
368  */
369 struct protocol_name_search{
370   gchar              *searched_name;  /* Protocol filter name we are looking for */
371   dissector_handle_t  matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
372   guint               nb_match;       /* How many dissectors matched searched_name */
373 };
374 typedef struct protocol_name_search *protocol_name_search_t;
375
376 /*
377  * This function parses all dissectors associated with a table to find the
378  * one whose protocol has the specified filter name.  It is called
379  * as a reference function in a call to dissector_table_foreach_handle.
380  * The name we are looking for, as well as the results, are stored in the
381  * protocol_name_search struct pointed to by user_data.
382  * If called using dissector_table_foreach_handle, we actually parse the
383  * whole list of dissectors.
384  */
385 static void
386 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
387
388 {
389   int                         proto_id;
390   const gchar                *protocol_filter_name;
391   protocol_name_search_t      search_info;
392
393   g_assert(handle);
394
395   search_info = (protocol_name_search_t)user_data;
396
397   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
398   if (proto_id != -1) {
399     protocol_filter_name = proto_get_protocol_filter_name(proto_id);
400     g_assert(protocol_filter_name != NULL);
401     if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
402       /* Found a match */
403       if (search_info->nb_match == 0) {
404         /* Record this handle only if this is the first match */
405         search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
406       }
407       search_info->nb_match++;
408     }
409   }
410 }
411
412 /*
413  * Print all layer type names supported.
414  * We send the output to the stream described by the handle output.
415  */
416
417 static void
418 fprint_all_layer_types(FILE *output)
419
420 {
421   dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
422 }
423
424 /*
425  * Print all protocol names supported for a specific layer type.
426  * table_name contains the layer type name in which the search is performed.
427  * We send the output to the stream described by the handle output.
428  */
429
430 static void
431 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
432
433 {
434   dissector_table_foreach_handle(table_name,
435                                  display_dissector_names,
436                                  (gpointer)output);
437 }
438
439 /*
440  * The function below parses the command-line parameters for the decode as
441  * feature (a string pointer by cl_param).
442  * It checks the format of the command-line, searches for a matching table
443  * and dissector.  If a table/dissector match is not found, we display a
444  * summary of the available tables/dissectors (on stderr) and return FALSE.
445  * If everything is fine, we get the "Decode as" preference activated,
446  * then we return TRUE.
447  */
448 static gboolean
449 add_decode_as(const gchar *cl_param)
450 {
451   gchar                        *table_name;
452   guint32                       selector;
453   gchar                        *decoded_param;
454   gchar                        *remaining_param;
455   gchar                        *selector_str;
456   gchar                        *dissector_str;
457   dissector_handle_t            dissector_matching;
458   dissector_table_t             table_matching;
459   ftenum_t                      dissector_table_selector_type;
460   struct protocol_name_search   user_protocol_name;
461
462   /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
463
464   g_assert(cl_param);
465   decoded_param = g_strdup(cl_param);
466   g_assert(decoded_param);
467
468
469   /* The lines below will parse this string (modifying it) to extract all
470     necessary information.  Note that decoded_param is still needed since
471     strings are not copied - we just save pointers. */
472
473   /* This section extracts a layer type (table_name) from decoded_param */
474   table_name = decoded_param; /* Layer type string starts from beginning */
475
476   remaining_param = strchr(table_name, '=');
477   if (remaining_param == NULL) {
478     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
479     /* If the argument does not follow the template, carry on anyway to check
480        if the table name is at least correct.  If remaining_param is NULL,
481        we'll exit anyway further down */
482   }
483   else {
484     *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
485   }
486
487   /* Remove leading and trailing spaces from the table name */
488   while ( table_name[0] == ' ' )
489     table_name++;
490   while ( table_name[strlen(table_name) - 1] == ' ' )
491     table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
492
493 /* The following part searches a table matching with the layer type specified */
494   table_matching = NULL;
495
496 /* Look for the requested table */
497   if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
498     cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
499   }
500   else {
501     table_matching = find_dissector_table(table_name);
502     if (!table_matching) {
503       cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
504     }
505   }
506
507   if (!table_matching) {
508     /* Display a list of supported layer types to help the user, if the
509        specified layer type was not found */
510     cmdarg_err("Valid layer types are:");
511     fprint_all_layer_types(stderr);
512   }
513   if (remaining_param == NULL || !table_matching) {
514     /* Exit if the layer type was not found, or if no '=' separator was found
515        (see above) */
516     g_free(decoded_param);
517     return FALSE;
518   }
519
520   if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
521     cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
522   }
523   else {
524     remaining_param++; /* Move to the second '=' */
525     *remaining_param = '\0'; /* Remove the second '=' */
526   }
527   remaining_param++; /* Position after the layer type string */
528
529   /* This section extracts a selector value (selector_str) from decoded_param */
530
531   selector_str = remaining_param; /* Next part starts with the selector number */
532
533   remaining_param = strchr(selector_str, ',');
534   if (remaining_param == NULL) {
535     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
536     /* If the argument does not follow the template, carry on anyway to check
537        if the selector value is at least correct.  If remaining_param is NULL,
538        we'll exit anyway further down */
539   }
540   else {
541     *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
542   }
543
544   dissector_table_selector_type = get_dissector_table_selector_type(table_name);
545
546   switch (dissector_table_selector_type) {
547
548   case FT_UINT8:
549   case FT_UINT16:
550   case FT_UINT24:
551   case FT_UINT32:
552     /* The selector for this table is an unsigned number.  Parse it as such.
553        There's no need to remove leading and trailing spaces from the
554        selector number string, because sscanf will do that for us. */
555     if ( sscanf(selector_str, "%u", &selector) != 1 ) {
556       cmdarg_err("Invalid selector number \"%s\"", selector_str);
557       g_free(decoded_param);
558       return FALSE;
559     }
560     break;
561
562   case FT_STRING:
563   case FT_STRINGZ:
564   case FT_EBCDIC:
565     /* The selector for this table is a string. */
566     break;
567
568   default:
569     /* There are currently no dissector tables with any types other
570        than the ones listed above. */
571     g_assert_not_reached();
572   }
573
574   if (remaining_param == NULL) {
575     /* Exit if no ',' separator was found (see above) */
576     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
577     fprint_all_protocols_for_layer_types(stderr, table_name);
578     g_free(decoded_param);
579     return FALSE;
580   }
581
582   remaining_param++; /* Position after the selector number string */
583
584   /* This section extracts a protocol filter name (dissector_str) from decoded_param */
585
586   dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
587
588   /* Remove leading and trailing spaces from the dissector name */
589   while ( dissector_str[0] == ' ' )
590     dissector_str++;
591   while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
592     dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
593
594   dissector_matching = NULL;
595
596   /* We now have a pointer to the handle for the requested table inside the variable table_matching */
597   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 */
598     cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
599   }
600   else {
601     user_protocol_name.nb_match = 0;
602     user_protocol_name.searched_name = dissector_str;
603     user_protocol_name.matched_handle = NULL;
604
605     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 */
606
607     if (user_protocol_name.nb_match != 0) {
608       dissector_matching = user_protocol_name.matched_handle;
609       if (user_protocol_name.nb_match > 1) {
610         cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
611       }
612     }
613     else {
614       /* OK, check whether the problem is that there isn't any such
615          protocol, or that there is but it's not specified as a protocol
616          that's valid for that dissector table.
617          Note, we don't exit here, but dissector_matching will remain NULL,
618          so we exit below */
619       if (proto_get_id_by_filter_name(dissector_str) == -1) {
620         /* No such protocol */
621         cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
622       } else {
623         cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
624                    dissector_str, table_name);
625       }
626     }
627   }
628
629   if (!dissector_matching) {
630     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
631     fprint_all_protocols_for_layer_types(stderr, table_name);
632     g_free(decoded_param);
633     return FALSE;
634   }
635
636 /* This is the end of the code that parses the command-line options.
637    All information is now stored in the variables:
638    table_name
639    selector
640    dissector_matching
641    The above variables that are strings are still pointing to areas within
642    decoded_parm.  decoded_parm thus still needs to be kept allocated in
643    until we stop needing these variables
644    decoded_param will be deallocated at each exit point of this function */
645
646
647   /* We now have a pointer to the handle for the requested dissector
648      (requested protocol) inside the variable dissector_matching */
649   switch (dissector_table_selector_type) {
650
651   case FT_UINT8:
652   case FT_UINT16:
653   case FT_UINT24:
654   case FT_UINT32:
655     /* The selector for this table is an unsigned number. */
656     dissector_change_uint(table_name, selector, dissector_matching);
657     break;
658
659   case FT_STRING:
660   case FT_STRINGZ:
661   case FT_EBCDIC:
662     /* The selector for this table is a string. */
663     dissector_change_string(table_name, selector_str, dissector_matching);
664     break;
665
666   default:
667     /* There are currently no dissector tables with any types other
668        than the ones listed above. */
669     g_assert_not_reached();
670   }
671   g_free(decoded_param); /* "Decode As" rule has been succesfully added */
672   return TRUE;
673 }
674
675 static void
676 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
677     const gchar *message, gpointer user_data)
678 {
679   /* ignore log message, if log_level isn't interesting based
680      upon the console log preferences.
681      If the preferences haven't been loaded loaded yet, display the
682      message anyway.
683
684      The default console_log_level preference value is such that only
685        ERROR, CRITICAL and WARNING level messages are processed;
686        MESSAGE, INFO and DEBUG level messages are ignored.
687
688      XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
689            ERROR and CRITICAL level messages so the current code is a behavioral
690            change.  The current behavior is the same as in Wireshark.
691   */
692   if((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
693      prefs.console_log_level != 0) {
694     return;
695   }
696
697   g_log_default_handler(log_domain, log_level, message, user_data);
698
699 }
700
701 static char *
702 output_file_description(const char *fname)
703 {
704   char *save_file_string;
705
706   /* Get a string that describes what we're writing to */
707   if (strcmp(fname, "-") == 0) {
708     /* We're writing to the standard output */
709     save_file_string = g_strdup("standard output");
710   } else {
711     /* We're writing to a file with the name in save_file */
712     save_file_string = g_strdup_printf("file \"%s\"", fname);
713   }
714   return save_file_string;
715 }
716
717 static void
718 print_current_user(void) {
719   gchar *cur_user, *cur_group;
720   if (started_with_special_privs()) {
721     cur_user = get_cur_username();
722     cur_group = get_cur_groupname();
723     fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
724       cur_user, cur_group);
725     g_free(cur_user);
726     g_free(cur_group);
727     if (running_with_special_privs()) {
728       fprintf(stderr, " This could be dangerous.");
729     }
730     fprintf(stderr, "\n");
731   }
732 }
733
734 static void
735 check_capture_privs(void) {
736 #ifdef _WIN32
737   load_wpcap();
738   /* Warn the user if npf.sys isn't loaded. */
739   if (!npf_sys_is_running() && get_os_major_version() >= 6) {
740     fprintf(stderr, "The NPF driver isn't running.  You may have trouble "
741       "capturing or\nlisting interfaces.\n");
742   }
743 #endif
744 }
745
746 static void
747 show_version(GString *comp_info_str, GString *runtime_info_str)
748 {
749   printf("TShark " VERSION "%s\n"
750          "\n"
751          "%s"
752          "\n"
753          "%s"
754          "\n"
755          "%s",
756          wireshark_svnversion, get_copyright_info(), comp_info_str->str,
757          runtime_info_str->str);
758 }
759
760 int
761 main(int argc, char *argv[])
762 {
763   char                *init_progfile_dir_error;
764   int                  opt;
765   gboolean             arg_error = FALSE;
766
767 #ifdef _WIN32
768   WSADATA              wsaData;
769   LPWSTR              *wc_argv;
770   int                  wc_argc, i;
771 #endif  /* _WIN32 */
772
773   char                *gpf_path, *pf_path;
774   char                *gdp_path, *dp_path;
775   int                  gpf_open_errno, gpf_read_errno;
776   int                  pf_open_errno, pf_read_errno;
777   int                  gdp_open_errno, gdp_read_errno;
778   int                  dp_open_errno, dp_read_errno;
779   int                  err;
780   int                  exit_status = 0;
781 #ifdef HAVE_LIBPCAP
782   gboolean             list_link_layer_types = FALSE;
783   gboolean             start_capture = FALSE;
784   int                  status;
785   GList               *if_list;
786   gchar               *err_str;
787 #else
788   gboolean             capture_option_specified = FALSE;
789 #endif
790   gboolean             quiet = FALSE;
791   int                  out_file_type = WTAP_FILE_PCAP;
792   gchar               *cf_name = NULL, *rfilter = NULL;
793 #ifdef HAVE_PCAP_OPEN_DEAD
794   struct bpf_program   fcode;
795 #endif
796   dfilter_t           *rfcode = NULL;
797   e_prefs             *prefs_p;
798   char                 badopt;
799   GLogLevelFlags       log_flags;
800   int                  optind_initial;
801
802 #ifdef HAVE_LIBPCAP
803 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
804 #define OPTSTRING_B "B:"
805 #else
806 #define OPTSTRING_B ""
807 #endif  /* _WIN32 or HAVE_PCAP_CREATE */
808 #else /* HAVE_LIBPCAP */
809 #define OPTSTRING_B ""
810 #endif  /* HAVE_LIBPCAP */
811
812 #ifdef HAVE_PCAP_CREATE
813 #define OPTSTRING_I "I"
814 #else
815 #define OPTSTRING_I ""
816 #endif
817
818 #define OPTSTRING "a:b:" OPTSTRING_B "c:C:d:De:E:f:F:G:hi:" OPTSTRING_I "K:lLnN:o:pPqr:R:s:St:T:u:vVw:xX:y:z:"
819
820   static const char    optstring[] = OPTSTRING;
821
822 #ifdef _WIN32
823   /* Convert our arg list to UTF-8. */
824   wc_argv = CommandLineToArgvW(GetCommandLineW(), &wc_argc);
825   if (wc_argv && wc_argc == argc) {
826     for (i = 0; i < argc; i++) {
827       argv[i] = g_utf16_to_utf8(wc_argv[i], -1, NULL, NULL, NULL);
828     }
829   } /* XXX else bail because something is horribly, horribly wrong? */
830 #endif /* _WIN32 */
831
832   /*
833    * Get credential information for later use.
834    */
835   init_process_policies();
836
837   /*
838    * Attempt to get the pathname of the executable file.
839    */
840   init_progfile_dir_error = init_progfile_dir(argv[0], main);
841   if (init_progfile_dir_error != NULL) {
842     fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
843             init_progfile_dir_error);
844   }
845
846   /*
847    * In order to have the -X opts assigned before the wslua machine starts
848    * we need to call getopts before epan_init() gets called.
849    */
850   opterr = 0;
851   optind_initial = optind;
852
853   while ((opt = getopt(argc, argv, optstring)) != -1) {
854     switch (opt) {
855     case 'C':        /* Configuration Profile */
856       if (profile_exists (optarg)) {
857         set_profile_name (optarg);
858       } else {
859         cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
860         return 1;
861       }
862       break;
863     case 'X':
864       ex_opt_add(optarg);
865       break;
866     default:
867       break;
868     }
869   }
870
871   optind = optind_initial;
872   opterr = 1;
873
874
875
876 /** Send All g_log messages to our own handler **/
877
878   log_flags =
879                     G_LOG_LEVEL_ERROR|
880                     G_LOG_LEVEL_CRITICAL|
881                     G_LOG_LEVEL_WARNING|
882                     G_LOG_LEVEL_MESSAGE|
883                     G_LOG_LEVEL_INFO|
884                     G_LOG_LEVEL_DEBUG|
885                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
886
887   g_log_set_handler(NULL,
888                     log_flags,
889                     tshark_log_handler, NULL /* user_data */);
890   g_log_set_handler(LOG_DOMAIN_MAIN,
891                     log_flags,
892                     tshark_log_handler, NULL /* user_data */);
893
894 #ifdef HAVE_LIBPCAP
895   g_log_set_handler(LOG_DOMAIN_CAPTURE,
896                     log_flags,
897                     tshark_log_handler, NULL /* user_data */);
898   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
899                     log_flags,
900                     tshark_log_handler, NULL /* user_data */);
901 #endif
902
903   initialize_funnel_ops();
904
905 #ifdef HAVE_LIBPCAP
906   capture_opts_init(&global_capture_opts, &cfile);
907 #endif
908
909   timestamp_set_type(TS_RELATIVE);
910   timestamp_set_precision(TS_PREC_AUTO);
911   timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
912
913   /* Register all dissectors; we must do this before checking for the
914      "-G" flag, as the "-G" flag dumps information registered by the
915      dissectors, and we must do it before we read the preferences, in
916      case any dissectors register preferences. */
917   epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
918             failure_message, open_failure_message, read_failure_message,
919             write_failure_message);
920
921   /* Register all tap listeners; we do this before we parse the arguments,
922      as the "-z" argument can specify a registered tap. */
923
924   /* we register the plugin taps before the other taps because
925      stats_tree taps plugins will be registered as tap listeners
926      by stats_tree_stat.c and need to registered before that */
927 #ifdef HAVE_PLUGINS
928   register_all_plugin_tap_listeners();
929 #endif
930   register_all_tap_listeners();
931
932   /* Now register the preferences for any non-dissector modules.
933      We must do that before we read the preferences as well. */
934   prefs_register_modules();
935
936   /* If invoked with the "-G" flag, we dump out information based on
937      the argument to the "-G" flag; if no argument is specified,
938      for backwards compatibility we dump out a glossary of display
939      filter symbols.
940
941      XXX - we do this here, for now, to support "-G" with no arguments.
942      If none of our build or other processes uses "-G" with no arguments,
943      we can just process it with the other arguments. */
944   if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
945     proto_initialize_all_prefixes();
946
947     if (argc == 2)
948       proto_registrar_dump_fields(1);
949     else {
950       if (strcmp(argv[2], "fields") == 0)
951         proto_registrar_dump_fields(1);
952       else if (strcmp(argv[2], "fields2") == 0)
953         proto_registrar_dump_fields(2);
954       else if (strcmp(argv[2], "fields3") == 0)
955         proto_registrar_dump_fields(3);
956       else if (strcmp(argv[2], "protocols") == 0)
957         proto_registrar_dump_protocols();
958       else if (strcmp(argv[2], "values") == 0)
959         proto_registrar_dump_values();
960       else if (strcmp(argv[2], "decodes") == 0)
961         dissector_dump_decodes();
962       else if (strcmp(argv[2], "defaultprefs") == 0)
963         write_prefs(NULL);
964       else if (strcmp(argv[2], "?") == 0)
965         glossary_option_help();
966       else if (strcmp(argv[2], "-?") == 0)
967         glossary_option_help();
968       else if (strcmp(argv[2], "currentprefs") == 0) {
969         read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
970             &pf_open_errno, &pf_read_errno, &pf_path);
971         write_prefs(NULL);
972       } else {
973         cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
974         return 1;
975       }
976     }
977     return 0;
978   }
979
980   /* Set the C-language locale to the native environment. */
981   setlocale(LC_ALL, "");
982
983   prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
984                      &pf_open_errno, &pf_read_errno, &pf_path);
985   if (gpf_path != NULL) {
986     if (gpf_open_errno != 0) {
987       cmdarg_err("Can't open global preferences file \"%s\": %s.",
988               pf_path, strerror(gpf_open_errno));
989     }
990     if (gpf_read_errno != 0) {
991       cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
992               pf_path, strerror(gpf_read_errno));
993     }
994   }
995   if (pf_path != NULL) {
996     if (pf_open_errno != 0) {
997       cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
998               strerror(pf_open_errno));
999     }
1000     if (pf_read_errno != 0) {
1001       cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
1002               pf_path, strerror(pf_read_errno));
1003     }
1004     g_free(pf_path);
1005     pf_path = NULL;
1006   }
1007
1008   /* Set the name resolution code's flags from the preferences. */
1009   gbl_resolv_flags = prefs_p->name_resolve;
1010
1011   /* Read the disabled protocols file. */
1012   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
1013                             &dp_path, &dp_open_errno, &dp_read_errno);
1014   if (gdp_path != NULL) {
1015     if (gdp_open_errno != 0) {
1016       cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
1017                  gdp_path, strerror(gdp_open_errno));
1018     }
1019     if (gdp_read_errno != 0) {
1020       cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
1021                  gdp_path, strerror(gdp_read_errno));
1022     }
1023     g_free(gdp_path);
1024   }
1025   if (dp_path != NULL) {
1026     if (dp_open_errno != 0) {
1027       cmdarg_err(
1028         "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
1029         strerror(dp_open_errno));
1030     }
1031     if (dp_read_errno != 0) {
1032       cmdarg_err(
1033         "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
1034         strerror(dp_read_errno));
1035     }
1036     g_free(dp_path);
1037   }
1038
1039   check_capture_privs();
1040
1041   cap_file_init(&cfile);
1042
1043   /* Print format defaults to this. */
1044   print_format = PR_FMT_TEXT;
1045
1046   output_fields = output_fields_new();
1047
1048   /* Now get our args */
1049   while ((opt = getopt(argc, argv, optstring)) != -1) {
1050     switch (opt) {
1051       case 'a':        /* autostop criteria */
1052       case 'b':        /* Ringbuffer option */
1053       case 'c':        /* Capture x packets */
1054       case 'f':        /* capture filter */
1055       case 'i':        /* Use interface x */
1056       case 'p':        /* Don't capture in promiscuous mode */
1057 #ifdef HAVE_PCAP_CREATE
1058       case 'I':        /* Capture in monitor mode, if available */
1059 #endif
1060       case 's':        /* Set the snapshot (capture) length */
1061       case 'w':        /* Write to capture file x */
1062       case 'y':        /* Set the pcap data link type */
1063 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1064       case 'B':        /* Buffer size */
1065 #endif /* _WIN32 or HAVE_PCAP_CREATE */
1066 #ifdef HAVE_LIBPCAP
1067         status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1068         if(status != 0) {
1069             return status;
1070         }
1071 #else
1072         capture_option_specified = TRUE;
1073         arg_error = TRUE;
1074 #endif
1075         break;
1076       case 'C':
1077         /* Configuration profile settings were already processed just ignore them this time*/
1078         break;
1079       case 'd':        /* Decode as rule */
1080         if (!add_decode_as(optarg))
1081           return 1;
1082         break;
1083 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1084       case 'K':        /* Kerberos keytab file */
1085         read_keytab_file(optarg);
1086         break;
1087 #endif
1088       case 'D':        /* Print a list of capture devices and exit */
1089 #ifdef HAVE_LIBPCAP
1090         if_list = capture_interface_list(&err, &err_str);
1091         if (if_list == NULL) {
1092           switch (err) {
1093           case CANT_GET_INTERFACE_LIST:
1094             cmdarg_err("%s", err_str);
1095             g_free(err_str);
1096             break;
1097
1098           case NO_INTERFACES_FOUND:
1099             cmdarg_err("There are no interfaces on which a capture can be done");
1100             break;
1101           }
1102           return 2;
1103         }
1104         capture_opts_print_interfaces(if_list);
1105         free_interface_list(if_list);
1106         return 0;
1107 #else
1108         capture_option_specified = TRUE;
1109         arg_error = TRUE;
1110 #endif
1111         break;
1112       case 'e':
1113         /* Field entry */
1114         output_fields_add(output_fields, optarg);
1115         break;
1116       case 'E':
1117         /* Field option */
1118         if(!output_fields_set_option(output_fields, optarg)) {
1119           cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1120           output_fields_list_options(stderr);
1121           return 1;
1122         }
1123         break;
1124       case 'F':
1125         out_file_type = wtap_short_string_to_file_type(optarg);
1126         if (out_file_type < 0) {
1127           cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1128           list_capture_types();
1129           return 1;
1130         }
1131         break;
1132       case 'h':        /* Print help and exit */
1133         print_usage(TRUE);
1134         return 0;
1135         break;
1136       case 'l':        /* "Line-buffer" standard output */
1137         /* This isn't line-buffering, strictly speaking, it's just
1138            flushing the standard output after the information for
1139            each packet is printed; however, that should be good
1140            enough for all the purposes to which "-l" is put (and
1141            is probably actually better for "-V", as it does fewer
1142            writes).
1143
1144            See the comment in "process_packet()" for an explanation of
1145            why we do that, and why we don't just use "setvbuf()" to
1146            make the standard output line-buffered (short version: in
1147            Windows, "line-buffered" is the same as "fully-buffered",
1148            and the output buffer is only flushed when it fills up). */
1149         line_buffered = TRUE;
1150         break;
1151       case 'L':        /* Print list of link-layer types and exit */
1152 #ifdef HAVE_LIBPCAP
1153         list_link_layer_types = TRUE;
1154 #else
1155         capture_option_specified = TRUE;
1156         arg_error = TRUE;
1157 #endif
1158         break;
1159 #if GLIB_CHECK_VERSION(2,10,0)
1160       case 'P':        /* Perform two pass analysis */
1161         perform_two_pass_analysis = TRUE;
1162         break;
1163 #endif
1164       case 'n':        /* No name resolution */
1165         gbl_resolv_flags = RESOLV_NONE;
1166         break;
1167       case 'N':        /* Select what types of addresses/port #s to resolve */
1168         if (gbl_resolv_flags == RESOLV_ALL)
1169           gbl_resolv_flags = RESOLV_NONE;
1170         badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
1171         if (badopt != '\0') {
1172           cmdarg_err("-N specifies unknown resolving option '%c';",
1173                      badopt);
1174           cmdarg_err_cont( "           Valid options are 'm', 'n', 't', and 'C'");
1175           return 1;
1176         }
1177         break;
1178       case 'o':        /* Override preference from command line */
1179         switch (prefs_set_pref(optarg)) {
1180
1181         case PREFS_SET_OK:
1182           break;
1183
1184         case PREFS_SET_SYNTAX_ERR:
1185           cmdarg_err("Invalid -o flag \"%s\"", optarg);
1186           return 1;
1187           break;
1188
1189         case PREFS_SET_NO_SUCH_PREF:
1190         case PREFS_SET_OBSOLETE:
1191           cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1192           return 1;
1193           break;
1194         }
1195         break;
1196       case 'q':        /* Quiet */
1197         quiet = TRUE;
1198         break;
1199       case 'r':        /* Read capture file x */
1200         cf_name = g_strdup(optarg);
1201         break;
1202       case 'R':        /* Read file filter */
1203         rfilter = optarg;
1204         break;
1205       case 'S':        /* show packets in real time */
1206         print_packet_info = TRUE;
1207         break;
1208       case 't':        /* Time stamp type */
1209         if (strcmp(optarg, "r") == 0)
1210           timestamp_set_type(TS_RELATIVE);
1211         else if (strcmp(optarg, "a") == 0)
1212           timestamp_set_type(TS_ABSOLUTE);
1213         else if (strcmp(optarg, "ad") == 0)
1214           timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1215         else if (strcmp(optarg, "d") == 0)
1216           timestamp_set_type(TS_DELTA);
1217         else if (strcmp(optarg, "dd") == 0)
1218           timestamp_set_type(TS_DELTA_DIS);
1219         else if (strcmp(optarg, "e") == 0)
1220           timestamp_set_type(TS_EPOCH);
1221         else {
1222           cmdarg_err("Invalid time stamp type \"%s\"",
1223             optarg);
1224           cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1225           cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1226           return 1;
1227         }
1228         break;
1229       case 'T':        /* printing Type */
1230         if (strcmp(optarg, "text") == 0) {
1231           output_action = WRITE_TEXT;
1232           print_format = PR_FMT_TEXT;
1233         } else if (strcmp(optarg, "ps") == 0) {
1234           output_action = WRITE_TEXT;
1235           print_format = PR_FMT_PS;
1236         } else if (strcmp(optarg, "pdml") == 0) {
1237           output_action = WRITE_XML;
1238           verbose = TRUE;
1239         } else if (strcmp(optarg, "psml") == 0) {
1240           output_action = WRITE_XML;
1241           verbose = FALSE;
1242         } else if(strcmp(optarg, "fields") == 0) {
1243           output_action = WRITE_FIELDS;
1244           verbose = TRUE; /* Need full tree info */
1245         } else {
1246           cmdarg_err("Invalid -T parameter.");
1247           cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1248           return 1;
1249         }
1250         break;
1251       case 'u':        /* Seconds type */
1252         if (strcmp(optarg, "s") == 0)
1253           timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1254         else if (strcmp(optarg, "hms") == 0)
1255           timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1256         else {
1257           cmdarg_err("Invalid seconds type \"%s\"", optarg);
1258           cmdarg_err_cont("It must be \"s\" for seconds or \"hms\" for hours, minutes and seconds.");
1259           return 1;
1260         }
1261         break;
1262       case 'v':         /* Show version and exit */
1263       {
1264         GString             *comp_info_str;
1265         GString             *runtime_info_str;
1266         /* Assemble the compile-time version information string */
1267         comp_info_str = g_string_new("Compiled ");
1268         get_compiled_version_info(comp_info_str, NULL, epan_get_compiled_version_info);
1269
1270         /* Assemble the run-time version information string */
1271         runtime_info_str = g_string_new("Running ");
1272         get_runtime_version_info(runtime_info_str, NULL);
1273         show_version(comp_info_str, runtime_info_str);
1274         g_string_free(comp_info_str, TRUE);
1275         g_string_free(runtime_info_str, TRUE);
1276         return 0;
1277         break;
1278       }
1279       case 'V':        /* Verbose */
1280         verbose = TRUE;
1281         /*  The user asked for a verbose output, so let's ensure they get it,
1282          *  even if they're writing to a file.
1283          */
1284         print_packet_info = TRUE;
1285         break;
1286       case 'x':        /* Print packet data in hex (and ASCII) */
1287         print_hex = TRUE;
1288         /*  The user asked for hex output, so let's ensure they get it,
1289          *  even if they're writing to a file.
1290          */
1291         print_packet_info = TRUE;
1292         break;
1293       case 'X':
1294         break;
1295       case 'z':
1296         /* We won't call the init function for the stat this soon
1297            as it would disallow MATE's fields (which are registered
1298            by the preferences set callback) from being used as
1299            part of a tap filter.  Instead, we just add the argument
1300            to a list of stat arguments. */
1301         if (!process_stat_cmd_arg(optarg)) {
1302           cmdarg_err("invalid -z argument.");
1303           cmdarg_err_cont("  -z argument must be one of :");
1304           list_stat_cmd_args();
1305           return 1;
1306         }
1307         break;
1308       default:
1309       case '?':        /* Bad flag - print usage message */
1310         switch(optopt) {
1311         case 'F':
1312           list_capture_types();
1313           break;
1314         default:
1315           print_usage(TRUE);
1316         }
1317         return 1;
1318         break;
1319     }
1320   }
1321
1322   /* If we specified output fields, but not the output field type... */
1323   if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1324         cmdarg_err("Output fields were specified with \"-e\", "
1325             "but \"-Tfields\" was not specified.");
1326         return 1;
1327   } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1328         cmdarg_err("\"-Tfields\" was specified, but no fields were "
1329                     "specified with \"-e\".");
1330
1331         return 1;
1332   }
1333
1334   /* If no capture filter or read filter has been specified, and there are
1335      still command-line arguments, treat them as the tokens of a capture
1336      filter (if no "-r" flag was specified) or a read filter (if a "-r"
1337      flag was specified. */
1338   if (optind < argc) {
1339     if (cf_name != NULL) {
1340       if (rfilter != NULL) {
1341         cmdarg_err("Read filters were specified both with \"-R\" "
1342             "and with additional command-line arguments");
1343         return 1;
1344       }
1345       rfilter = get_args_as_string(argc, argv, optind);
1346     } else {
1347 #ifdef HAVE_LIBPCAP
1348       if (global_capture_opts.has_cfilter) {
1349         cmdarg_err("Capture filters were specified both with \"-f\""
1350             " and with additional command-line arguments");
1351         return 1;
1352       }
1353       global_capture_opts.has_cfilter = TRUE;
1354       global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1355 #else
1356       capture_option_specified = TRUE;
1357 #endif
1358     }
1359   }
1360
1361 #ifdef HAVE_LIBPCAP
1362   if (!global_capture_opts.saving_to_file) {
1363     /* We're not saving the capture to a file; if "-q" wasn't specified,
1364        we should print packet information */
1365     if (!quiet)
1366       print_packet_info = TRUE;
1367   } else {
1368     /* We're saving to a file; if we're writing to the standard output.
1369        and we'll also be writing dissected packets to the standard
1370        output, reject the request.  At best, we could redirect that
1371        to the standard error; we *can't* write both to the standard
1372        output and have either of them be useful. */
1373     if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1374       cmdarg_err("You can't write both raw packet data and dissected packets"
1375           " to the standard output.");
1376       return 1;
1377     }
1378   }
1379 #else
1380   /* We're not saving the capture to a file; if "-q" wasn't specified,
1381      we should print packet information */
1382   if (!quiet)
1383     print_packet_info = TRUE;
1384 #endif
1385
1386 #ifndef HAVE_LIBPCAP
1387   if (capture_option_specified)
1388     cmdarg_err("This version of TShark was not built with support for capturing packets.");
1389 #endif
1390   if (arg_error) {
1391     print_usage(FALSE);
1392     return 1;
1393   }
1394
1395   /* We don't support capture filters when reading from a capture file
1396      (the BPF compiler doesn't support all link-layer types that we
1397      support in capture files we read). */
1398 #ifdef HAVE_LIBPCAP
1399   if (cf_name != NULL) {
1400     if (global_capture_opts.has_cfilter) {
1401       cmdarg_err("Only read filters, not capture filters, "
1402           "can be specified when reading a capture file.");
1403       return 1;
1404     }
1405   }
1406 #endif
1407
1408   if (print_hex) {
1409     if (output_action != WRITE_TEXT) {
1410       cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1411       return 1;
1412     }
1413   }
1414
1415 #ifdef HAVE_LIBPCAP
1416   if (list_link_layer_types) {
1417     /* We're supposed to list the link-layer types for an interface;
1418        did the user also specify a capture file to be read? */
1419     if (cf_name) {
1420       /* Yes - that's bogus. */
1421       cmdarg_err("You can't specify -L and a capture file to be read.");
1422       return 1;
1423     }
1424     /* No - did they specify a ring buffer option? */
1425     if (global_capture_opts.multi_files_on) {
1426       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1427       return 1;
1428     }
1429   } else {
1430     if (cf_name) {
1431       /*
1432        * "-r" was specified, so we're reading a capture file.
1433        * Capture options don't apply here.
1434        */
1435       if (global_capture_opts.multi_files_on) {
1436         cmdarg_err("Multiple capture files requested, but "
1437                    "a capture isn't being done.");
1438         return 1;
1439       }
1440       if (global_capture_opts.has_file_duration) {
1441         cmdarg_err("Switching capture files after a time interval was specified, but "
1442                    "a capture isn't being done.");
1443         return 1;
1444       }
1445       if (global_capture_opts.has_ring_num_files) {
1446         cmdarg_err("A ring buffer of capture files was specified, but "
1447           "a capture isn't being done.");
1448         return 1;
1449       }
1450       if (global_capture_opts.has_autostop_files) {
1451         cmdarg_err("A maximum number of capture files was specified, but "
1452           "a capture isn't being done.");
1453         return 1;
1454       }
1455
1456       /* Note: TShark now allows the restriction of a _read_ file by packet count
1457        * and byte count as well as a write file. Other autostop options remain valid
1458        * only for a write file.
1459        */
1460       if (global_capture_opts.has_autostop_duration) {
1461         cmdarg_err("A maximum capture time was specified, but "
1462           "a capture isn't being done.");
1463         return 1;
1464       }
1465     } else {
1466       /*
1467        * "-r" wasn't specified, so we're doing a live capture.
1468        */
1469       if (global_capture_opts.saving_to_file) {
1470         /* They specified a "-w" flag, so we'll be saving to a capture file. */
1471
1472         /* When capturing, we only support writing libpcap format. */
1473         if (out_file_type != WTAP_FILE_PCAP) {
1474           cmdarg_err("Live captures can only be saved in libpcap format.");
1475           return 1;
1476         }
1477         if (global_capture_opts.multi_files_on) {
1478           /* Multiple-file mode doesn't work under certain conditions:
1479              a) it doesn't work if you're writing to the standard output;
1480              b) it doesn't work if you're writing to a pipe;
1481           */
1482           if (strcmp(global_capture_opts.save_file, "-") == 0) {
1483             cmdarg_err("Multiple capture files requested, but "
1484               "the capture is being written to the standard output.");
1485             return 1;
1486           }
1487           if (global_capture_opts.output_to_pipe) {
1488             cmdarg_err("Multiple capture files requested, but "
1489               "the capture file is a pipe.");
1490             return 1;
1491           }
1492           if (!global_capture_opts.has_autostop_filesize &&
1493               !global_capture_opts.has_file_duration) {
1494             cmdarg_err("Multiple capture files requested, but "
1495               "no maximum capture file size or duration was specified.");
1496             return 1;
1497           }
1498         }
1499         /* Currently, we don't support read filters when capturing
1500            and saving the packets. */
1501         if (rfilter != NULL) {
1502           cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1503           return 1;
1504         }
1505       } else {
1506         /* They didn't specify a "-w" flag, so we won't be saving to a
1507            capture file.  Check for options that only make sense if
1508            we're saving to a file. */
1509         if (global_capture_opts.has_autostop_filesize) {
1510           cmdarg_err("Maximum capture file size specified, but "
1511            "capture isn't being saved to a file.");
1512           return 1;
1513         }
1514         if (global_capture_opts.multi_files_on) {
1515           cmdarg_err("Multiple capture files requested, but "
1516             "the capture isn't being saved to a file.");
1517           return 1;
1518         }
1519       }
1520     }
1521   }
1522 #endif
1523
1524 #ifdef _WIN32
1525   /* Start windows sockets */
1526   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1527 #endif /* _WIN32 */
1528
1529   /* Notify all registered modules that have had any of their preferences
1530      changed either from one of the preferences file or from the command
1531      line that their preferences have changed. */
1532   prefs_apply_all();
1533
1534   /* At this point MATE will have registered its field array so we can
1535      have a tap filter with one of MATE's late-registered fields as part
1536      of the filter.  We can now process all the "-z" arguments. */
1537   start_requested_stats();
1538
1539 #ifdef HAVE_LIBPCAP
1540   /* We currently don't support taps, or printing dissected packets,
1541      if we're writing to a pipe. */
1542   if (global_capture_opts.saving_to_file &&
1543       global_capture_opts.output_to_pipe) {
1544     if (have_tap_listeners()) {
1545       cmdarg_err("Taps aren't supported when saving to a pipe.");
1546       return 1;
1547     }
1548     if (print_packet_info) {
1549       cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1550       return 1;
1551     }
1552   }
1553 #endif
1554
1555   /* disabled protocols as per configuration file */
1556   if (gdp_path == NULL && dp_path == NULL) {
1557     set_disabled_protos_list();
1558   }
1559
1560   /* Build the column format array */
1561   build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1562
1563 #ifdef HAVE_LIBPCAP
1564   capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1565   capture_opts_trim_ring_num_files(&global_capture_opts);
1566 #endif
1567
1568   if (rfilter != NULL) {
1569     if (!dfilter_compile(rfilter, &rfcode)) {
1570       cmdarg_err("%s", dfilter_error_msg);
1571       epan_cleanup();
1572 #ifdef HAVE_PCAP_OPEN_DEAD
1573       {
1574         pcap_t *pc;
1575
1576         pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1577         if (pc != NULL) {
1578           if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1579             cmdarg_err_cont(
1580               "  Note: That display filter code looks like a valid capture filter;");
1581             cmdarg_err_cont(
1582               "        maybe you mixed them up?");
1583           }
1584           pcap_close(pc);
1585         }
1586       }
1587 #endif
1588       return 2;
1589     }
1590   }
1591   cfile.rfcode = rfcode;
1592
1593   if (print_packet_info) {
1594     /* If we're printing as text or PostScript, we have
1595        to create a print stream. */
1596     if (output_action == WRITE_TEXT) {
1597       switch (print_format) {
1598
1599       case PR_FMT_TEXT:
1600         print_stream = print_stream_text_stdio_new(stdout);
1601         break;
1602
1603       case PR_FMT_PS:
1604         print_stream = print_stream_ps_stdio_new(stdout);
1605         break;
1606
1607       default:
1608         g_assert_not_reached();
1609       }
1610     }
1611   }
1612
1613   /* We have to dissect each packet if:
1614
1615         we're printing information about each packet;
1616
1617         we're using a read filter on the packets;
1618
1619         we're using any taps. */
1620   do_dissection = print_packet_info || rfcode || have_tap_listeners();
1621
1622   if (cf_name) {
1623     /*
1624      * We're reading a capture file.
1625      */
1626
1627     /*
1628      * Immediately relinquish any special privileges we have; we must not
1629      * be allowed to read any capture files the user running TShark
1630      * can't open.
1631      */
1632     relinquish_special_privs_perm();
1633     print_current_user();
1634
1635     if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1636       epan_cleanup();
1637       return 2;
1638     }
1639
1640     /* Set timestamp precision; there should arguably be a command-line
1641        option to let the user set this. */
1642     switch(wtap_file_tsprecision(cfile.wth)) {
1643     case(WTAP_FILE_TSPREC_SEC):
1644       timestamp_set_precision(TS_PREC_AUTO_SEC);
1645       break;
1646     case(WTAP_FILE_TSPREC_DSEC):
1647       timestamp_set_precision(TS_PREC_AUTO_DSEC);
1648       break;
1649     case(WTAP_FILE_TSPREC_CSEC):
1650       timestamp_set_precision(TS_PREC_AUTO_CSEC);
1651       break;
1652     case(WTAP_FILE_TSPREC_MSEC):
1653       timestamp_set_precision(TS_PREC_AUTO_MSEC);
1654       break;
1655     case(WTAP_FILE_TSPREC_USEC):
1656       timestamp_set_precision(TS_PREC_AUTO_USEC);
1657       break;
1658     case(WTAP_FILE_TSPREC_NSEC):
1659       timestamp_set_precision(TS_PREC_AUTO_NSEC);
1660       break;
1661     default:
1662       g_assert_not_reached();
1663     }
1664
1665     /* Process the packets in the file */
1666 #ifdef HAVE_LIBPCAP
1667     err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1668         global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1669         global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1670 #else
1671     err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1672 #endif
1673     if (err != 0) {
1674       /* We still dump out the results of taps, etc., as we might have
1675          read some packets; however, we exit with an error status. */
1676       exit_status = 2;
1677     }
1678   } else {
1679     /* No capture file specified, so we're supposed to do a live capture
1680        (or get a list of link-layer types for a live capture device);
1681        do we have support for live captures? */
1682 #ifdef HAVE_LIBPCAP
1683
1684 #ifdef _WIN32
1685     if (!has_wpcap) {
1686       char *detailed_err;
1687
1688       cmdarg_err("WinPcap couldn't be found.");
1689       detailed_err = cant_load_winpcap_err("TShark");
1690       cmdarg_err_cont("%s", detailed_err);
1691       g_free(detailed_err);
1692       return 2;
1693     }
1694 #endif
1695
1696     /* trim the interface name and exit if that failed */
1697     if (!capture_opts_trim_iface(&global_capture_opts,
1698         (prefs_p->capture_device) ? get_if_name(prefs_p->capture_device) : NULL)) {
1699         return 2;
1700     }
1701
1702     /* if requested, list the link layer types and exit */
1703     if (list_link_layer_types) {
1704         /* Get the list of link-layer types for the capture device. */
1705         if_capabilities_t *caps;
1706
1707         caps = capture_get_if_capabilities(global_capture_opts.iface,
1708                                            global_capture_opts.monitor_mode,
1709                                            &err_str);
1710         if (caps == NULL) {
1711             cmdarg_err("%s", err_str);
1712             g_free(err_str);
1713             return 2;
1714         }
1715         if (caps->data_link_types == NULL) {
1716             cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
1717             return 2;
1718         }
1719         capture_opts_print_if_capabilities(caps,
1720                                            global_capture_opts.monitor_mode);
1721         free_if_capabilities(caps);
1722         return 0;
1723     }
1724
1725     if (print_packet_info) {
1726       if (!write_preamble(NULL)) {
1727         show_print_file_io_error(errno);
1728         return 2;
1729       }
1730     } else if (!quiet) {
1731       /*
1732        * We're not printing information for each packet, and the user
1733        * didn't ask us not to print a count of packets as they arrive,
1734        * so print that count so the user knows that packets are arriving.
1735        *
1736        * XXX - what if the user wants to do a live capture, doesn't want
1737        * to save it to a file, doesn't want information printed for each
1738        * packet, does want some "-z" statistic, and wants packet counts
1739        * so they know whether they're seeing any packets?
1740        */
1741       print_packet_counts = TRUE;
1742     }
1743
1744     /* For now, assume libpcap gives microsecond precision. */
1745     timestamp_set_precision(TS_PREC_AUTO_USEC);
1746
1747     /*
1748      * XXX - this returns FALSE if an error occurred, but it also
1749      * returns FALSE if the capture stops because a time limit
1750      * was reached (and possibly other limits), so we can't assume
1751      * it means an error.
1752      *
1753      * The capture code is a bit twisty, so it doesn't appear to
1754      * be an easy fix.  We just ignore the return value for now.
1755      * Instead, pass on the exit status from the capture child.
1756      */
1757     capture();
1758     exit_status = global_capture_opts.fork_child_status;
1759
1760     if (print_packet_info) {
1761       if (!write_finale()) {
1762         err = errno;
1763         show_print_file_io_error(err);
1764       }
1765     }
1766 #else
1767     /* No - complain. */
1768     cmdarg_err("This version of TShark was not built with support for capturing packets.");
1769     return 2;
1770 #endif
1771   }
1772
1773   g_free(cf_name);
1774
1775 #if GLIB_CHECK_VERSION(2,10,0)
1776   if (cfile.plist_start != NULL)
1777     g_slice_free_chain(frame_data, cfile.plist_start, next);
1778 #endif
1779
1780   draw_tap_listeners(TRUE);
1781   funnel_dump_all_text_windows();
1782   epan_cleanup();
1783
1784   output_fields_free(output_fields);
1785   output_fields = NULL;
1786
1787   return exit_status;
1788 }
1789
1790 /*#define USE_BROKEN_G_MAIN_LOOP*/
1791
1792 #ifdef USE_BROKEN_G_MAIN_LOOP
1793   GMainLoop *loop;
1794 #else
1795   gboolean loop_running = FALSE;
1796 #endif
1797   guint32 packet_count = 0;
1798
1799
1800 /* XXX - move to the right position / file */
1801 /* read from a pipe (callback) */
1802 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1803
1804 typedef struct pipe_input_tag {
1805     gint                source;
1806     gpointer            user_data;
1807     int                 *child_process;
1808     pipe_input_cb_t     input_cb;
1809     guint               pipe_input_id;
1810 #ifdef _WIN32
1811     GStaticMutex        callback_running;
1812 #endif
1813 } pipe_input_t;
1814
1815 static pipe_input_t pipe_input;
1816
1817 #ifdef _WIN32
1818 /* The timer has expired, see if there's stuff to read from the pipe,
1819    if so, do the callback */
1820 static gint
1821 pipe_timer_cb(gpointer data)
1822 {
1823   HANDLE handle;
1824   DWORD avail = 0;
1825   gboolean result, result1;
1826   DWORD childstatus;
1827   pipe_input_t *pipe_input = data;
1828   gint iterations = 0;
1829
1830
1831   g_static_mutex_lock (&pipe_input->callback_running);
1832
1833   /* try to read data from the pipe only 5 times, to avoid blocking */
1834   while(iterations < 5) {
1835     /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1836
1837     /* Oddly enough although Named pipes don't work on win9x,
1838        PeekNamedPipe does !!! */
1839     handle = (HANDLE) _get_osfhandle (pipe_input->source);
1840     result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1841
1842     /* Get the child process exit status */
1843     result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1844                                  &childstatus);
1845
1846     /* If the Peek returned an error, or there are bytes to be read
1847        or the childwatcher thread has terminated then call the normal
1848        callback */
1849     if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1850
1851       /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1852
1853       /* And call the real handler */
1854       if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1855         g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1856         /* pipe closed, return false so that the timer is stopped */
1857         g_static_mutex_unlock (&pipe_input->callback_running);
1858         return FALSE;
1859       }
1860     }
1861     else {
1862       /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1863       /* No data, stop now */
1864       break;
1865     }
1866
1867     iterations++;
1868   }
1869
1870   /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1871
1872   g_static_mutex_unlock (&pipe_input->callback_running);
1873
1874   /* we didn't stopped the timer, so let it run */
1875   return TRUE;
1876 }
1877 #endif
1878
1879
1880 void
1881 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1882 {
1883
1884   pipe_input.source         = source;
1885   pipe_input.child_process  = child_process;
1886   pipe_input.user_data      = user_data;
1887   pipe_input.input_cb       = input_cb;
1888
1889 #ifdef _WIN32
1890   g_static_mutex_init(&pipe_input.callback_running);
1891   /* Tricky to use pipes in win9x, as no concept of wait.  NT can
1892      do this but that doesn't cover all win32 platforms.  GTK can do
1893      this but doesn't seem to work over processes.  Attempt to do
1894      something similar here, start a timer and check for data on every
1895      timeout. */
1896   /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1897   pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1898 #endif
1899 }
1900
1901
1902 #ifdef HAVE_LIBPCAP
1903 static gboolean
1904 capture(void)
1905 {
1906   gboolean ret;
1907 #ifdef USE_TSHARK_SELECT
1908   fd_set readfds;
1909 #endif
1910 #ifndef _WIN32
1911   struct sigaction action, oldaction;
1912 #endif
1913
1914   /*
1915    * XXX - dropping privileges is still required, until code cleanup is done
1916    *
1917    * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1918    * when it's done, we don't need special privileges to run tshark at all,
1919    * therefore we don't need to drop these privileges
1920    * The only thing we might want to keep is a warning if tshark is run as root,
1921    * as it's no longer necessary and potentially dangerous.
1922    *
1923    * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1924    * We've opened the capture device, so we shouldn't need any special
1925    * privileges any more; relinquish those privileges.
1926    *
1927    * XXX - if we have saved set-user-ID support, we should give up those
1928    * privileges immediately, and then reclaim them long enough to get
1929    * a list of network interfaces and to open one, and then give them
1930    * up again, so that stuff we do while processing the argument list,
1931    * reading the user's preferences, loading and starting plugins
1932    * (especially *user* plugins), etc. is done with the user's privileges,
1933    * not special privileges.
1934    */
1935   relinquish_special_privs_perm();
1936   print_current_user();
1937
1938   /* Cleanup all data structures used for dissection. */
1939   cleanup_dissection();
1940   /* Initialize all data structures used for dissection. */
1941   init_dissection();
1942
1943 #ifdef _WIN32
1944   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1945   SetConsoleCtrlHandler(capture_cleanup, TRUE);
1946 #else /* _WIN32 */
1947   /* Catch SIGINT and SIGTERM and, if we get either of them,
1948      clean up and exit.  If SIGHUP isn't being ignored, catch
1949      it too and, if we get it, clean up and exit.
1950
1951      We restart any read that was in progress, so that it doesn't
1952      disrupt reading from the sync pipe.  The signal handler tells
1953      the capture child to finish; it will report that it finished,
1954      or will exit abnormally, so  we'll stop reading from the sync
1955      pipe, pick up the exit status, and quit. */
1956   action.sa_handler = capture_cleanup;
1957   action.sa_flags = SA_RESTART;
1958   sigemptyset(&action.sa_mask);
1959   sigaction(SIGTERM, &action, NULL);
1960   sigaction(SIGINT, &action, NULL);
1961   sigaction(SIGHUP, NULL, &oldaction);
1962   if (oldaction.sa_handler == SIG_DFL)
1963     sigaction(SIGHUP, &action, NULL);
1964
1965 #ifdef SIGINFO
1966   /* Catch SIGINFO and, if we get it and we're capturing to a file in
1967      quiet mode, report the number of packets we've captured.
1968
1969      Again, restart any read that was in progress, so that it doesn't
1970      disrupt reading from the sync pipe. */
1971   action.sa_handler = report_counts_siginfo;
1972   action.sa_flags = SA_RESTART;
1973   sigemptyset(&action.sa_mask);
1974   sigaction(SIGINFO, &action, NULL);
1975 #endif /* SIGINFO */
1976 #endif /* _WIN32 */
1977
1978   global_capture_opts.state = CAPTURE_PREPARING;
1979
1980   /* Let the user know what interface was chosen. */
1981   global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1982   fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1983
1984   ret = sync_pipe_start(&global_capture_opts);
1985
1986   if (!ret)
1987     return FALSE;
1988
1989   /* the actual capture loop
1990    *
1991    * XXX - glib doesn't seem to provide any event based loop handling.
1992    *
1993    * XXX - for whatever reason,
1994    * calling g_main_loop_new() ends up in 100% cpu load.
1995    *
1996    * But that doesn't matter: in UNIX we can use select() to find an input
1997    * source with something to do.
1998    *
1999    * But that doesn't matter because we're in a CLI (that doesn't need to
2000    * update a GUI or something at the same time) so it's OK if we block
2001    * trying to read from the pipe.
2002    *
2003    * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2004    * wrong (but I leave it there in case I am...).
2005    */
2006
2007 #ifdef USE_TSHARK_SELECT
2008   FD_ZERO(&readfds);
2009   FD_SET(pipe_input.source, &readfds);
2010 #endif
2011
2012   loop_running = TRUE;
2013
2014   while (loop_running)
2015   {
2016 #ifdef USE_TSHARK_SELECT
2017     ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2018
2019     if (ret == -1)
2020     {
2021       perror("select()");
2022       return TRUE;
2023     } else if (ret == 1) {
2024 #endif
2025       /* Call the real handler */
2026       if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2027         g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2028         return FALSE;
2029       }
2030 #ifdef USE_TSHARK_SELECT
2031     }
2032 #endif
2033   }
2034
2035   return TRUE;
2036 }
2037
2038
2039 /* XXX - move the call to main_window_update() out of capture_sync.c */
2040 /* dummy for capture_sync.c to make linker happy */
2041 void main_window_update(void)
2042 {
2043 }
2044
2045 /* capture child detected an error */
2046 void
2047 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
2048 {
2049   cmdarg_err("%s", error_msg);
2050   cmdarg_err_cont("%s", secondary_error_msg);
2051 }
2052
2053
2054 /* capture child detected an capture filter related error */
2055 void
2056 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
2057 {
2058   dfilter_t   *rfcode = NULL;
2059
2060
2061   if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
2062     cmdarg_err(
2063       "Invalid capture filter: \"%s\"!\n"
2064       "\n"
2065       "That string looks like a valid display filter; however, it isn't a valid\n"
2066       "capture filter (%s).\n"
2067       "\n"
2068       "Note that display filters and capture filters don't have the same syntax,\n"
2069       "so you can't use most display filter expressions as capture filters.\n"
2070       "\n"
2071       "See the User's Guide for a description of the capture filter syntax.",
2072       capture_opts->cfilter, error_message);
2073     dfilter_free(rfcode);
2074   } else {
2075     cmdarg_err(
2076       "Invalid capture filter: \"%s\"!\n"
2077       "\n"
2078       "That string isn't a valid capture filter (%s).\n"
2079       "See the User's Guide for a description of the capture filter syntax.",
2080       capture_opts->cfilter, error_message);
2081   }
2082 }
2083
2084
2085 /* capture child tells us we have a new (or the first) capture file */
2086 gboolean
2087 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
2088 {
2089   gboolean is_tempfile;
2090   int  err;
2091
2092   if(capture_opts->state == CAPTURE_PREPARING) {
2093     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
2094   }
2095   g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2096
2097   g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
2098
2099   /* free the old filename */
2100   if (capture_opts->save_file != NULL) {
2101
2102     /* we start a new capture file, close the old one (if we had one before) */
2103     if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
2104       if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
2105         wtap_close(((capture_file *) capture_opts->cf)->wth);
2106       }
2107       ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
2108     }
2109
2110     g_free(capture_opts->save_file);
2111     is_tempfile = FALSE;
2112   } else {
2113     /* we didn't had a save_file before, must be a tempfile */
2114     is_tempfile = TRUE;
2115   }
2116
2117   /* save the new filename */
2118   capture_opts->save_file = g_strdup(new_file);
2119
2120   /* if we are in real-time mode, open the new file now */
2121   if(do_dissection) {
2122     /* Attempt to open the capture file and set up to read from it. */
2123     switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
2124     case CF_OK:
2125       break;
2126     case CF_ERROR:
2127       /* Don't unlink (delete) the save file - leave it around,
2128          for debugging purposes. */
2129       g_free(capture_opts->save_file);
2130       capture_opts->save_file = NULL;
2131       return FALSE;
2132     }
2133   }
2134
2135   capture_opts->state = CAPTURE_RUNNING;
2136
2137   return TRUE;
2138 }
2139
2140
2141 /* capture child tells us we have new packets to read */
2142 void
2143 capture_input_new_packets(capture_options *capture_opts, int to_read)
2144 {
2145   gboolean     ret;
2146   int          err;
2147   gchar        *err_info;
2148   gint64       data_offset;
2149   capture_file *cf = capture_opts->cf;
2150   gboolean filtering_tap_listeners;
2151   guint tap_flags;
2152
2153 #ifdef SIGINFO
2154   /*
2155    * Prevent a SIGINFO handler from writing to the standard error while
2156    * we're doing so or writing to the standard output; instead, have it
2157    * just set a flag telling us to print that information when we're done.
2158    */
2159   infodelay = TRUE;
2160 #endif /* SIGINFO */
2161
2162   /* Do we have any tap listeners with filters? */
2163   filtering_tap_listeners = have_filtering_tap_listeners();
2164
2165   /* Get the union of the flags for all tap listeners. */
2166   tap_flags = union_of_tap_listener_flags();
2167
2168   if(do_dissection) {
2169     while (to_read-- && cf->wth) {
2170       wtap_cleareof(cf->wth);
2171       ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2172       if(ret == FALSE) {
2173         /* read from file failed, tell the capture child to stop */
2174         sync_pipe_stop(capture_opts);
2175         wtap_close(cf->wth);
2176         cf->wth = NULL;
2177       } else {
2178         ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2179                              wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2180                              filtering_tap_listeners, tap_flags);
2181       }
2182       if (ret != FALSE) {
2183         /* packet sucessfully read and gone through the "Read Filter" */
2184         packet_count++;
2185       }
2186     }
2187   } else {
2188     /*
2189      * Dumpcap's doing all the work; we're not doing any dissection.
2190      * Count all the packets it wrote.
2191      */
2192     packet_count += to_read;
2193   }
2194
2195   if (print_packet_counts) {
2196       /* We're printing packet counts. */
2197       if (packet_count != 0) {
2198         fprintf(stderr, "\r%u ", packet_count);
2199         /* stderr could be line buffered */
2200         fflush(stderr);
2201       }
2202   }
2203
2204 #ifdef SIGINFO
2205   /*
2206    * Allow SIGINFO handlers to write.
2207    */
2208   infodelay = FALSE;
2209
2210   /*
2211    * If a SIGINFO handler asked us to write out capture counts, do so.
2212    */
2213   if (infoprint)
2214     report_counts();
2215 #endif /* SIGINFO */
2216 }
2217
2218 static void
2219 report_counts(void)
2220 {
2221   if (!print_packet_counts) {
2222     /* Report the count only if we aren't printing a packet count
2223        as packets arrive. */
2224     fprintf(stderr, "%u packet%s captured\n", packet_count,
2225             plurality(packet_count, "", "s"));
2226   }
2227 #ifdef SIGINFO
2228   infoprint = FALSE; /* we just reported it */
2229 #endif /* SIGINFO */
2230 }
2231
2232 #ifdef SIGINFO
2233 static void
2234 report_counts_siginfo(int signum _U_)
2235 {
2236   int sav_errno = errno;
2237   /* If we've been told to delay printing, just set a flag asking
2238      that we print counts (if we're supposed to), otherwise print
2239      the count of packets captured (if we're supposed to). */
2240   if (infodelay)
2241     infoprint = TRUE;
2242   else
2243     report_counts();
2244   errno = sav_errno;
2245 }
2246 #endif /* SIGINFO */
2247
2248
2249 /* capture child detected any packet drops? */
2250 void
2251 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2252 {
2253   if (print_packet_counts) {
2254     /* We're printing packet counts to stderr.
2255        Send a newline so that we move to the line after the packet count. */
2256     fprintf(stderr, "\n");
2257   }
2258
2259   if (dropped != 0) {
2260     /* We're printing packet counts to stderr.
2261        Send a newline so that we move to the line after the packet count. */
2262     fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2263   }
2264 }
2265
2266
2267 /*
2268  * Capture child closed its side of the pipe, report any error and
2269  * do the required cleanup.
2270  */
2271 void
2272 capture_input_closed(capture_options *capture_opts, gchar *msg)
2273 {
2274   if (msg != NULL)
2275     fprintf(stderr, "tshark: %s\n", msg);
2276
2277   report_counts();
2278
2279   if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2280     wtap_close(((capture_file *) capture_opts->cf)->wth);
2281         if(((capture_file *) capture_opts->cf)->user_saved == FALSE){
2282                 ws_unlink(((capture_file *) capture_opts->cf)->filename);
2283         }
2284   }
2285 #ifdef USE_BROKEN_G_MAIN_LOOP
2286   /*g_main_loop_quit(loop);*/
2287   g_main_quit(loop);
2288 #else
2289   loop_running = FALSE;
2290 #endif
2291 }
2292
2293
2294
2295
2296 #ifdef _WIN32
2297 static BOOL WINAPI
2298 capture_cleanup(DWORD ctrltype _U_)
2299 {
2300   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2301      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2302      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2303      like SIGTERM at least when the machine's shutting down.
2304
2305      For now, we handle them all as indications that we should clean up
2306      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2307      way on UNIX.
2308
2309      We must return TRUE so that no other handler - such as one that would
2310      terminate the process - gets called.
2311
2312      XXX - for some reason, typing ^C to TShark, if you run this in
2313      a Cygwin console window in at least some versions of Cygwin,
2314      causes TShark to terminate immediately; this routine gets
2315      called, but the main loop doesn't get a chance to run and
2316      exit cleanly, at least if this is compiled with Microsoft Visual
2317      C++ (i.e., it's a property of the Cygwin console window or Bash;
2318      it happens if TShark is not built with Cygwin - for all I know,
2319      building it with Cygwin may make the problem go away). */
2320
2321   /* tell the capture child to stop */
2322   sync_pipe_stop(&global_capture_opts);
2323
2324   /* don't stop our own loop already here, otherwise status messages and
2325    * cleanup wouldn't be done properly. The child will indicate the stop of
2326    * everything by calling capture_input_closed() later */
2327
2328   return TRUE;
2329 }
2330 #else
2331 static void
2332 capture_cleanup(int signum _U_)
2333 {
2334   /* tell the capture child to stop */
2335   sync_pipe_stop(&global_capture_opts);
2336
2337   /* don't stop our own loop already here, otherwise status messages and
2338    * cleanup wouldn't be done properly. The child will indicate the stop of
2339    * everything by calling capture_input_closed() later */
2340 }
2341 #endif /* _WIN32 */
2342 #endif /* HAVE_LIBPCAP */
2343
2344 #if GLIB_CHECK_VERSION(2,10,0)
2345 static gboolean
2346 process_packet_first_pass(capture_file *cf,
2347                gint64 offset, const struct wtap_pkthdr *whdr,
2348                union wtap_pseudo_header *pseudo_header, const guchar *pd)
2349 {
2350   frame_data *fdata = g_slice_new(frame_data);
2351   epan_dissect_t edt;
2352   gboolean passed;
2353
2354   /* Count this packet. */
2355   cf->count++;
2356
2357   /* If we're not running a display filter and we're not printing any
2358      packet information, we don't need to do a dissection. This means
2359      that all packets can be marked as 'passed'. */
2360   passed = TRUE;
2361
2362   frame_data_init(fdata, cf->count, whdr, offset, cum_bytes);
2363
2364   /* If we're going to print packet information, or we're going to
2365      run a read filter, or we're going to process taps, set up to
2366      do a dissection and do so. */
2367   if (do_dissection) {
2368     if (gbl_resolv_flags)
2369       /* Grab any resolved addresses */
2370       host_name_lookup_process(NULL);
2371
2372     /* The protocol tree will be "visible", i.e., printed, only if we're
2373        printing packet details, which is true if we're printing stuff
2374        ("print_packet_info" is true) and we're in verbose mode ("verbose"
2375        is true). */
2376     epan_dissect_init(&edt, FALSE, FALSE);
2377
2378     /* If we're running a read filter, prime the epan_dissect_t with that
2379        filter. */
2380     if (cf->rfcode)
2381       epan_dissect_prime_dfilter(&edt, cf->rfcode);
2382
2383     frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2384                                   &first_ts, &prev_dis_ts, &prev_cap_ts);
2385
2386     epan_dissect_run(&edt, pseudo_header, pd, fdata, NULL);
2387
2388     /* Run the read filter if we have one. */
2389     if (cf->rfcode)
2390       passed = dfilter_apply_edt(cf->rfcode, &edt);
2391   }
2392
2393   if (passed) {
2394     frame_data_set_after_dissect(fdata, &cum_bytes, &prev_dis_ts);
2395     cap_file_add_fdata(cf, fdata);
2396   }
2397   else
2398     g_slice_free(frame_data, fdata);
2399
2400   if (do_dissection)
2401     epan_dissect_cleanup(&edt);
2402
2403   return passed;
2404 }
2405
2406 static gboolean
2407 process_packet_second_pass(capture_file *cf, frame_data *fdata,
2408                union wtap_pseudo_header *pseudo_header, const guchar *pd,
2409                gboolean filtering_tap_listeners, guint tap_flags)
2410 {
2411   gboolean create_proto_tree;
2412   column_info *cinfo;
2413   epan_dissect_t edt;
2414   gboolean passed;
2415
2416   /* If we're not running a display filter and we're not printing any
2417      packet information, we don't need to do a dissection. This means
2418      that all packets can be marked as 'passed'. */
2419   passed = TRUE;
2420
2421   /* If we're going to print packet information, or we're going to
2422      run a read filter, or we're going to process taps, set up to
2423      do a dissection and do so. */
2424   if (do_dissection) {
2425     if (gbl_resolv_flags)
2426       /* Grab any resolved addresses */
2427       host_name_lookup_process(NULL);
2428
2429     if (cf->rfcode || verbose || filtering_tap_listeners ||
2430         (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2431       create_proto_tree = TRUE;
2432     else
2433       create_proto_tree = FALSE;
2434
2435     /* The protocol tree will be "visible", i.e., printed, only if we're
2436        printing packet details, which is true if we're printing stuff
2437        ("print_packet_info" is true) and we're in verbose mode ("verbose"
2438        is true). */
2439     epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2440
2441     /* If we're running a read filter, prime the epan_dissect_t with that
2442        filter. */
2443     if (cf->rfcode)
2444       epan_dissect_prime_dfilter(&edt, cf->rfcode);
2445
2446     col_custom_prime_edt(&edt, &cf->cinfo);
2447
2448     tap_queue_init(&edt);
2449
2450     /* We only need the columns if either
2451
2452          1) some tap needs the columns
2453
2454        or
2455
2456          2) we're printing packet info but we're *not* verbose; in verbose
2457             mode, we print the protocol tree, not the protocol summary. */
2458     if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2459       cinfo = &cf->cinfo;
2460     else
2461       cinfo = NULL;
2462
2463     epan_dissect_run(&edt, pseudo_header, pd, fdata, cinfo);
2464
2465     tap_push_tapped_queue(&edt);
2466
2467     /* Run the read filter if we have one. */
2468     if (cf->rfcode)
2469       passed = dfilter_apply_edt(cf->rfcode, &edt);
2470   }
2471
2472   if (passed) {
2473     /* Process this packet. */
2474     if (print_packet_info) {
2475       /* We're printing packet information; print the information for
2476          this packet. */
2477       if (do_dissection)
2478         print_packet(cf, &edt);
2479       else
2480         print_packet(cf, NULL);
2481
2482       /* The ANSI C standard does not appear to *require* that a line-buffered
2483          stream be flushed to the host environment whenever a newline is
2484          written, it just says that, on such a stream, characters "are
2485          intended to be transmitted to or from the host environment as a
2486          block when a new-line character is encountered".
2487
2488          The Visual C++ 6.0 C implementation doesn't do what is intended;
2489          even if you set a stream to be line-buffered, it still doesn't
2490          flush the buffer at the end of every line.
2491
2492          So, if the "-l" flag was specified, we flush the standard output
2493          at the end of a packet.  This will do the right thing if we're
2494          printing packet summary lines, and, as we print the entire protocol
2495          tree for a single packet without waiting for anything to happen,
2496          it should be as good as line-buffered mode if we're printing
2497          protocol trees.  (The whole reason for the "-l" flag in either
2498          tcpdump or TShark is to allow the output of a live capture to
2499          be piped to a program or script and to have that script see the
2500          information for the packet as soon as it's printed, rather than
2501          having to wait until a standard I/O buffer fills up. */
2502       if (line_buffered)
2503         fflush(stdout);
2504
2505       if (ferror(stdout)) {
2506         show_print_file_io_error(errno);
2507         exit(2);
2508       }
2509     }
2510   }
2511
2512   if (do_dissection) {
2513     epan_dissect_cleanup(&edt);
2514   }
2515   return passed;
2516 }
2517 #endif
2518
2519 static int
2520 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2521     int max_packet_count, gint64 max_byte_count)
2522 {
2523   gint         linktype;
2524   int          snapshot_length;
2525   wtap_dumper *pdh;
2526   int          err;
2527   gchar        *err_info;
2528   gint64       data_offset;
2529   char         *save_file_string = NULL;
2530   gboolean     filtering_tap_listeners;
2531   guint        tap_flags;
2532
2533   linktype = wtap_file_encap(cf->wth);
2534   if (save_file != NULL) {
2535     /* Get a string that describes what we're writing to */
2536     save_file_string = output_file_description(save_file);
2537
2538     /* Set up to write to the capture file. */
2539     snapshot_length = wtap_snapshot_length(cf->wth);
2540     if (snapshot_length == 0) {
2541       /* Snapshot length of input file not known. */
2542       snapshot_length = WTAP_MAX_PACKET_SIZE;
2543     }
2544     pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2545                          FALSE /* compressed */, &err);
2546
2547     if (pdh == NULL) {
2548       /* We couldn't set up to write to the capture file. */
2549       switch (err) {
2550
2551       case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2552         cmdarg_err("Capture files can't be written in that format.");
2553         break;
2554
2555       case WTAP_ERR_UNSUPPORTED_ENCAP:
2556       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2557         cmdarg_err("The capture file being read can't be written in "
2558           "that format.");
2559         break;
2560
2561       case WTAP_ERR_CANT_OPEN:
2562         cmdarg_err("The %s couldn't be created for some "
2563           "unknown reason.", save_file_string);
2564         break;
2565
2566       case WTAP_ERR_SHORT_WRITE:
2567         cmdarg_err("A full header couldn't be written to the %s.",
2568                    save_file_string);
2569         break;
2570
2571       default:
2572         cmdarg_err("The %s could not be created: %s.", save_file_string,
2573                    wtap_strerror(err));
2574         break;
2575       }
2576       goto out;
2577     }
2578   } else {
2579     if (print_packet_info) {
2580       if (!write_preamble(cf)) {
2581         err = errno;
2582         show_print_file_io_error(err);
2583         goto out;
2584       }
2585     }
2586     pdh = NULL;
2587   }
2588
2589   /* Do we have any tap listeners with filters? */
2590   filtering_tap_listeners = have_filtering_tap_listeners();
2591
2592   /* Get the union of the flags for all tap listeners. */
2593   tap_flags = union_of_tap_listener_flags();
2594
2595   if (perform_two_pass_analysis) {
2596 #if GLIB_CHECK_VERSION(2,10,0)
2597     frame_data *fdata;
2598     int old_max_packet_count = max_packet_count;
2599
2600     while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2601       if (process_packet_first_pass(cf, data_offset, wtap_phdr(cf->wth),
2602                          wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2603         /* Stop reading if we have the maximum number of packets;
2604          * When the -c option has not been used, max_packet_count
2605          * starts at 0, which practically means, never stop reading.
2606          * (unless we roll over max_packet_count ?)
2607          */
2608         if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2609           err = 0; /* This is not an error */
2610           break;
2611         }
2612       }
2613     }
2614
2615     /* Close the sequential I/O side, to free up memory it requires. */
2616     wtap_sequential_close(cf->wth);
2617
2618     /* Allow the protocol dissectors to free up memory that they
2619      * don't need after the sequential run-through of the packets. */
2620     postseq_cleanup_all_protocols();
2621
2622     max_packet_count = old_max_packet_count;
2623
2624     for (fdata = cf->plist_start; err == 0 && fdata != NULL; fdata = fdata->next) {
2625       if (wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
2626           cf->pd, fdata->cap_len, &err, &err_info)) {
2627         if (process_packet_second_pass(cf, fdata,
2628                            &cf->pseudo_header, cf->pd,
2629                            filtering_tap_listeners, tap_flags)) {
2630           /* Either there's no read filtering or this packet passed the
2631              filter, so, if we're writing to a capture file, write
2632              this packet out. */
2633           if (pdh != NULL) {
2634             if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2635                            wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2636                            &err)) {
2637               /* Error writing to a capture file */
2638               show_capture_file_io_error(save_file, err, FALSE);
2639               wtap_dump_close(pdh, &err);
2640               exit(2);
2641             }
2642           }
2643           /* Stop reading if we have the maximum number of packets;
2644            * When the -c option has not been used, max_packet_count
2645            * starts at 0, which practically means, never stop reading.
2646            * (unless we roll over max_packet_count ?)
2647            */
2648           if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2649             err = 0; /* This is not an error */
2650             break;
2651           }
2652         }
2653       }
2654     }
2655 #endif
2656   }
2657   else {
2658     while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2659       if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2660                          wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2661                          filtering_tap_listeners, tap_flags)) {
2662         /* Either there's no read filtering or this packet passed the
2663            filter, so, if we're writing to a capture file, write
2664            this packet out. */
2665         if (pdh != NULL) {
2666           if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2667                          wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2668                          &err)) {
2669             /* Error writing to a capture file */
2670             show_capture_file_io_error(save_file, err, FALSE);
2671             wtap_dump_close(pdh, &err);
2672             exit(2);
2673           }
2674         }
2675         /* Stop reading if we have the maximum number of packets;
2676          * When the -c option has not been used, max_packet_count
2677          * starts at 0, which practically means, never stop reading.
2678          * (unless we roll over max_packet_count ?)
2679          */
2680         if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2681           err = 0; /* This is not an error */
2682           break;
2683         }
2684       }
2685     }
2686   }
2687
2688   if (err != 0) {
2689     /*
2690      * Print a message noting that the read failed somewhere along the line.
2691      *
2692      * If we're printing packet data, and the standard output and error are
2693      * going to the same place, flush the standard output, so everything
2694      * buffered up is written, and then print a newline to the standard error
2695      * before printing the error message, to separate it from the packet
2696      * data.  (Alas, that only works on UN*X; st_dev is meaningless, and
2697      * the _fstat() documentation at Microsoft doesn't indicate whether
2698      * st_ino is even supported.)
2699      */
2700 #ifndef _WIN32
2701     if (print_packet_info) {
2702       struct stat stat_stdout, stat_stderr;
2703
2704       if (fstat(1, &stat_stdout) == 0 && fstat(2, &stat_stderr) == 0) {
2705         if (stat_stdout.st_dev == stat_stderr.st_dev &&
2706             stat_stdout.st_ino == stat_stderr.st_ino) {
2707           fflush(stdout);
2708           fprintf(stderr, "\n");
2709         }
2710       }
2711     }
2712 #endif
2713     switch (err) {
2714
2715     case WTAP_ERR_UNSUPPORTED_ENCAP:
2716       cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2717                  cf->filename, err_info);
2718       g_free(err_info);
2719       break;
2720
2721     case WTAP_ERR_CANT_READ:
2722       cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2723                  cf->filename);
2724       break;
2725
2726     case WTAP_ERR_SHORT_READ:
2727       cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2728                  cf->filename);
2729       break;
2730
2731     case WTAP_ERR_BAD_RECORD:
2732       cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2733                  cf->filename, err_info);
2734       g_free(err_info);
2735       break;
2736
2737     default:
2738       cmdarg_err("An error occurred while reading \"%s\": %s.",
2739                  cf->filename, wtap_strerror(err));
2740       break;
2741     }
2742     if (save_file != NULL) {
2743       /* Now close the capture file. */
2744       if (!wtap_dump_close(pdh, &err))
2745         show_capture_file_io_error(save_file, err, TRUE);
2746     }
2747   } else {
2748     if (save_file != NULL) {
2749       /* Now close the capture file. */
2750       if (!wtap_dump_close(pdh, &err))
2751         show_capture_file_io_error(save_file, err, TRUE);
2752     } else {
2753       if (print_packet_info) {
2754         if (!write_finale()) {
2755           err = errno;
2756           show_print_file_io_error(err);
2757         }
2758       }
2759     }
2760   }
2761
2762 out:
2763   wtap_close(cf->wth);
2764   cf->wth = NULL;
2765
2766   g_free(save_file_string);
2767
2768   return err;
2769 }
2770
2771 static gboolean
2772 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2773                union wtap_pseudo_header *pseudo_header, const guchar *pd,
2774                gboolean filtering_tap_listeners, guint tap_flags)
2775 {
2776   frame_data fdata;
2777   gboolean create_proto_tree;
2778   column_info *cinfo;
2779   epan_dissect_t edt;
2780   gboolean passed;
2781
2782   /* Count this packet. */
2783   cf->count++;
2784
2785   /* If we're not running a display filter and we're not printing any
2786      packet information, we don't need to do a dissection. This means
2787      that all packets can be marked as 'passed'. */
2788   passed = TRUE;
2789
2790   frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
2791
2792   /* If we're going to print packet information, or we're going to
2793      run a read filter, or we're going to process taps, set up to
2794      do a dissection and do so. */
2795   if (do_dissection) {
2796     if (print_packet_info && gbl_resolv_flags)
2797       /* Grab any resolved addresses */
2798       host_name_lookup_process(NULL);
2799
2800     if (cf->rfcode || verbose || filtering_tap_listeners ||
2801         (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2802       create_proto_tree = TRUE;
2803     else
2804       create_proto_tree = FALSE;
2805
2806     /* The protocol tree will be "visible", i.e., printed, only if we're
2807        printing packet details, which is true if we're printing stuff
2808        ("print_packet_info" is true) and we're in verbose mode ("verbose"
2809        is true). */
2810     epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2811
2812     /* If we're running a read filter, prime the epan_dissect_t with that
2813        filter. */
2814     if (cf->rfcode)
2815       epan_dissect_prime_dfilter(&edt, cf->rfcode);
2816
2817     col_custom_prime_edt(&edt, &cf->cinfo);
2818
2819     tap_queue_init(&edt);
2820
2821     /* We only need the columns if either
2822
2823          1) some tap needs the columns
2824
2825        or
2826
2827          2) we're printing packet info but we're *not* verbose; in verbose
2828             mode, we print the protocol tree, not the protocol summary. */
2829     if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2830       cinfo = &cf->cinfo;
2831     else
2832       cinfo = NULL;
2833
2834     frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
2835                                   &first_ts, &prev_dis_ts, &prev_cap_ts);
2836
2837     epan_dissect_run(&edt, pseudo_header, pd, &fdata, cinfo);
2838
2839     tap_push_tapped_queue(&edt);
2840
2841     /* Run the read filter if we have one. */
2842     if (cf->rfcode)
2843       passed = dfilter_apply_edt(cf->rfcode, &edt);
2844   }
2845
2846   if (passed) {
2847     frame_data_set_after_dissect(&fdata, &cum_bytes, &prev_dis_ts);
2848
2849     /* Process this packet. */
2850     if (print_packet_info) {
2851       /* We're printing packet information; print the information for
2852          this packet. */
2853       if (do_dissection)
2854         print_packet(cf, &edt);
2855       else
2856         print_packet(cf, NULL);
2857
2858       /* The ANSI C standard does not appear to *require* that a line-buffered
2859          stream be flushed to the host environment whenever a newline is
2860          written, it just says that, on such a stream, characters "are
2861          intended to be transmitted to or from the host environment as a
2862          block when a new-line character is encountered".
2863
2864          The Visual C++ 6.0 C implementation doesn't do what is intended;
2865          even if you set a stream to be line-buffered, it still doesn't
2866          flush the buffer at the end of every line.
2867
2868          So, if the "-l" flag was specified, we flush the standard output
2869          at the end of a packet.  This will do the right thing if we're
2870          printing packet summary lines, and, as we print the entire protocol
2871          tree for a single packet without waiting for anything to happen,
2872          it should be as good as line-buffered mode if we're printing
2873          protocol trees.  (The whole reason for the "-l" flag in either
2874          tcpdump or TShark is to allow the output of a live capture to
2875          be piped to a program or script and to have that script see the
2876          information for the packet as soon as it's printed, rather than
2877          having to wait until a standard I/O buffer fills up. */
2878       if (line_buffered)
2879         fflush(stdout);
2880
2881       if (ferror(stdout)) {
2882         show_print_file_io_error(errno);
2883         exit(2);
2884       }
2885     }
2886   }
2887
2888   if (do_dissection) {
2889     epan_dissect_cleanup(&edt);
2890     frame_data_cleanup(&fdata);
2891   }
2892   return passed;
2893 }
2894
2895 static gboolean
2896 write_preamble(capture_file *cf)
2897 {
2898   switch (output_action) {
2899
2900   case WRITE_TEXT:
2901     return print_preamble(print_stream, cf ? cf->filename : NULL);
2902
2903   case WRITE_XML:
2904     if (verbose)
2905       write_pdml_preamble(stdout);
2906     else
2907       write_psml_preamble(stdout);
2908     return !ferror(stdout);
2909
2910   case WRITE_FIELDS:
2911     write_fields_preamble(output_fields, stdout);
2912     return !ferror(stdout);
2913
2914   default:
2915     g_assert_not_reached();
2916     return FALSE;
2917   }
2918 }
2919
2920 static char *
2921 get_line_buf(size_t len)
2922 {
2923   static char *line_bufp = NULL;
2924   static size_t line_buf_len = 256;
2925   size_t new_line_buf_len;
2926
2927   for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2928        new_line_buf_len *= 2)
2929     ;
2930   if (line_bufp == NULL) {
2931     line_buf_len = new_line_buf_len;
2932     line_bufp = g_malloc(line_buf_len + 1);
2933   } else {
2934     if (new_line_buf_len > line_buf_len) {
2935       line_buf_len = new_line_buf_len;
2936       line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2937     }
2938   }
2939   return line_bufp;
2940 }
2941
2942 static gboolean
2943 print_columns(capture_file *cf)
2944 {
2945   char *line_bufp;
2946   int i;
2947   size_t buf_offset;
2948   size_t column_len;
2949
2950   line_bufp = get_line_buf(256);
2951   buf_offset = 0;
2952   *line_bufp = '\0';
2953   for (i = 0; i < cf->cinfo.num_cols; i++) {
2954     switch (cf->cinfo.col_fmt[i]) {
2955     case COL_NUMBER:
2956 #ifdef HAVE_LIBPCAP
2957       /*
2958        * Don't print this if we're doing a live capture from a network
2959        * interface - if we're doing a live capture, you won't be
2960        * able to look at the capture in the future (it's not being
2961        * saved anywhere), so the frame numbers are unlikely to be
2962        * useful.
2963        *
2964        * (XXX - it might be nice to be able to save and print at
2965        * the same time, sort of like an "Update list of packets
2966        * in real time" capture in Wireshark.)
2967        */
2968       if (global_capture_opts.iface != NULL)
2969         continue;
2970 #endif
2971       column_len = strlen(cf->cinfo.col_data[i]);
2972       if (column_len < 3)
2973         column_len = 3;
2974       line_bufp = get_line_buf(buf_offset + column_len);
2975       sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2976       break;
2977
2978     case COL_CLS_TIME:
2979     case COL_REL_TIME:
2980     case COL_ABS_TIME:
2981     case COL_ABS_DATE_TIME: /* XXX - wider */
2982       column_len = strlen(cf->cinfo.col_data[i]);
2983       if (column_len < 10)
2984         column_len = 10;
2985       line_bufp = get_line_buf(buf_offset + column_len);
2986       sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2987       break;
2988
2989     case COL_DEF_SRC:
2990     case COL_RES_SRC:
2991     case COL_UNRES_SRC:
2992     case COL_DEF_DL_SRC:
2993     case COL_RES_DL_SRC:
2994     case COL_UNRES_DL_SRC:
2995     case COL_DEF_NET_SRC:
2996     case COL_RES_NET_SRC:
2997     case COL_UNRES_NET_SRC:
2998       column_len = strlen(cf->cinfo.col_data[i]);
2999       if (column_len < 12)
3000         column_len = 12;
3001       line_bufp = get_line_buf(buf_offset + column_len);
3002       sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
3003       break;
3004
3005     case COL_DEF_DST:
3006     case COL_RES_DST:
3007     case COL_UNRES_DST:
3008     case COL_DEF_DL_DST:
3009     case COL_RES_DL_DST:
3010     case COL_UNRES_DL_DST:
3011     case COL_DEF_NET_DST:
3012     case COL_RES_NET_DST:
3013     case COL_UNRES_NET_DST:
3014       column_len = strlen(cf->cinfo.col_data[i]);
3015       if (column_len < 12)
3016         column_len = 12;
3017       line_bufp = get_line_buf(buf_offset + column_len);
3018       sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
3019       break;
3020
3021     default:
3022       column_len = strlen(cf->cinfo.col_data[i]);
3023       line_bufp = get_line_buf(buf_offset + column_len);
3024       strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
3025       break;
3026     }
3027     buf_offset += column_len;
3028     if (i != cf->cinfo.num_cols - 1) {
3029       /*
3030        * This isn't the last column, so we need to print a
3031        * separator between this column and the next.
3032        *
3033        * If we printed a network source and are printing a
3034        * network destination of the same type next, separate
3035        * them with "->"; if we printed a network destination
3036        * and are printing a network source of the same type
3037        * next, separate them with "<-"; otherwise separate them
3038        * with a space.
3039        *
3040        * We add enough space to the buffer for " <- " or " -> ",
3041        * even if we're only adding " ".
3042        */
3043       line_bufp = get_line_buf(buf_offset + 4);
3044       switch (cf->cinfo.col_fmt[i]) {
3045
3046       case COL_DEF_SRC:
3047       case COL_RES_SRC:
3048       case COL_UNRES_SRC:
3049         switch (cf->cinfo.col_fmt[i + 1]) {
3050
3051         case COL_DEF_DST:
3052         case COL_RES_DST:
3053         case COL_UNRES_DST:
3054           strcat(line_bufp + buf_offset, " -> ");
3055           buf_offset += 4;
3056           break;
3057
3058         default:
3059           strcat(line_bufp + buf_offset, " ");
3060           buf_offset += 1;
3061           break;
3062         }
3063         break;
3064
3065       case COL_DEF_DL_SRC:
3066       case COL_RES_DL_SRC:
3067       case COL_UNRES_DL_SRC:
3068         switch (cf->cinfo.col_fmt[i + 1]) {
3069
3070         case COL_DEF_DL_DST:
3071         case COL_RES_DL_DST:
3072         case COL_UNRES_DL_DST:
3073           strcat(line_bufp + buf_offset, " -> ");
3074           buf_offset += 4;
3075           break;
3076
3077         default:
3078           strcat(line_bufp + buf_offset, " ");
3079           buf_offset += 1;
3080           break;
3081         }
3082         break;
3083
3084       case COL_DEF_NET_SRC:
3085       case COL_RES_NET_SRC:
3086       case COL_UNRES_NET_SRC:
3087         switch (cf->cinfo.col_fmt[i + 1]) {
3088
3089         case COL_DEF_NET_DST:
3090         case COL_RES_NET_DST:
3091         case COL_UNRES_NET_DST:
3092           strcat(line_bufp + buf_offset, " -> ");
3093           buf_offset += 4;
3094           break;
3095
3096         default:
3097           strcat(line_bufp + buf_offset, " ");
3098           buf_offset += 1;
3099           break;
3100         }
3101         break;
3102
3103       case COL_DEF_DST:
3104       case COL_RES_DST:
3105       case COL_UNRES_DST:
3106         switch (cf->cinfo.col_fmt[i + 1]) {
3107
3108         case COL_DEF_SRC:
3109         case COL_RES_SRC:
3110         case COL_UNRES_SRC:
3111           strcat(line_bufp + buf_offset, " <- ");
3112           buf_offset += 4;
3113           break;
3114
3115         default:
3116           strcat(line_bufp + buf_offset, " ");
3117           buf_offset += 1;
3118           break;
3119         }
3120         break;
3121
3122       case COL_DEF_DL_DST:
3123       case COL_RES_DL_DST:
3124       case COL_UNRES_DL_DST:
3125         switch (cf->cinfo.col_fmt[i + 1]) {
3126
3127         case COL_DEF_DL_SRC:
3128         case COL_RES_DL_SRC:
3129         case COL_UNRES_DL_SRC:
3130           strcat(line_bufp + buf_offset, " <- ");
3131           buf_offset += 4;
3132           break;
3133
3134         default:
3135           strcat(line_bufp + buf_offset, " ");
3136           buf_offset += 1;
3137           break;
3138         }
3139         break;
3140
3141       case COL_DEF_NET_DST:
3142       case COL_RES_NET_DST:
3143       case COL_UNRES_NET_DST:
3144         switch (cf->cinfo.col_fmt[i + 1]) {
3145
3146         case COL_DEF_NET_SRC:
3147         case COL_RES_NET_SRC:
3148         case COL_UNRES_NET_SRC:
3149           strcat(line_bufp + buf_offset, " <- ");
3150           buf_offset += 4;
3151           break;
3152
3153         default:
3154           strcat(line_bufp + buf_offset, " ");
3155           buf_offset += 1;
3156           break;
3157         }
3158         break;
3159
3160       default:
3161         strcat(line_bufp + buf_offset, " ");
3162         buf_offset += 1;
3163         break;
3164       }
3165     }
3166   }
3167   return print_line(print_stream, 0, line_bufp);
3168 }
3169
3170 static gboolean
3171 print_packet(capture_file *cf, epan_dissect_t *edt)
3172 {
3173   print_args_t  print_args;
3174
3175   if (verbose) {
3176     /* Print the information in the protocol tree. */
3177     switch (output_action) {
3178
3179     case WRITE_TEXT:
3180       print_args.to_file = TRUE;
3181       print_args.format = print_format;
3182       print_args.print_summary = !verbose;
3183       print_args.print_hex = verbose && print_hex;
3184       print_args.print_formfeed = FALSE;
3185       print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
3186
3187       /* init the packet range */
3188       packet_range_init(&print_args.range);
3189
3190       if (!proto_tree_print(&print_args, edt, print_stream))
3191         return FALSE;
3192       if (!print_hex) {
3193         /* "print_hex_data()" will put out a leading blank line, as well
3194          as a trailing one; print one here, to separate the packets,
3195          only if "print_hex_data()" won't be called. */
3196         if (!print_line(print_stream, 0, ""))
3197           return FALSE;
3198       }
3199       break;
3200
3201     case WRITE_XML:
3202       proto_tree_write_pdml(edt, stdout);
3203       printf("\n");
3204       return !ferror(stdout);
3205     case WRITE_FIELDS:
3206       proto_tree_write_fields(output_fields, edt, stdout);
3207       printf("\n");
3208       return !ferror(stdout);
3209     }
3210   } else {
3211     /* Just fill in the columns. */
3212     epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3213
3214     /* Now print them. */
3215     switch (output_action) {
3216
3217     case WRITE_TEXT:
3218         if (!print_columns(cf))
3219           return FALSE;
3220         break;
3221
3222     case WRITE_XML:
3223         proto_tree_write_psml(edt, stdout);
3224         return !ferror(stdout);
3225     case WRITE_FIELDS: /*No non-verbose "fields" format */
3226         g_assert_not_reached();
3227         break;
3228     }
3229   }
3230   if (print_hex) {
3231     if (!print_hex_data(print_stream, edt))
3232       return FALSE;
3233     if (!print_line(print_stream, 0, ""))
3234       return FALSE;
3235   }
3236   return TRUE;
3237 }
3238
3239 static gboolean
3240 write_finale(void)
3241 {
3242   switch (output_action) {
3243
3244   case WRITE_TEXT:
3245     return print_finale(print_stream);
3246
3247   case WRITE_XML:
3248     if (verbose)
3249       write_pdml_finale(stdout);
3250     else
3251       write_psml_finale(stdout);
3252     return !ferror(stdout);
3253
3254   case WRITE_FIELDS:
3255     write_fields_finale(output_fields, stdout);
3256     return !ferror(stdout);
3257
3258   default:
3259     g_assert_not_reached();
3260     return FALSE;
3261   }
3262 }
3263
3264 cf_status_t
3265 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3266 {
3267   wtap       *wth;
3268   gchar       *err_info;
3269   char        err_msg[2048+1];
3270
3271   wth = wtap_open_offline(fname, err, &err_info, perform_two_pass_analysis);
3272   if (wth == NULL)
3273     goto fail;
3274
3275   /* The open succeeded.  Fill in the information for this file. */
3276
3277   /* Cleanup all data structures used for dissection. */
3278   cleanup_dissection();
3279   /* Initialize all data structures used for dissection. */
3280   init_dissection();
3281
3282   cf->wth = wth;
3283   cf->f_datalen = 0; /* not used, but set it anyway */
3284
3285   /* Set the file name because we need it to set the follow stream filter.
3286      XXX - is that still true?  We need it for other reasons, though,
3287      in any case. */
3288   cf->filename = g_strdup(fname);
3289
3290   /* Indicate whether it's a permanent or temporary file. */
3291   cf->is_tempfile = is_tempfile;
3292
3293   /* If it's a temporary capture buffer file, mark it as not saved. */
3294   cf->user_saved = !is_tempfile;
3295
3296   cf->cd_t      = wtap_file_type(cf->wth);
3297   cf->count     = 0;
3298   cf->drops_known = FALSE;
3299   cf->drops     = 0;
3300   cf->snap      = wtap_snapshot_length(cf->wth);
3301   if (cf->snap == 0) {
3302     /* Snapshot length not known. */
3303     cf->has_snap = FALSE;
3304     cf->snap = WTAP_MAX_PACKET_SIZE;
3305   } else
3306     cf->has_snap = TRUE;
3307   nstime_set_zero(&cf->elapsed_time);
3308   nstime_set_unset(&first_ts);
3309   nstime_set_unset(&prev_dis_ts);
3310   nstime_set_unset(&prev_cap_ts);
3311
3312   cf->state = FILE_READ_IN_PROGRESS;
3313
3314   return CF_OK;
3315
3316 fail:
3317   g_snprintf(err_msg, sizeof err_msg,
3318              cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3319   cmdarg_err("%s", err_msg);
3320   return CF_ERROR;
3321 }
3322
3323 static void
3324 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3325 {
3326   char *save_file_string;
3327
3328   save_file_string = output_file_description(fname);
3329
3330   switch (err) {
3331
3332   case ENOSPC:
3333     cmdarg_err("Not all the packets could be written to the %s because there is "
3334                "no space left on the file system.",
3335                save_file_string);
3336     break;
3337
3338 #ifdef EDQUOT
3339   case EDQUOT:
3340     cmdarg_err("Not all the packets could be written to the %s because you are "
3341                "too close to, or over your disk quota.",
3342                save_file_string);
3343   break;
3344 #endif
3345
3346   case WTAP_ERR_CANT_CLOSE:
3347     cmdarg_err("The %s couldn't be closed for some unknown reason.",
3348                save_file_string);
3349     break;
3350
3351   case WTAP_ERR_SHORT_WRITE:
3352     cmdarg_err("Not all the packets could be written to the %s.",
3353                save_file_string);
3354     break;
3355
3356   default:
3357     if (is_close) {
3358       cmdarg_err("The %s could not be closed: %s.", save_file_string,
3359                  wtap_strerror(err));
3360     } else {
3361       cmdarg_err("An error occurred while writing to the %s: %s.",
3362                  save_file_string, wtap_strerror(err));
3363     }
3364     break;
3365   }
3366   g_free(save_file_string);
3367 }
3368
3369 static void
3370 show_print_file_io_error(int err)
3371 {
3372   switch (err) {
3373
3374   case ENOSPC:
3375     cmdarg_err("Not all the packets could be printed because there is "
3376 "no space left on the file system.");
3377     break;
3378
3379 #ifdef EDQUOT
3380   case EDQUOT:
3381     cmdarg_err("Not all the packets could be printed because you are "
3382 "too close to, or over your disk quota.");
3383   break;
3384 #endif
3385
3386   default:
3387     cmdarg_err("An error occurred while printing packets: %s.",
3388       strerror(err));
3389     break;
3390   }
3391 }
3392
3393 static const char *
3394 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3395                       int file_type)
3396 {
3397   const char *errmsg;
3398   static char errmsg_errno[1024+1];
3399
3400   if (err < 0) {
3401     /* Wiretap error. */
3402     switch (err) {
3403
3404     case WTAP_ERR_NOT_REGULAR_FILE:
3405       errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3406       break;
3407
3408     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3409       /* Seen only when opening a capture file for reading. */
3410       errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
3411       break;
3412
3413     case WTAP_ERR_UNSUPPORTED:
3414       /* Seen only when opening a capture file for reading. */
3415       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3416                "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
3417                "(%s)", err_info);
3418       g_free(err_info);
3419       errmsg = errmsg_errno;
3420       break;
3421
3422     case WTAP_ERR_CANT_WRITE_TO_PIPE:
3423       /* Seen only when opening a capture file for writing. */
3424       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3425                  "The file \"%%s\" is a pipe, and %s capture files can't be "
3426                  "written to a pipe.", wtap_file_type_string(file_type));
3427       errmsg = errmsg_errno;
3428       break;
3429
3430     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3431       /* Seen only when opening a capture file for writing. */
3432       errmsg = "TShark doesn't support writing capture files in that format.";
3433       break;
3434
3435     case WTAP_ERR_UNSUPPORTED_ENCAP:
3436       if (for_writing)
3437         errmsg = "TShark can't save this capture in that format.";
3438       else {
3439         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3440                  "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3441                  "(%s)", err_info);
3442         g_free(err_info);
3443         errmsg = errmsg_errno;
3444       }
3445       break;
3446
3447     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3448       if (for_writing)
3449         errmsg = "TShark can't save this capture in that format.";
3450       else
3451         errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3452       break;
3453
3454     case WTAP_ERR_BAD_RECORD:
3455       /* Seen only when opening a capture file for reading. */
3456       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3457                "The file \"%%s\" appears to be damaged or corrupt.\n"
3458                "(%s)", err_info);
3459       g_free(err_info);
3460       errmsg = errmsg_errno;
3461       break;
3462
3463     case WTAP_ERR_CANT_OPEN:
3464       if (for_writing)
3465         errmsg = "The file \"%s\" could not be created for some unknown reason.";
3466       else
3467         errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3468       break;
3469
3470     case WTAP_ERR_SHORT_READ:
3471       errmsg = "The file \"%s\" appears to have been cut short"
3472                " in the middle of a packet or other data.";
3473       break;
3474
3475     case WTAP_ERR_SHORT_WRITE:
3476       errmsg = "A full header couldn't be written to the file \"%s\".";
3477       break;
3478
3479     default:
3480       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3481                  "The file \"%%s\" could not be %s: %s.",
3482                  for_writing ? "created" : "opened",
3483                  wtap_strerror(err));
3484       errmsg = errmsg_errno;
3485       break;
3486     }
3487   } else
3488     errmsg = file_open_error_message(err, for_writing);
3489   return errmsg;
3490 }
3491
3492 /*
3493  * Open/create errors are reported with an console message in TShark.
3494  */
3495 static void
3496 open_failure_message(const char *filename, int err, gboolean for_writing)
3497 {
3498   fprintf(stderr, "tshark: ");
3499   fprintf(stderr, file_open_error_message(err, for_writing), filename);
3500   fprintf(stderr, "\n");
3501 }
3502
3503
3504 /*
3505  * General errors are reported with an console message in TShark.
3506  */
3507 static void
3508 failure_message(const char *msg_format, va_list ap)
3509 {
3510   fprintf(stderr, "tshark: ");
3511   vfprintf(stderr, msg_format, ap);
3512   fprintf(stderr, "\n");
3513 }
3514
3515 /*
3516  * Read errors are reported with an console message in TShark.
3517  */
3518 static void
3519 read_failure_message(const char *filename, int err)
3520 {
3521   cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3522           filename, strerror(err));
3523 }
3524
3525 /*
3526  * Write errors are reported with an console message in TShark.
3527  */
3528 static void
3529 write_failure_message(const char *filename, int err)
3530 {
3531   cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3532           filename, strerror(err));
3533 }
3534
3535 /*
3536  * Print to the standard error.  This is a command-line tool, so there's
3537  * no need to pop up a console.
3538  */
3539 void
3540 vfprintf_stderr(const char *fmt, va_list ap)
3541 {
3542   vfprintf(stderr, fmt, ap);
3543 }
3544
3545 void
3546 fprintf_stderr(const char *fmt, ...)
3547 {
3548   va_list ap;
3549
3550   va_start(ap, fmt);
3551   vfprintf_stderr(fmt, ap);
3552   va_end(ap);
3553 }
3554
3555 /*
3556  * Report an error in command-line arguments.
3557  */
3558 void
3559 cmdarg_err(const char *fmt, ...)
3560 {
3561   va_list ap;
3562
3563   va_start(ap, fmt);
3564   failure_message(fmt, ap);
3565   va_end(ap);
3566 }
3567
3568 /*
3569  * Report additional information for an error in command-line arguments.
3570  */
3571 void
3572 cmdarg_err_cont(const char *fmt, ...)
3573 {
3574   va_list ap;
3575
3576   va_start(ap, fmt);
3577   vfprintf(stderr, fmt, ap);
3578   fprintf(stderr, "\n");
3579   va_end(ap);
3580 }