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