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