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>.
8 * Wireshark - Network traffic analyzer
9 * By Gerald Combs <gerald@wireshark.org>
10 * Copyright 1998 Gerald Combs
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.
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.
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.
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
54 #ifdef NEED_STRERROR_H
55 #include "wsutil/strerror.h"
61 #include "wsutil/wsgetopt.h"
65 #include <epan/epan.h>
66 #include <epan/filesystem.h>
67 #include <wsutil/privileges.h>
68 #include <wsutil/file_util.h>
71 #include <epan/timestamp.h>
72 #include <epan/packet.h>
74 #include "disabled_protos.h"
75 #include <epan/prefs.h>
76 #include <epan/column.h>
78 #include <epan/addr_resolv.h>
80 #include "clopts_common.h"
81 #include "console_io.h"
82 #include "cmdarg_err.h"
83 #include "version_info.h"
84 #include <epan/plugins.h>
86 #include <epan/epan_dissect.h>
88 #include <epan/stat_cmd_args.h>
89 #include <epan/timestamp.h>
90 #include <epan/ex-opt.h>
93 #include "capture_ui_utils.h"
94 #include "capture_ifinfo.h"
95 #include "capture-pcap-util.h"
97 #include "capture-wpcap.h"
98 #include "capture_errs.h"
101 #include "capture_sync.h"
102 #endif /* HAVE_LIBPCAP */
104 #include <epan/funnel.h>
108 * This is the template for the decode as option; it is shared between the
109 * various functions that output the usage for this parameter.
111 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
113 static guint32 cum_bytes;
114 static nstime_t first_ts;
115 static nstime_t prev_dis_ts;
116 static nstime_t prev_cap_ts;
118 static gboolean print_packet_info; /* TRUE if we're to print packet information */
120 static gboolean perform_two_pass_analysis;
123 * The way the packet decode is to be written.
126 WRITE_TEXT, /* summary or detail text */
127 WRITE_XML, /* PDML or PSML */
128 WRITE_FIELDS /* User defined list of fields */
129 /* Add CSV and the like here */
132 static output_action_e output_action;
133 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
134 static gboolean verbose;
135 static gboolean print_hex;
136 static gboolean line_buffered;
138 static print_format_e print_format = PR_FMT_TEXT;
139 static print_stream_t *print_stream;
141 static output_fields_t* output_fields = NULL;
145 * TRUE if we're to print packet counts to keep track of captured packets.
147 static gboolean print_packet_counts;
150 static capture_options global_capture_opts;
153 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
154 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
157 static gboolean capture(void);
158 static void report_counts(void);
160 static BOOL WINAPI capture_cleanup(DWORD);
162 static void capture_cleanup(int);
164 static void report_counts_siginfo(int);
167 #endif /* HAVE_LIBPCAP */
169 static int load_cap_file(capture_file *, char *, int, int, gint64);
170 static gboolean process_packet(capture_file *cf, gint64 offset,
171 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
172 const guchar *pd, gboolean filtering_tap_listeners, guint tap_flags);
173 static void show_capture_file_io_error(const char *, int, gboolean);
174 static void show_print_file_io_error(int err);
175 static gboolean write_preamble(capture_file *cf);
176 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
177 static gboolean write_finale(void);
178 static const char *cf_open_error_message(int err, gchar *err_info,
179 gboolean for_writing, int file_type);
181 static void open_failure_message(const char *filename, int err,
182 gboolean for_writing);
183 static void failure_message(const char *msg_format, va_list ap);
184 static void read_failure_message(const char *filename, int err);
185 static void write_failure_message(const char *filename, int err);
189 static void list_capture_types(void) {
192 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
193 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
194 if (wtap_dump_can_open(i))
195 fprintf(stderr, " %s - %s\n",
196 wtap_file_type_short_string(i), wtap_file_type_string(i));
201 print_usage(gboolean print_ver)
208 "TShark " VERSION "%s\n"
209 "Dump and analyze network traffic.\n"
210 "See http://www.wireshark.org for more information.\n"
213 wireshark_svnversion, get_copyright_info());
217 fprintf(output, "\n");
218 fprintf(output, "Usage: tshark [options] ...\n");
219 fprintf(output, "\n");
222 fprintf(output, "Capture interface:\n");
223 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
224 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
225 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
226 fprintf(output, " -p don't capture in promiscuous mode\n");
227 #ifdef HAVE_PCAP_CREATE
228 fprintf(output, " -I capture in monitor mode, if available\n");
230 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
231 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
233 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
234 fprintf(output, " -D print list of interfaces and exit\n");
235 fprintf(output, " -L print list of link-layer types of iface and exit\n");
236 fprintf(output, "\n");
237 fprintf(output, "Capture stop conditions:\n");
238 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
239 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
240 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
241 fprintf(output, " files:NUM - stop after NUM files\n");
242 /*fprintf(output, "\n");*/
243 fprintf(output, "Capture output:\n");
244 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
245 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
246 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
247 #endif /* HAVE_LIBPCAP */
249 /*fprintf(output, "\n");*/
250 fprintf(output, "Input file:\n");
251 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
253 fprintf(output, "\n");
254 fprintf(output, "Processing:\n");
255 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
256 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
257 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
258 fprintf(output, " -d %s ...\n", decode_as_arg_template);
259 fprintf(output, " \"Decode As\", see the man page for details\n");
260 fprintf(output, " Example: tcp.port==8888,http\n");
262 /*fprintf(output, "\n");*/
263 fprintf(output, "Output:\n");
264 fprintf(output, " -w <outfile|-> write packets to a pcap-format file named \"outfile\"\n");
265 fprintf(output, " (or to the standard output for \"-\")\n");
266 fprintf(output, " -C <config profile> start with specified configuration profile\n");
267 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
268 fprintf(output, " an empty \"-F\" option will list the file types\n");
269 fprintf(output, " -V add output of packet tree (Packet Details)\n");
270 fprintf(output, " -S display packets even when writing to a file\n");
271 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
272 fprintf(output, " -T pdml|ps|psml|text|fields\n");
273 fprintf(output, " format of text output (def: text)\n");
274 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
275 fprintf(output, " this option can be repeated to print multiple fields\n");
276 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
277 fprintf(output, " header=y|n switch headers on and off\n");
278 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
279 fprintf(output, " occurrence=f|l|a print first, last or all occurrences of each field\n");
280 fprintf(output, " aggregator=,|/s|<char> select comma, space, printable character as aggregator\n");
281 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
282 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
283 fprintf(output, " -u s|hms output format of seconds (def: s: seconds)\n");
284 fprintf(output, " -l flush standard output after each packet\n");
285 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
286 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
287 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
289 fprintf(output, "\n");
290 fprintf(output, "Miscellaneous:\n");
291 fprintf(output, " -h display this help and exit\n");
292 fprintf(output, " -v display version info and exit\n");
293 fprintf(output, " -o <name>:<value> ... override preference setting\n");
294 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
295 fprintf(output, " -G [report] dump one of several available reports and exit\n");
296 fprintf(output, " default report=\"fields\"\n");
297 fprintf(output, " use \"-G ?\" for more help\n");
301 glossary_option_help(void)
307 fprintf(output, "TShark " VERSION "%s\n", wireshark_svnversion);
309 fprintf(output, "\n");
310 fprintf(output, "Usage: tshark -G [report]\n");
311 fprintf(output, "\n");
312 fprintf(output, "Glossary table reports:\n");
313 fprintf(output, " -G [fields] dump glossary in original format and exit\n");
314 fprintf(output, " -G fields2 dump glossary in format 2 and exit\n");
315 fprintf(output, " -G fields3 dump glossary in format 3 and exit\n");
316 fprintf(output, " -G protocols dump protocols in registration database and exit\n");
317 fprintf(output, " -G values dump value, range, true/false strings and exit\n");
318 fprintf(output, " -G decodes dump \"layer type\"/\"decode as\" associations and exit\n");
319 fprintf(output, "\n");
320 fprintf(output, "Preference reports:\n");
321 fprintf(output, " -G defaultprefs dump default preferences and exit\n");
322 fprintf(output, " -G currentprefs dump current preferences and exit\n");
323 fprintf(output, "\n");
328 * For a dissector table, print on the stream described by output,
329 * its short name (which is what's used in the "-d" option) and its
333 display_dissector_table_names(const char *table_name, const char *ui_name,
336 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
340 * For a dissector handle, print on the stream described by output,
341 * the filter name (which is what's used in the "-d" option) and the full
342 * name for the protocol that corresponds to this handle.
345 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
348 const gchar* proto_filter_name;
349 const gchar* proto_ui_name;
351 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
353 if (proto_id != -1) {
354 proto_filter_name = proto_get_protocol_filter_name(proto_id);
355 proto_ui_name = proto_get_protocol_name(proto_id);
356 g_assert(proto_filter_name != NULL);
357 g_assert(proto_ui_name != NULL);
359 fprintf((FILE *)output, "\t%s (%s)\n",
366 * The protocol_name_search structure is used by find_protocol_name_func()
367 * to pass parameters and store results
369 struct protocol_name_search{
370 gchar *searched_name; /* Protocol filter name we are looking for */
371 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
372 guint nb_match; /* How many dissectors matched searched_name */
374 typedef struct protocol_name_search *protocol_name_search_t;
377 * This function parses all dissectors associated with a table to find the
378 * one whose protocol has the specified filter name. It is called
379 * as a reference function in a call to dissector_table_foreach_handle.
380 * The name we are looking for, as well as the results, are stored in the
381 * protocol_name_search struct pointed to by user_data.
382 * If called using dissector_table_foreach_handle, we actually parse the
383 * whole list of dissectors.
386 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
390 const gchar *protocol_filter_name;
391 protocol_name_search_t search_info;
395 search_info = (protocol_name_search_t)user_data;
397 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
398 if (proto_id != -1) {
399 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
400 g_assert(protocol_filter_name != NULL);
401 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
403 if (search_info->nb_match == 0) {
404 /* Record this handle only if this is the first match */
405 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
407 search_info->nb_match++;
413 * Print all layer type names supported.
414 * We send the output to the stream described by the handle output.
418 fprint_all_layer_types(FILE *output)
421 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
425 * Print all protocol names supported for a specific layer type.
426 * table_name contains the layer type name in which the search is performed.
427 * We send the output to the stream described by the handle output.
431 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
434 dissector_table_foreach_handle(table_name,
435 display_dissector_names,
440 * The function below parses the command-line parameters for the decode as
441 * feature (a string pointer by cl_param).
442 * It checks the format of the command-line, searches for a matching table
443 * and dissector. If a table/dissector match is not found, we display a
444 * summary of the available tables/dissectors (on stderr) and return FALSE.
445 * If everything is fine, we get the "Decode as" preference activated,
446 * then we return TRUE.
449 add_decode_as(const gchar *cl_param)
453 gchar *decoded_param;
454 gchar *remaining_param;
456 gchar *dissector_str;
457 dissector_handle_t dissector_matching;
458 dissector_table_t table_matching;
459 ftenum_t dissector_table_selector_type;
460 struct protocol_name_search user_protocol_name;
462 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
465 decoded_param = g_strdup(cl_param);
466 g_assert(decoded_param);
469 /* The lines below will parse this string (modifying it) to extract all
470 necessary information. Note that decoded_param is still needed since
471 strings are not copied - we just save pointers. */
473 /* This section extracts a layer type (table_name) from decoded_param */
474 table_name = decoded_param; /* Layer type string starts from beginning */
476 remaining_param = strchr(table_name, '=');
477 if (remaining_param == NULL) {
478 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
479 /* If the argument does not follow the template, carry on anyway to check
480 if the table name is at least correct. If remaining_param is NULL,
481 we'll exit anyway further down */
484 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
487 /* Remove leading and trailing spaces from the table name */
488 while ( table_name[0] == ' ' )
490 while ( table_name[strlen(table_name) - 1] == ' ' )
491 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
493 /* The following part searches a table matching with the layer type specified */
494 table_matching = NULL;
496 /* Look for the requested table */
497 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
498 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
501 table_matching = find_dissector_table(table_name);
502 if (!table_matching) {
503 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
507 if (!table_matching) {
508 /* Display a list of supported layer types to help the user, if the
509 specified layer type was not found */
510 cmdarg_err("Valid layer types are:");
511 fprint_all_layer_types(stderr);
513 if (remaining_param == NULL || !table_matching) {
514 /* Exit if the layer type was not found, or if no '=' separator was found
516 g_free(decoded_param);
520 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
521 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
524 remaining_param++; /* Move to the second '=' */
525 *remaining_param = '\0'; /* Remove the second '=' */
527 remaining_param++; /* Position after the layer type string */
529 /* This section extracts a selector value (selector_str) from decoded_param */
531 selector_str = remaining_param; /* Next part starts with the selector number */
533 remaining_param = strchr(selector_str, ',');
534 if (remaining_param == NULL) {
535 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
536 /* If the argument does not follow the template, carry on anyway to check
537 if the selector value is at least correct. If remaining_param is NULL,
538 we'll exit anyway further down */
541 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
544 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
546 switch (dissector_table_selector_type) {
552 /* The selector for this table is an unsigned number. Parse it as such.
553 There's no need to remove leading and trailing spaces from the
554 selector number string, because sscanf will do that for us. */
555 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
556 cmdarg_err("Invalid selector number \"%s\"", selector_str);
557 g_free(decoded_param);
565 /* The selector for this table is a string. */
569 /* There are currently no dissector tables with any types other
570 than the ones listed above. */
571 g_assert_not_reached();
574 if (remaining_param == NULL) {
575 /* Exit if no ',' separator was found (see above) */
576 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
577 fprint_all_protocols_for_layer_types(stderr, table_name);
578 g_free(decoded_param);
582 remaining_param++; /* Position after the selector number string */
584 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
586 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
588 /* Remove leading and trailing spaces from the dissector name */
589 while ( dissector_str[0] == ' ' )
591 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
592 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
594 dissector_matching = NULL;
596 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
597 if ( ! (*dissector_str) ) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
598 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
601 user_protocol_name.nb_match = 0;
602 user_protocol_name.searched_name = dissector_str;
603 user_protocol_name.matched_handle = NULL;
605 dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
607 if (user_protocol_name.nb_match != 0) {
608 dissector_matching = user_protocol_name.matched_handle;
609 if (user_protocol_name.nb_match > 1) {
610 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
614 /* OK, check whether the problem is that there isn't any such
615 protocol, or that there is but it's not specified as a protocol
616 that's valid for that dissector table.
617 Note, we don't exit here, but dissector_matching will remain NULL,
619 if (proto_get_id_by_filter_name(dissector_str) == -1) {
620 /* No such protocol */
621 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
623 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
624 dissector_str, table_name);
629 if (!dissector_matching) {
630 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
631 fprint_all_protocols_for_layer_types(stderr, table_name);
632 g_free(decoded_param);
636 /* This is the end of the code that parses the command-line options.
637 All information is now stored in the variables:
641 The above variables that are strings are still pointing to areas within
642 decoded_parm. decoded_parm thus still needs to be kept allocated in
643 until we stop needing these variables
644 decoded_param will be deallocated at each exit point of this function */
647 /* We now have a pointer to the handle for the requested dissector
648 (requested protocol) inside the variable dissector_matching */
649 switch (dissector_table_selector_type) {
655 /* The selector for this table is an unsigned number. */
656 dissector_change_uint(table_name, selector, dissector_matching);
662 /* The selector for this table is a string. */
663 dissector_change_string(table_name, selector_str, dissector_matching);
667 /* There are currently no dissector tables with any types other
668 than the ones listed above. */
669 g_assert_not_reached();
671 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
676 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
677 const gchar *message, gpointer user_data)
679 /* ignore log message, if log_level isn't interesting based
680 upon the console log preferences.
681 If the preferences haven't been loaded loaded yet, display the
684 The default console_log_level preference value is such that only
685 ERROR, CRITICAL and WARNING level messages are processed;
686 MESSAGE, INFO and DEBUG level messages are ignored.
688 XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
689 ERROR and CRITICAL level messages so the current code is a behavioral
690 change. The current behavior is the same as in Wireshark.
692 if((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
693 prefs.console_log_level != 0) {
697 g_log_default_handler(log_domain, log_level, message, user_data);
702 output_file_description(const char *fname)
704 char *save_file_string;
706 /* Get a string that describes what we're writing to */
707 if (strcmp(fname, "-") == 0) {
708 /* We're writing to the standard output */
709 save_file_string = g_strdup("standard output");
711 /* We're writing to a file with the name in save_file */
712 save_file_string = g_strdup_printf("file \"%s\"", fname);
714 return save_file_string;
718 print_current_user(void) {
719 gchar *cur_user, *cur_group;
720 if (started_with_special_privs()) {
721 cur_user = get_cur_username();
722 cur_group = get_cur_groupname();
723 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
724 cur_user, cur_group);
727 if (running_with_special_privs()) {
728 fprintf(stderr, " This could be dangerous.");
730 fprintf(stderr, "\n");
735 check_capture_privs(void) {
738 /* Warn the user if npf.sys isn't loaded. */
739 if (!npf_sys_is_running() && get_os_major_version() >= 6) {
740 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
741 "capturing or\nlisting interfaces.\n");
747 show_version(GString *comp_info_str, GString *runtime_info_str)
749 printf("TShark " VERSION "%s\n"
756 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
757 runtime_info_str->str);
761 main(int argc, char *argv[])
763 char *init_progfile_dir_error;
765 gboolean arg_error = FALSE;
773 char *gpf_path, *pf_path;
774 char *gdp_path, *dp_path;
775 int gpf_open_errno, gpf_read_errno;
776 int pf_open_errno, pf_read_errno;
777 int gdp_open_errno, gdp_read_errno;
778 int dp_open_errno, dp_read_errno;
782 gboolean list_link_layer_types = FALSE;
783 gboolean start_capture = FALSE;
788 gboolean capture_option_specified = FALSE;
790 gboolean quiet = FALSE;
791 int out_file_type = WTAP_FILE_PCAP;
792 gchar *cf_name = NULL, *rfilter = NULL;
793 #ifdef HAVE_PCAP_OPEN_DEAD
794 struct bpf_program fcode;
796 dfilter_t *rfcode = NULL;
799 GLogLevelFlags log_flags;
803 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
804 #define OPTSTRING_B "B:"
806 #define OPTSTRING_B ""
807 #endif /* _WIN32 or HAVE_PCAP_CREATE */
808 #else /* HAVE_LIBPCAP */
809 #define OPTSTRING_B ""
810 #endif /* HAVE_LIBPCAP */
812 #ifdef HAVE_PCAP_CREATE
813 #define OPTSTRING_I "I"
815 #define OPTSTRING_I ""
818 #define OPTSTRING "a:b:" OPTSTRING_B "c:C:d:De:E:f:F:G:hi:" OPTSTRING_I "K:lLnN:o:pPqr:R:s:St:T:u:vVw:xX:y:z:"
820 static const char optstring[] = OPTSTRING;
823 /* Convert our arg list to UTF-8. */
824 wc_argv = CommandLineToArgvW(GetCommandLineW(), &wc_argc);
825 if (wc_argv && wc_argc == argc) {
826 for (i = 0; i < argc; i++) {
827 argv[i] = g_utf16_to_utf8(wc_argv[i], -1, NULL, NULL, NULL);
829 } /* XXX else bail because something is horribly, horribly wrong? */
833 * Get credential information for later use.
835 init_process_policies();
838 * Attempt to get the pathname of the executable file.
840 init_progfile_dir_error = init_progfile_dir(argv[0], main);
841 if (init_progfile_dir_error != NULL) {
842 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
843 init_progfile_dir_error);
847 * In order to have the -X opts assigned before the wslua machine starts
848 * we need to call getopts before epan_init() gets called.
851 optind_initial = optind;
853 while ((opt = getopt(argc, argv, optstring)) != -1) {
855 case 'C': /* Configuration Profile */
856 if (profile_exists (optarg)) {
857 set_profile_name (optarg);
859 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
871 optind = optind_initial;
876 /** Send All g_log messages to our own handler **/
880 G_LOG_LEVEL_CRITICAL|
885 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
887 g_log_set_handler(NULL,
889 tshark_log_handler, NULL /* user_data */);
890 g_log_set_handler(LOG_DOMAIN_MAIN,
892 tshark_log_handler, NULL /* user_data */);
895 g_log_set_handler(LOG_DOMAIN_CAPTURE,
897 tshark_log_handler, NULL /* user_data */);
898 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
900 tshark_log_handler, NULL /* user_data */);
903 initialize_funnel_ops();
906 capture_opts_init(&global_capture_opts, &cfile);
909 timestamp_set_type(TS_RELATIVE);
910 timestamp_set_precision(TS_PREC_AUTO);
911 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
913 /* Register all dissectors; we must do this before checking for the
914 "-G" flag, as the "-G" flag dumps information registered by the
915 dissectors, and we must do it before we read the preferences, in
916 case any dissectors register preferences. */
917 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
918 failure_message, open_failure_message, read_failure_message,
919 write_failure_message);
921 /* Register all tap listeners; we do this before we parse the arguments,
922 as the "-z" argument can specify a registered tap. */
924 /* we register the plugin taps before the other taps because
925 stats_tree taps plugins will be registered as tap listeners
926 by stats_tree_stat.c and need to registered before that */
928 register_all_plugin_tap_listeners();
930 register_all_tap_listeners();
932 /* Now register the preferences for any non-dissector modules.
933 We must do that before we read the preferences as well. */
934 prefs_register_modules();
936 /* If invoked with the "-G" flag, we dump out information based on
937 the argument to the "-G" flag; if no argument is specified,
938 for backwards compatibility we dump out a glossary of display
941 XXX - we do this here, for now, to support "-G" with no arguments.
942 If none of our build or other processes uses "-G" with no arguments,
943 we can just process it with the other arguments. */
944 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
945 proto_initialize_all_prefixes();
948 proto_registrar_dump_fields(1);
950 if (strcmp(argv[2], "fields") == 0)
951 proto_registrar_dump_fields(1);
952 else if (strcmp(argv[2], "fields2") == 0)
953 proto_registrar_dump_fields(2);
954 else if (strcmp(argv[2], "fields3") == 0)
955 proto_registrar_dump_fields(3);
956 else if (strcmp(argv[2], "protocols") == 0)
957 proto_registrar_dump_protocols();
958 else if (strcmp(argv[2], "values") == 0)
959 proto_registrar_dump_values();
960 else if (strcmp(argv[2], "decodes") == 0)
961 dissector_dump_decodes();
962 else if (strcmp(argv[2], "defaultprefs") == 0)
964 else if (strcmp(argv[2], "?") == 0)
965 glossary_option_help();
966 else if (strcmp(argv[2], "-?") == 0)
967 glossary_option_help();
968 else if (strcmp(argv[2], "currentprefs") == 0) {
969 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
970 &pf_open_errno, &pf_read_errno, &pf_path);
973 cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
980 /* Set the C-language locale to the native environment. */
981 setlocale(LC_ALL, "");
983 prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
984 &pf_open_errno, &pf_read_errno, &pf_path);
985 if (gpf_path != NULL) {
986 if (gpf_open_errno != 0) {
987 cmdarg_err("Can't open global preferences file \"%s\": %s.",
988 pf_path, strerror(gpf_open_errno));
990 if (gpf_read_errno != 0) {
991 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
992 pf_path, strerror(gpf_read_errno));
995 if (pf_path != NULL) {
996 if (pf_open_errno != 0) {
997 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
998 strerror(pf_open_errno));
1000 if (pf_read_errno != 0) {
1001 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
1002 pf_path, strerror(pf_read_errno));
1008 /* Set the name resolution code's flags from the preferences. */
1009 gbl_resolv_flags = prefs_p->name_resolve;
1011 /* Read the disabled protocols file. */
1012 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
1013 &dp_path, &dp_open_errno, &dp_read_errno);
1014 if (gdp_path != NULL) {
1015 if (gdp_open_errno != 0) {
1016 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
1017 gdp_path, strerror(gdp_open_errno));
1019 if (gdp_read_errno != 0) {
1020 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
1021 gdp_path, strerror(gdp_read_errno));
1025 if (dp_path != NULL) {
1026 if (dp_open_errno != 0) {
1028 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
1029 strerror(dp_open_errno));
1031 if (dp_read_errno != 0) {
1033 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
1034 strerror(dp_read_errno));
1039 check_capture_privs();
1041 cap_file_init(&cfile);
1043 /* Print format defaults to this. */
1044 print_format = PR_FMT_TEXT;
1046 output_fields = output_fields_new();
1048 /* Now get our args */
1049 while ((opt = getopt(argc, argv, optstring)) != -1) {
1051 case 'a': /* autostop criteria */
1052 case 'b': /* Ringbuffer option */
1053 case 'c': /* Capture x packets */
1054 case 'f': /* capture filter */
1055 case 'i': /* Use interface x */
1056 case 'p': /* Don't capture in promiscuous mode */
1057 #ifdef HAVE_PCAP_CREATE
1058 case 'I': /* Capture in monitor mode, if available */
1060 case 's': /* Set the snapshot (capture) length */
1061 case 'w': /* Write to capture file x */
1062 case 'y': /* Set the pcap data link type */
1063 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1064 case 'B': /* Buffer size */
1065 #endif /* _WIN32 or HAVE_PCAP_CREATE */
1067 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1072 capture_option_specified = TRUE;
1077 /* Configuration profile settings were already processed just ignore them this time*/
1079 case 'd': /* Decode as rule */
1080 if (!add_decode_as(optarg))
1083 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1084 case 'K': /* Kerberos keytab file */
1085 read_keytab_file(optarg);
1088 case 'D': /* Print a list of capture devices and exit */
1090 if_list = capture_interface_list(&err, &err_str);
1091 if (if_list == NULL) {
1093 case CANT_GET_INTERFACE_LIST:
1094 cmdarg_err("%s", err_str);
1098 case NO_INTERFACES_FOUND:
1099 cmdarg_err("There are no interfaces on which a capture can be done");
1104 capture_opts_print_interfaces(if_list);
1105 free_interface_list(if_list);
1108 capture_option_specified = TRUE;
1114 output_fields_add(output_fields, optarg);
1118 if(!output_fields_set_option(output_fields, optarg)) {
1119 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1120 output_fields_list_options(stderr);
1125 out_file_type = wtap_short_string_to_file_type(optarg);
1126 if (out_file_type < 0) {
1127 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1128 list_capture_types();
1132 case 'h': /* Print help and exit */
1136 case 'l': /* "Line-buffer" standard output */
1137 /* This isn't line-buffering, strictly speaking, it's just
1138 flushing the standard output after the information for
1139 each packet is printed; however, that should be good
1140 enough for all the purposes to which "-l" is put (and
1141 is probably actually better for "-V", as it does fewer
1144 See the comment in "process_packet()" for an explanation of
1145 why we do that, and why we don't just use "setvbuf()" to
1146 make the standard output line-buffered (short version: in
1147 Windows, "line-buffered" is the same as "fully-buffered",
1148 and the output buffer is only flushed when it fills up). */
1149 line_buffered = TRUE;
1151 case 'L': /* Print list of link-layer types and exit */
1153 list_link_layer_types = TRUE;
1155 capture_option_specified = TRUE;
1159 #if GLIB_CHECK_VERSION(2,10,0)
1160 case 'P': /* Perform two pass analysis */
1161 perform_two_pass_analysis = TRUE;
1164 case 'n': /* No name resolution */
1165 gbl_resolv_flags = RESOLV_NONE;
1167 case 'N': /* Select what types of addresses/port #s to resolve */
1168 if (gbl_resolv_flags == RESOLV_ALL)
1169 gbl_resolv_flags = RESOLV_NONE;
1170 badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
1171 if (badopt != '\0') {
1172 cmdarg_err("-N specifies unknown resolving option '%c';",
1174 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1178 case 'o': /* Override preference from command line */
1179 switch (prefs_set_pref(optarg)) {
1184 case PREFS_SET_SYNTAX_ERR:
1185 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1189 case PREFS_SET_NO_SUCH_PREF:
1190 case PREFS_SET_OBSOLETE:
1191 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1196 case 'q': /* Quiet */
1199 case 'r': /* Read capture file x */
1200 cf_name = g_strdup(optarg);
1202 case 'R': /* Read file filter */
1205 case 'S': /* show packets in real time */
1206 print_packet_info = TRUE;
1208 case 't': /* Time stamp type */
1209 if (strcmp(optarg, "r") == 0)
1210 timestamp_set_type(TS_RELATIVE);
1211 else if (strcmp(optarg, "a") == 0)
1212 timestamp_set_type(TS_ABSOLUTE);
1213 else if (strcmp(optarg, "ad") == 0)
1214 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1215 else if (strcmp(optarg, "d") == 0)
1216 timestamp_set_type(TS_DELTA);
1217 else if (strcmp(optarg, "dd") == 0)
1218 timestamp_set_type(TS_DELTA_DIS);
1219 else if (strcmp(optarg, "e") == 0)
1220 timestamp_set_type(TS_EPOCH);
1222 cmdarg_err("Invalid time stamp type \"%s\"",
1224 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1225 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1229 case 'T': /* printing Type */
1230 if (strcmp(optarg, "text") == 0) {
1231 output_action = WRITE_TEXT;
1232 print_format = PR_FMT_TEXT;
1233 } else if (strcmp(optarg, "ps") == 0) {
1234 output_action = WRITE_TEXT;
1235 print_format = PR_FMT_PS;
1236 } else if (strcmp(optarg, "pdml") == 0) {
1237 output_action = WRITE_XML;
1239 } else if (strcmp(optarg, "psml") == 0) {
1240 output_action = WRITE_XML;
1242 } else if(strcmp(optarg, "fields") == 0) {
1243 output_action = WRITE_FIELDS;
1244 verbose = TRUE; /* Need full tree info */
1246 cmdarg_err("Invalid -T parameter.");
1247 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1251 case 'u': /* Seconds type */
1252 if (strcmp(optarg, "s") == 0)
1253 timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1254 else if (strcmp(optarg, "hms") == 0)
1255 timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1257 cmdarg_err("Invalid seconds type \"%s\"", optarg);
1258 cmdarg_err_cont("It must be \"s\" for seconds or \"hms\" for hours, minutes and seconds.");
1262 case 'v': /* Show version and exit */
1264 GString *comp_info_str;
1265 GString *runtime_info_str;
1266 /* Assemble the compile-time version information string */
1267 comp_info_str = g_string_new("Compiled ");
1268 get_compiled_version_info(comp_info_str, NULL, epan_get_compiled_version_info);
1270 /* Assemble the run-time version information string */
1271 runtime_info_str = g_string_new("Running ");
1272 get_runtime_version_info(runtime_info_str, NULL);
1273 show_version(comp_info_str, runtime_info_str);
1274 g_string_free(comp_info_str, TRUE);
1275 g_string_free(runtime_info_str, TRUE);
1279 case 'V': /* Verbose */
1281 /* The user asked for a verbose output, so let's ensure they get it,
1282 * even if they're writing to a file.
1284 print_packet_info = TRUE;
1286 case 'x': /* Print packet data in hex (and ASCII) */
1288 /* The user asked for hex output, so let's ensure they get it,
1289 * even if they're writing to a file.
1291 print_packet_info = TRUE;
1296 /* We won't call the init function for the stat this soon
1297 as it would disallow MATE's fields (which are registered
1298 by the preferences set callback) from being used as
1299 part of a tap filter. Instead, we just add the argument
1300 to a list of stat arguments. */
1301 if (!process_stat_cmd_arg(optarg)) {
1302 cmdarg_err("invalid -z argument.");
1303 cmdarg_err_cont(" -z argument must be one of :");
1304 list_stat_cmd_args();
1309 case '?': /* Bad flag - print usage message */
1312 list_capture_types();
1322 /* If we specified output fields, but not the output field type... */
1323 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1324 cmdarg_err("Output fields were specified with \"-e\", "
1325 "but \"-Tfields\" was not specified.");
1327 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1328 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1329 "specified with \"-e\".");
1334 /* If no capture filter or read filter has been specified, and there are
1335 still command-line arguments, treat them as the tokens of a capture
1336 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1337 flag was specified. */
1338 if (optind < argc) {
1339 if (cf_name != NULL) {
1340 if (rfilter != NULL) {
1341 cmdarg_err("Read filters were specified both with \"-R\" "
1342 "and with additional command-line arguments");
1345 rfilter = get_args_as_string(argc, argv, optind);
1348 if (global_capture_opts.has_cfilter) {
1349 cmdarg_err("Capture filters were specified both with \"-f\""
1350 " and with additional command-line arguments");
1353 global_capture_opts.has_cfilter = TRUE;
1354 global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1356 capture_option_specified = TRUE;
1362 if (!global_capture_opts.saving_to_file) {
1363 /* We're not saving the capture to a file; if "-q" wasn't specified,
1364 we should print packet information */
1366 print_packet_info = TRUE;
1368 /* We're saving to a file; if we're writing to the standard output.
1369 and we'll also be writing dissected packets to the standard
1370 output, reject the request. At best, we could redirect that
1371 to the standard error; we *can't* write both to the standard
1372 output and have either of them be useful. */
1373 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1374 cmdarg_err("You can't write both raw packet data and dissected packets"
1375 " to the standard output.");
1380 /* We're not saving the capture to a file; if "-q" wasn't specified,
1381 we should print packet information */
1383 print_packet_info = TRUE;
1386 #ifndef HAVE_LIBPCAP
1387 if (capture_option_specified)
1388 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1395 /* We don't support capture filters when reading from a capture file
1396 (the BPF compiler doesn't support all link-layer types that we
1397 support in capture files we read). */
1399 if (cf_name != NULL) {
1400 if (global_capture_opts.has_cfilter) {
1401 cmdarg_err("Only read filters, not capture filters, "
1402 "can be specified when reading a capture file.");
1409 if (output_action != WRITE_TEXT) {
1410 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1416 if (list_link_layer_types) {
1417 /* We're supposed to list the link-layer types for an interface;
1418 did the user also specify a capture file to be read? */
1420 /* Yes - that's bogus. */
1421 cmdarg_err("You can't specify -L and a capture file to be read.");
1424 /* No - did they specify a ring buffer option? */
1425 if (global_capture_opts.multi_files_on) {
1426 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1432 * "-r" was specified, so we're reading a capture file.
1433 * Capture options don't apply here.
1435 if (global_capture_opts.multi_files_on) {
1436 cmdarg_err("Multiple capture files requested, but "
1437 "a capture isn't being done.");
1440 if (global_capture_opts.has_file_duration) {
1441 cmdarg_err("Switching capture files after a time interval was specified, but "
1442 "a capture isn't being done.");
1445 if (global_capture_opts.has_ring_num_files) {
1446 cmdarg_err("A ring buffer of capture files was specified, but "
1447 "a capture isn't being done.");
1450 if (global_capture_opts.has_autostop_files) {
1451 cmdarg_err("A maximum number of capture files was specified, but "
1452 "a capture isn't being done.");
1456 /* Note: TShark now allows the restriction of a _read_ file by packet count
1457 * and byte count as well as a write file. Other autostop options remain valid
1458 * only for a write file.
1460 if (global_capture_opts.has_autostop_duration) {
1461 cmdarg_err("A maximum capture time was specified, but "
1462 "a capture isn't being done.");
1467 * "-r" wasn't specified, so we're doing a live capture.
1469 if (global_capture_opts.saving_to_file) {
1470 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1472 /* When capturing, we only support writing libpcap format. */
1473 if (out_file_type != WTAP_FILE_PCAP) {
1474 cmdarg_err("Live captures can only be saved in libpcap format.");
1477 if (global_capture_opts.multi_files_on) {
1478 /* Multiple-file mode doesn't work under certain conditions:
1479 a) it doesn't work if you're writing to the standard output;
1480 b) it doesn't work if you're writing to a pipe;
1482 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1483 cmdarg_err("Multiple capture files requested, but "
1484 "the capture is being written to the standard output.");
1487 if (global_capture_opts.output_to_pipe) {
1488 cmdarg_err("Multiple capture files requested, but "
1489 "the capture file is a pipe.");
1492 if (!global_capture_opts.has_autostop_filesize &&
1493 !global_capture_opts.has_file_duration) {
1494 cmdarg_err("Multiple capture files requested, but "
1495 "no maximum capture file size or duration was specified.");
1499 /* Currently, we don't support read filters when capturing
1500 and saving the packets. */
1501 if (rfilter != NULL) {
1502 cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1506 /* They didn't specify a "-w" flag, so we won't be saving to a
1507 capture file. Check for options that only make sense if
1508 we're saving to a file. */
1509 if (global_capture_opts.has_autostop_filesize) {
1510 cmdarg_err("Maximum capture file size specified, but "
1511 "capture isn't being saved to a file.");
1514 if (global_capture_opts.multi_files_on) {
1515 cmdarg_err("Multiple capture files requested, but "
1516 "the capture isn't being saved to a file.");
1525 /* Start windows sockets */
1526 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1529 /* Notify all registered modules that have had any of their preferences
1530 changed either from one of the preferences file or from the command
1531 line that their preferences have changed. */
1534 /* At this point MATE will have registered its field array so we can
1535 have a tap filter with one of MATE's late-registered fields as part
1536 of the filter. We can now process all the "-z" arguments. */
1537 start_requested_stats();
1540 /* We currently don't support taps, or printing dissected packets,
1541 if we're writing to a pipe. */
1542 if (global_capture_opts.saving_to_file &&
1543 global_capture_opts.output_to_pipe) {
1544 if (have_tap_listeners()) {
1545 cmdarg_err("Taps aren't supported when saving to a pipe.");
1548 if (print_packet_info) {
1549 cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1555 /* disabled protocols as per configuration file */
1556 if (gdp_path == NULL && dp_path == NULL) {
1557 set_disabled_protos_list();
1560 /* Build the column format array */
1561 build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1564 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1565 capture_opts_trim_ring_num_files(&global_capture_opts);
1568 if (rfilter != NULL) {
1569 if (!dfilter_compile(rfilter, &rfcode)) {
1570 cmdarg_err("%s", dfilter_error_msg);
1572 #ifdef HAVE_PCAP_OPEN_DEAD
1576 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1578 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1580 " Note: That display filter code looks like a valid capture filter;");
1582 " maybe you mixed them up?");
1591 cfile.rfcode = rfcode;
1593 if (print_packet_info) {
1594 /* If we're printing as text or PostScript, we have
1595 to create a print stream. */
1596 if (output_action == WRITE_TEXT) {
1597 switch (print_format) {
1600 print_stream = print_stream_text_stdio_new(stdout);
1604 print_stream = print_stream_ps_stdio_new(stdout);
1608 g_assert_not_reached();
1613 /* We have to dissect each packet if:
1615 we're printing information about each packet;
1617 we're using a read filter on the packets;
1619 we're using any taps. */
1620 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1624 * We're reading a capture file.
1628 * Immediately relinquish any special privileges we have; we must not
1629 * be allowed to read any capture files the user running TShark
1632 relinquish_special_privs_perm();
1633 print_current_user();
1635 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1640 /* Set timestamp precision; there should arguably be a command-line
1641 option to let the user set this. */
1642 switch(wtap_file_tsprecision(cfile.wth)) {
1643 case(WTAP_FILE_TSPREC_SEC):
1644 timestamp_set_precision(TS_PREC_AUTO_SEC);
1646 case(WTAP_FILE_TSPREC_DSEC):
1647 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1649 case(WTAP_FILE_TSPREC_CSEC):
1650 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1652 case(WTAP_FILE_TSPREC_MSEC):
1653 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1655 case(WTAP_FILE_TSPREC_USEC):
1656 timestamp_set_precision(TS_PREC_AUTO_USEC);
1658 case(WTAP_FILE_TSPREC_NSEC):
1659 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1662 g_assert_not_reached();
1665 /* Process the packets in the file */
1667 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1668 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1669 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1671 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1674 /* We still dump out the results of taps, etc., as we might have
1675 read some packets; however, we exit with an error status. */
1679 /* No capture file specified, so we're supposed to do a live capture
1680 (or get a list of link-layer types for a live capture device);
1681 do we have support for live captures? */
1688 cmdarg_err("WinPcap couldn't be found.");
1689 detailed_err = cant_load_winpcap_err("TShark");
1690 cmdarg_err_cont("%s", detailed_err);
1691 g_free(detailed_err);
1696 /* trim the interface name and exit if that failed */
1697 if (!capture_opts_trim_iface(&global_capture_opts,
1698 (prefs_p->capture_device) ? get_if_name(prefs_p->capture_device) : NULL)) {
1702 /* if requested, list the link layer types and exit */
1703 if (list_link_layer_types) {
1704 /* Get the list of link-layer types for the capture device. */
1705 if_capabilities_t *caps;
1707 caps = capture_get_if_capabilities(global_capture_opts.iface,
1708 global_capture_opts.monitor_mode,
1711 cmdarg_err("%s", err_str);
1715 if (caps->data_link_types == NULL) {
1716 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
1719 capture_opts_print_if_capabilities(caps,
1720 global_capture_opts.monitor_mode);
1721 free_if_capabilities(caps);
1725 if (print_packet_info) {
1726 if (!write_preamble(NULL)) {
1727 show_print_file_io_error(errno);
1730 } else if (!quiet) {
1732 * We're not printing information for each packet, and the user
1733 * didn't ask us not to print a count of packets as they arrive,
1734 * so print that count so the user knows that packets are arriving.
1736 * XXX - what if the user wants to do a live capture, doesn't want
1737 * to save it to a file, doesn't want information printed for each
1738 * packet, does want some "-z" statistic, and wants packet counts
1739 * so they know whether they're seeing any packets?
1741 print_packet_counts = TRUE;
1744 /* For now, assume libpcap gives microsecond precision. */
1745 timestamp_set_precision(TS_PREC_AUTO_USEC);
1748 * XXX - this returns FALSE if an error occurred, but it also
1749 * returns FALSE if the capture stops because a time limit
1750 * was reached (and possibly other limits), so we can't assume
1751 * it means an error.
1753 * The capture code is a bit twisty, so it doesn't appear to
1754 * be an easy fix. We just ignore the return value for now.
1755 * Instead, pass on the exit status from the capture child.
1758 exit_status = global_capture_opts.fork_child_status;
1760 if (print_packet_info) {
1761 if (!write_finale()) {
1763 show_print_file_io_error(err);
1767 /* No - complain. */
1768 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1775 #if GLIB_CHECK_VERSION(2,10,0)
1776 if (cfile.plist_start != NULL)
1777 g_slice_free_chain(frame_data, cfile.plist_start, next);
1780 draw_tap_listeners(TRUE);
1781 funnel_dump_all_text_windows();
1784 output_fields_free(output_fields);
1785 output_fields = NULL;
1790 /*#define USE_BROKEN_G_MAIN_LOOP*/
1792 #ifdef USE_BROKEN_G_MAIN_LOOP
1795 gboolean loop_running = FALSE;
1797 guint32 packet_count = 0;
1800 /* XXX - move to the right position / file */
1801 /* read from a pipe (callback) */
1802 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1804 typedef struct pipe_input_tag {
1808 pipe_input_cb_t input_cb;
1809 guint pipe_input_id;
1811 GStaticMutex callback_running;
1815 static pipe_input_t pipe_input;
1818 /* The timer has expired, see if there's stuff to read from the pipe,
1819 if so, do the callback */
1821 pipe_timer_cb(gpointer data)
1825 gboolean result, result1;
1827 pipe_input_t *pipe_input = data;
1828 gint iterations = 0;
1831 g_static_mutex_lock (&pipe_input->callback_running);
1833 /* try to read data from the pipe only 5 times, to avoid blocking */
1834 while(iterations < 5) {
1835 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1837 /* Oddly enough although Named pipes don't work on win9x,
1838 PeekNamedPipe does !!! */
1839 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1840 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1842 /* Get the child process exit status */
1843 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1846 /* If the Peek returned an error, or there are bytes to be read
1847 or the childwatcher thread has terminated then call the normal
1849 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1851 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1853 /* And call the real handler */
1854 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1855 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1856 /* pipe closed, return false so that the timer is stopped */
1857 g_static_mutex_unlock (&pipe_input->callback_running);
1862 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1863 /* No data, stop now */
1870 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1872 g_static_mutex_unlock (&pipe_input->callback_running);
1874 /* we didn't stopped the timer, so let it run */
1881 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1884 pipe_input.source = source;
1885 pipe_input.child_process = child_process;
1886 pipe_input.user_data = user_data;
1887 pipe_input.input_cb = input_cb;
1890 g_static_mutex_init(&pipe_input.callback_running);
1891 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1892 do this but that doesn't cover all win32 platforms. GTK can do
1893 this but doesn't seem to work over processes. Attempt to do
1894 something similar here, start a timer and check for data on every
1896 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1897 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1907 #ifdef USE_TSHARK_SELECT
1911 struct sigaction action, oldaction;
1915 * XXX - dropping privileges is still required, until code cleanup is done
1917 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1918 * when it's done, we don't need special privileges to run tshark at all,
1919 * therefore we don't need to drop these privileges
1920 * The only thing we might want to keep is a warning if tshark is run as root,
1921 * as it's no longer necessary and potentially dangerous.
1923 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1924 * We've opened the capture device, so we shouldn't need any special
1925 * privileges any more; relinquish those privileges.
1927 * XXX - if we have saved set-user-ID support, we should give up those
1928 * privileges immediately, and then reclaim them long enough to get
1929 * a list of network interfaces and to open one, and then give them
1930 * up again, so that stuff we do while processing the argument list,
1931 * reading the user's preferences, loading and starting plugins
1932 * (especially *user* plugins), etc. is done with the user's privileges,
1933 * not special privileges.
1935 relinquish_special_privs_perm();
1936 print_current_user();
1938 /* Cleanup all data structures used for dissection. */
1939 cleanup_dissection();
1940 /* Initialize all data structures used for dissection. */
1944 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1945 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1947 /* Catch SIGINT and SIGTERM and, if we get either of them,
1948 clean up and exit. If SIGHUP isn't being ignored, catch
1949 it too and, if we get it, clean up and exit.
1951 We restart any read that was in progress, so that it doesn't
1952 disrupt reading from the sync pipe. The signal handler tells
1953 the capture child to finish; it will report that it finished,
1954 or will exit abnormally, so we'll stop reading from the sync
1955 pipe, pick up the exit status, and quit. */
1956 action.sa_handler = capture_cleanup;
1957 action.sa_flags = SA_RESTART;
1958 sigemptyset(&action.sa_mask);
1959 sigaction(SIGTERM, &action, NULL);
1960 sigaction(SIGINT, &action, NULL);
1961 sigaction(SIGHUP, NULL, &oldaction);
1962 if (oldaction.sa_handler == SIG_DFL)
1963 sigaction(SIGHUP, &action, NULL);
1966 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1967 quiet mode, report the number of packets we've captured.
1969 Again, restart any read that was in progress, so that it doesn't
1970 disrupt reading from the sync pipe. */
1971 action.sa_handler = report_counts_siginfo;
1972 action.sa_flags = SA_RESTART;
1973 sigemptyset(&action.sa_mask);
1974 sigaction(SIGINFO, &action, NULL);
1975 #endif /* SIGINFO */
1978 global_capture_opts.state = CAPTURE_PREPARING;
1980 /* Let the user know what interface was chosen. */
1981 global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1982 fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1984 ret = sync_pipe_start(&global_capture_opts);
1989 /* the actual capture loop
1991 * XXX - glib doesn't seem to provide any event based loop handling.
1993 * XXX - for whatever reason,
1994 * calling g_main_loop_new() ends up in 100% cpu load.
1996 * But that doesn't matter: in UNIX we can use select() to find an input
1997 * source with something to do.
1999 * But that doesn't matter because we're in a CLI (that doesn't need to
2000 * update a GUI or something at the same time) so it's OK if we block
2001 * trying to read from the pipe.
2003 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2004 * wrong (but I leave it there in case I am...).
2007 #ifdef USE_TSHARK_SELECT
2009 FD_SET(pipe_input.source, &readfds);
2012 loop_running = TRUE;
2014 while (loop_running)
2016 #ifdef USE_TSHARK_SELECT
2017 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2023 } else if (ret == 1) {
2025 /* Call the real handler */
2026 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2027 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2030 #ifdef USE_TSHARK_SELECT
2039 /* XXX - move the call to main_window_update() out of capture_sync.c */
2040 /* dummy for capture_sync.c to make linker happy */
2041 void main_window_update(void)
2045 /* capture child detected an error */
2047 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
2049 cmdarg_err("%s", error_msg);
2050 cmdarg_err_cont("%s", secondary_error_msg);
2054 /* capture child detected an capture filter related error */
2056 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
2058 dfilter_t *rfcode = NULL;
2061 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
2063 "Invalid capture filter: \"%s\"!\n"
2065 "That string looks like a valid display filter; however, it isn't a valid\n"
2066 "capture filter (%s).\n"
2068 "Note that display filters and capture filters don't have the same syntax,\n"
2069 "so you can't use most display filter expressions as capture filters.\n"
2071 "See the User's Guide for a description of the capture filter syntax.",
2072 capture_opts->cfilter, error_message);
2073 dfilter_free(rfcode);
2076 "Invalid capture filter: \"%s\"!\n"
2078 "That string isn't a valid capture filter (%s).\n"
2079 "See the User's Guide for a description of the capture filter syntax.",
2080 capture_opts->cfilter, error_message);
2085 /* capture child tells us we have a new (or the first) capture file */
2087 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
2089 gboolean is_tempfile;
2092 if(capture_opts->state == CAPTURE_PREPARING) {
2093 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
2095 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2097 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
2099 /* free the old filename */
2100 if (capture_opts->save_file != NULL) {
2102 /* we start a new capture file, close the old one (if we had one before) */
2103 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
2104 if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
2105 wtap_close(((capture_file *) capture_opts->cf)->wth);
2107 ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
2110 g_free(capture_opts->save_file);
2111 is_tempfile = FALSE;
2113 /* we didn't had a save_file before, must be a tempfile */
2117 /* save the new filename */
2118 capture_opts->save_file = g_strdup(new_file);
2120 /* if we are in real-time mode, open the new file now */
2122 /* Attempt to open the capture file and set up to read from it. */
2123 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
2127 /* Don't unlink (delete) the save file - leave it around,
2128 for debugging purposes. */
2129 g_free(capture_opts->save_file);
2130 capture_opts->save_file = NULL;
2135 capture_opts->state = CAPTURE_RUNNING;
2141 /* capture child tells us we have new packets to read */
2143 capture_input_new_packets(capture_options *capture_opts, int to_read)
2149 capture_file *cf = capture_opts->cf;
2150 gboolean filtering_tap_listeners;
2155 * Prevent a SIGINFO handler from writing to the standard error while
2156 * we're doing so or writing to the standard output; instead, have it
2157 * just set a flag telling us to print that information when we're done.
2160 #endif /* SIGINFO */
2162 /* Do we have any tap listeners with filters? */
2163 filtering_tap_listeners = have_filtering_tap_listeners();
2165 /* Get the union of the flags for all tap listeners. */
2166 tap_flags = union_of_tap_listener_flags();
2169 while (to_read-- && cf->wth) {
2170 wtap_cleareof(cf->wth);
2171 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2173 /* read from file failed, tell the capture child to stop */
2174 sync_pipe_stop(capture_opts);
2175 wtap_close(cf->wth);
2178 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2179 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2180 filtering_tap_listeners, tap_flags);
2183 /* packet sucessfully read and gone through the "Read Filter" */
2189 * Dumpcap's doing all the work; we're not doing any dissection.
2190 * Count all the packets it wrote.
2192 packet_count += to_read;
2195 if (print_packet_counts) {
2196 /* We're printing packet counts. */
2197 if (packet_count != 0) {
2198 fprintf(stderr, "\r%u ", packet_count);
2199 /* stderr could be line buffered */
2206 * Allow SIGINFO handlers to write.
2211 * If a SIGINFO handler asked us to write out capture counts, do so.
2215 #endif /* SIGINFO */
2221 if (!print_packet_counts) {
2222 /* Report the count only if we aren't printing a packet count
2223 as packets arrive. */
2224 fprintf(stderr, "%u packet%s captured\n", packet_count,
2225 plurality(packet_count, "", "s"));
2228 infoprint = FALSE; /* we just reported it */
2229 #endif /* SIGINFO */
2234 report_counts_siginfo(int signum _U_)
2236 int sav_errno = errno;
2237 /* If we've been told to delay printing, just set a flag asking
2238 that we print counts (if we're supposed to), otherwise print
2239 the count of packets captured (if we're supposed to). */
2246 #endif /* SIGINFO */
2249 /* capture child detected any packet drops? */
2251 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2253 if (print_packet_counts) {
2254 /* We're printing packet counts to stderr.
2255 Send a newline so that we move to the line after the packet count. */
2256 fprintf(stderr, "\n");
2260 /* We're printing packet counts to stderr.
2261 Send a newline so that we move to the line after the packet count. */
2262 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2268 * Capture child closed its side of the pipe, report any error and
2269 * do the required cleanup.
2272 capture_input_closed(capture_options *capture_opts, gchar *msg)
2275 fprintf(stderr, "tshark: %s\n", msg);
2279 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2280 wtap_close(((capture_file *) capture_opts->cf)->wth);
2281 if(((capture_file *) capture_opts->cf)->user_saved == FALSE){
2282 ws_unlink(((capture_file *) capture_opts->cf)->filename);
2285 #ifdef USE_BROKEN_G_MAIN_LOOP
2286 /*g_main_loop_quit(loop);*/
2289 loop_running = FALSE;
2298 capture_cleanup(DWORD ctrltype _U_)
2300 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2301 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2302 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2303 like SIGTERM at least when the machine's shutting down.
2305 For now, we handle them all as indications that we should clean up
2306 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2309 We must return TRUE so that no other handler - such as one that would
2310 terminate the process - gets called.
2312 XXX - for some reason, typing ^C to TShark, if you run this in
2313 a Cygwin console window in at least some versions of Cygwin,
2314 causes TShark to terminate immediately; this routine gets
2315 called, but the main loop doesn't get a chance to run and
2316 exit cleanly, at least if this is compiled with Microsoft Visual
2317 C++ (i.e., it's a property of the Cygwin console window or Bash;
2318 it happens if TShark is not built with Cygwin - for all I know,
2319 building it with Cygwin may make the problem go away). */
2321 /* tell the capture child to stop */
2322 sync_pipe_stop(&global_capture_opts);
2324 /* don't stop our own loop already here, otherwise status messages and
2325 * cleanup wouldn't be done properly. The child will indicate the stop of
2326 * everything by calling capture_input_closed() later */
2332 capture_cleanup(int signum _U_)
2334 /* tell the capture child to stop */
2335 sync_pipe_stop(&global_capture_opts);
2337 /* don't stop our own loop already here, otherwise status messages and
2338 * cleanup wouldn't be done properly. The child will indicate the stop of
2339 * everything by calling capture_input_closed() later */
2342 #endif /* HAVE_LIBPCAP */
2344 #if GLIB_CHECK_VERSION(2,10,0)
2346 process_packet_first_pass(capture_file *cf,
2347 gint64 offset, const struct wtap_pkthdr *whdr,
2348 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2350 frame_data *fdata = g_slice_new(frame_data);
2354 /* Count this packet. */
2357 /* If we're not running a display filter and we're not printing any
2358 packet information, we don't need to do a dissection. This means
2359 that all packets can be marked as 'passed'. */
2362 frame_data_init(fdata, cf->count, whdr, offset, cum_bytes);
2364 /* If we're going to print packet information, or we're going to
2365 run a read filter, or we're going to process taps, set up to
2366 do a dissection and do so. */
2367 if (do_dissection) {
2368 if (gbl_resolv_flags)
2369 /* Grab any resolved addresses */
2370 host_name_lookup_process(NULL);
2372 /* The protocol tree will be "visible", i.e., printed, only if we're
2373 printing packet details, which is true if we're printing stuff
2374 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2376 epan_dissect_init(&edt, FALSE, FALSE);
2378 /* If we're running a read filter, prime the epan_dissect_t with that
2381 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2383 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2384 &first_ts, &prev_dis_ts, &prev_cap_ts);
2386 epan_dissect_run(&edt, pseudo_header, pd, fdata, NULL);
2388 /* Run the read filter if we have one. */
2390 passed = dfilter_apply_edt(cf->rfcode, &edt);
2394 frame_data_set_after_dissect(fdata, &cum_bytes, &prev_dis_ts);
2395 cap_file_add_fdata(cf, fdata);
2398 g_slice_free(frame_data, fdata);
2401 epan_dissect_cleanup(&edt);
2407 process_packet_second_pass(capture_file *cf, frame_data *fdata,
2408 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2409 gboolean filtering_tap_listeners, guint tap_flags)
2411 gboolean create_proto_tree;
2416 /* If we're not running a display filter and we're not printing any
2417 packet information, we don't need to do a dissection. This means
2418 that all packets can be marked as 'passed'. */
2421 /* If we're going to print packet information, or we're going to
2422 run a read filter, or we're going to process taps, set up to
2423 do a dissection and do so. */
2424 if (do_dissection) {
2425 if (gbl_resolv_flags)
2426 /* Grab any resolved addresses */
2427 host_name_lookup_process(NULL);
2429 if (cf->rfcode || verbose || filtering_tap_listeners ||
2430 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2431 create_proto_tree = TRUE;
2433 create_proto_tree = FALSE;
2435 /* The protocol tree will be "visible", i.e., printed, only if we're
2436 printing packet details, which is true if we're printing stuff
2437 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2439 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2441 /* If we're running a read filter, prime the epan_dissect_t with that
2444 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2446 col_custom_prime_edt(&edt, &cf->cinfo);
2448 tap_queue_init(&edt);
2450 /* We only need the columns if either
2452 1) some tap needs the columns
2456 2) we're printing packet info but we're *not* verbose; in verbose
2457 mode, we print the protocol tree, not the protocol summary. */
2458 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2463 epan_dissect_run(&edt, pseudo_header, pd, fdata, cinfo);
2465 tap_push_tapped_queue(&edt);
2467 /* Run the read filter if we have one. */
2469 passed = dfilter_apply_edt(cf->rfcode, &edt);
2473 /* Process this packet. */
2474 if (print_packet_info) {
2475 /* We're printing packet information; print the information for
2478 print_packet(cf, &edt);
2480 print_packet(cf, NULL);
2482 /* The ANSI C standard does not appear to *require* that a line-buffered
2483 stream be flushed to the host environment whenever a newline is
2484 written, it just says that, on such a stream, characters "are
2485 intended to be transmitted to or from the host environment as a
2486 block when a new-line character is encountered".
2488 The Visual C++ 6.0 C implementation doesn't do what is intended;
2489 even if you set a stream to be line-buffered, it still doesn't
2490 flush the buffer at the end of every line.
2492 So, if the "-l" flag was specified, we flush the standard output
2493 at the end of a packet. This will do the right thing if we're
2494 printing packet summary lines, and, as we print the entire protocol
2495 tree for a single packet without waiting for anything to happen,
2496 it should be as good as line-buffered mode if we're printing
2497 protocol trees. (The whole reason for the "-l" flag in either
2498 tcpdump or TShark is to allow the output of a live capture to
2499 be piped to a program or script and to have that script see the
2500 information for the packet as soon as it's printed, rather than
2501 having to wait until a standard I/O buffer fills up. */
2505 if (ferror(stdout)) {
2506 show_print_file_io_error(errno);
2512 if (do_dissection) {
2513 epan_dissect_cleanup(&edt);
2520 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2521 int max_packet_count, gint64 max_byte_count)
2524 int snapshot_length;
2529 char *save_file_string = NULL;
2530 gboolean filtering_tap_listeners;
2533 linktype = wtap_file_encap(cf->wth);
2534 if (save_file != NULL) {
2535 /* Get a string that describes what we're writing to */
2536 save_file_string = output_file_description(save_file);
2538 /* Set up to write to the capture file. */
2539 snapshot_length = wtap_snapshot_length(cf->wth);
2540 if (snapshot_length == 0) {
2541 /* Snapshot length of input file not known. */
2542 snapshot_length = WTAP_MAX_PACKET_SIZE;
2544 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2545 FALSE /* compressed */, &err);
2548 /* We couldn't set up to write to the capture file. */
2551 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2552 cmdarg_err("Capture files can't be written in that format.");
2555 case WTAP_ERR_UNSUPPORTED_ENCAP:
2556 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2557 cmdarg_err("The capture file being read can't be written in "
2561 case WTAP_ERR_CANT_OPEN:
2562 cmdarg_err("The %s couldn't be created for some "
2563 "unknown reason.", save_file_string);
2566 case WTAP_ERR_SHORT_WRITE:
2567 cmdarg_err("A full header couldn't be written to the %s.",
2572 cmdarg_err("The %s could not be created: %s.", save_file_string,
2573 wtap_strerror(err));
2579 if (print_packet_info) {
2580 if (!write_preamble(cf)) {
2582 show_print_file_io_error(err);
2589 /* Do we have any tap listeners with filters? */
2590 filtering_tap_listeners = have_filtering_tap_listeners();
2592 /* Get the union of the flags for all tap listeners. */
2593 tap_flags = union_of_tap_listener_flags();
2595 if (perform_two_pass_analysis) {
2596 #if GLIB_CHECK_VERSION(2,10,0)
2598 int old_max_packet_count = max_packet_count;
2600 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2601 if (process_packet_first_pass(cf, data_offset, wtap_phdr(cf->wth),
2602 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2603 /* Stop reading if we have the maximum number of packets;
2604 * When the -c option has not been used, max_packet_count
2605 * starts at 0, which practically means, never stop reading.
2606 * (unless we roll over max_packet_count ?)
2608 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2609 err = 0; /* This is not an error */
2615 /* Close the sequential I/O side, to free up memory it requires. */
2616 wtap_sequential_close(cf->wth);
2618 /* Allow the protocol dissectors to free up memory that they
2619 * don't need after the sequential run-through of the packets. */
2620 postseq_cleanup_all_protocols();
2622 max_packet_count = old_max_packet_count;
2624 for (fdata = cf->plist_start; err == 0 && fdata != NULL; fdata = fdata->next) {
2625 if (wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
2626 cf->pd, fdata->cap_len, &err, &err_info)) {
2627 if (process_packet_second_pass(cf, fdata,
2628 &cf->pseudo_header, cf->pd,
2629 filtering_tap_listeners, tap_flags)) {
2630 /* Either there's no read filtering or this packet passed the
2631 filter, so, if we're writing to a capture file, write
2634 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2635 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2637 /* Error writing to a capture file */
2638 show_capture_file_io_error(save_file, err, FALSE);
2639 wtap_dump_close(pdh, &err);
2643 /* Stop reading if we have the maximum number of packets;
2644 * When the -c option has not been used, max_packet_count
2645 * starts at 0, which practically means, never stop reading.
2646 * (unless we roll over max_packet_count ?)
2648 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2649 err = 0; /* This is not an error */
2658 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2659 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2660 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2661 filtering_tap_listeners, tap_flags)) {
2662 /* Either there's no read filtering or this packet passed the
2663 filter, so, if we're writing to a capture file, write
2666 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2667 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2669 /* Error writing to a capture file */
2670 show_capture_file_io_error(save_file, err, FALSE);
2671 wtap_dump_close(pdh, &err);
2675 /* Stop reading if we have the maximum number of packets;
2676 * When the -c option has not been used, max_packet_count
2677 * starts at 0, which practically means, never stop reading.
2678 * (unless we roll over max_packet_count ?)
2680 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2681 err = 0; /* This is not an error */
2690 * Print a message noting that the read failed somewhere along the line.
2692 * If we're printing packet data, and the standard output and error are
2693 * going to the same place, flush the standard output, so everything
2694 * buffered up is written, and then print a newline to the standard error
2695 * before printing the error message, to separate it from the packet
2696 * data. (Alas, that only works on UN*X; st_dev is meaningless, and
2697 * the _fstat() documentation at Microsoft doesn't indicate whether
2698 * st_ino is even supported.)
2701 if (print_packet_info) {
2702 struct stat stat_stdout, stat_stderr;
2704 if (fstat(1, &stat_stdout) == 0 && fstat(2, &stat_stderr) == 0) {
2705 if (stat_stdout.st_dev == stat_stderr.st_dev &&
2706 stat_stdout.st_ino == stat_stderr.st_ino) {
2708 fprintf(stderr, "\n");
2715 case WTAP_ERR_UNSUPPORTED_ENCAP:
2716 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2717 cf->filename, err_info);
2721 case WTAP_ERR_CANT_READ:
2722 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2726 case WTAP_ERR_SHORT_READ:
2727 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2731 case WTAP_ERR_BAD_RECORD:
2732 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2733 cf->filename, err_info);
2738 cmdarg_err("An error occurred while reading \"%s\": %s.",
2739 cf->filename, wtap_strerror(err));
2742 if (save_file != NULL) {
2743 /* Now close the capture file. */
2744 if (!wtap_dump_close(pdh, &err))
2745 show_capture_file_io_error(save_file, err, TRUE);
2748 if (save_file != NULL) {
2749 /* Now close the capture file. */
2750 if (!wtap_dump_close(pdh, &err))
2751 show_capture_file_io_error(save_file, err, TRUE);
2753 if (print_packet_info) {
2754 if (!write_finale()) {
2756 show_print_file_io_error(err);
2763 wtap_close(cf->wth);
2766 g_free(save_file_string);
2772 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2773 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2774 gboolean filtering_tap_listeners, guint tap_flags)
2777 gboolean create_proto_tree;
2782 /* Count this packet. */
2785 /* If we're not running a display filter and we're not printing any
2786 packet information, we don't need to do a dissection. This means
2787 that all packets can be marked as 'passed'. */
2790 frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
2792 /* If we're going to print packet information, or we're going to
2793 run a read filter, or we're going to process taps, set up to
2794 do a dissection and do so. */
2795 if (do_dissection) {
2796 if (print_packet_info && gbl_resolv_flags)
2797 /* Grab any resolved addresses */
2798 host_name_lookup_process(NULL);
2800 if (cf->rfcode || verbose || filtering_tap_listeners ||
2801 (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2802 create_proto_tree = TRUE;
2804 create_proto_tree = FALSE;
2806 /* The protocol tree will be "visible", i.e., printed, only if we're
2807 printing packet details, which is true if we're printing stuff
2808 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2810 epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2812 /* If we're running a read filter, prime the epan_dissect_t with that
2815 epan_dissect_prime_dfilter(&edt, cf->rfcode);
2817 col_custom_prime_edt(&edt, &cf->cinfo);
2819 tap_queue_init(&edt);
2821 /* We only need the columns if either
2823 1) some tap needs the columns
2827 2) we're printing packet info but we're *not* verbose; in verbose
2828 mode, we print the protocol tree, not the protocol summary. */
2829 if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2834 frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
2835 &first_ts, &prev_dis_ts, &prev_cap_ts);
2837 epan_dissect_run(&edt, pseudo_header, pd, &fdata, cinfo);
2839 tap_push_tapped_queue(&edt);
2841 /* Run the read filter if we have one. */
2843 passed = dfilter_apply_edt(cf->rfcode, &edt);
2847 frame_data_set_after_dissect(&fdata, &cum_bytes, &prev_dis_ts);
2849 /* Process this packet. */
2850 if (print_packet_info) {
2851 /* We're printing packet information; print the information for
2854 print_packet(cf, &edt);
2856 print_packet(cf, NULL);
2858 /* The ANSI C standard does not appear to *require* that a line-buffered
2859 stream be flushed to the host environment whenever a newline is
2860 written, it just says that, on such a stream, characters "are
2861 intended to be transmitted to or from the host environment as a
2862 block when a new-line character is encountered".
2864 The Visual C++ 6.0 C implementation doesn't do what is intended;
2865 even if you set a stream to be line-buffered, it still doesn't
2866 flush the buffer at the end of every line.
2868 So, if the "-l" flag was specified, we flush the standard output
2869 at the end of a packet. This will do the right thing if we're
2870 printing packet summary lines, and, as we print the entire protocol
2871 tree for a single packet without waiting for anything to happen,
2872 it should be as good as line-buffered mode if we're printing
2873 protocol trees. (The whole reason for the "-l" flag in either
2874 tcpdump or TShark is to allow the output of a live capture to
2875 be piped to a program or script and to have that script see the
2876 information for the packet as soon as it's printed, rather than
2877 having to wait until a standard I/O buffer fills up. */
2881 if (ferror(stdout)) {
2882 show_print_file_io_error(errno);
2888 if (do_dissection) {
2889 epan_dissect_cleanup(&edt);
2890 frame_data_cleanup(&fdata);
2896 write_preamble(capture_file *cf)
2898 switch (output_action) {
2901 return print_preamble(print_stream, cf ? cf->filename : NULL);
2905 write_pdml_preamble(stdout);
2907 write_psml_preamble(stdout);
2908 return !ferror(stdout);
2911 write_fields_preamble(output_fields, stdout);
2912 return !ferror(stdout);
2915 g_assert_not_reached();
2921 get_line_buf(size_t len)
2923 static char *line_bufp = NULL;
2924 static size_t line_buf_len = 256;
2925 size_t new_line_buf_len;
2927 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2928 new_line_buf_len *= 2)
2930 if (line_bufp == NULL) {
2931 line_buf_len = new_line_buf_len;
2932 line_bufp = g_malloc(line_buf_len + 1);
2934 if (new_line_buf_len > line_buf_len) {
2935 line_buf_len = new_line_buf_len;
2936 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2943 print_columns(capture_file *cf)
2950 line_bufp = get_line_buf(256);
2953 for (i = 0; i < cf->cinfo.num_cols; i++) {
2954 switch (cf->cinfo.col_fmt[i]) {
2958 * Don't print this if we're doing a live capture from a network
2959 * interface - if we're doing a live capture, you won't be
2960 * able to look at the capture in the future (it's not being
2961 * saved anywhere), so the frame numbers are unlikely to be
2964 * (XXX - it might be nice to be able to save and print at
2965 * the same time, sort of like an "Update list of packets
2966 * in real time" capture in Wireshark.)
2968 if (global_capture_opts.iface != NULL)
2971 column_len = strlen(cf->cinfo.col_data[i]);
2974 line_bufp = get_line_buf(buf_offset + column_len);
2975 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2981 case COL_ABS_DATE_TIME: /* XXX - wider */
2982 column_len = strlen(cf->cinfo.col_data[i]);
2983 if (column_len < 10)
2985 line_bufp = get_line_buf(buf_offset + column_len);
2986 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2992 case COL_DEF_DL_SRC:
2993 case COL_RES_DL_SRC:
2994 case COL_UNRES_DL_SRC:
2995 case COL_DEF_NET_SRC:
2996 case COL_RES_NET_SRC:
2997 case COL_UNRES_NET_SRC:
2998 column_len = strlen(cf->cinfo.col_data[i]);
2999 if (column_len < 12)
3001 line_bufp = get_line_buf(buf_offset + column_len);
3002 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
3008 case COL_DEF_DL_DST:
3009 case COL_RES_DL_DST:
3010 case COL_UNRES_DL_DST:
3011 case COL_DEF_NET_DST:
3012 case COL_RES_NET_DST:
3013 case COL_UNRES_NET_DST:
3014 column_len = strlen(cf->cinfo.col_data[i]);
3015 if (column_len < 12)
3017 line_bufp = get_line_buf(buf_offset + column_len);
3018 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
3022 column_len = strlen(cf->cinfo.col_data[i]);
3023 line_bufp = get_line_buf(buf_offset + column_len);
3024 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
3027 buf_offset += column_len;
3028 if (i != cf->cinfo.num_cols - 1) {
3030 * This isn't the last column, so we need to print a
3031 * separator between this column and the next.
3033 * If we printed a network source and are printing a
3034 * network destination of the same type next, separate
3035 * them with "->"; if we printed a network destination
3036 * and are printing a network source of the same type
3037 * next, separate them with "<-"; otherwise separate them
3040 * We add enough space to the buffer for " <- " or " -> ",
3041 * even if we're only adding " ".
3043 line_bufp = get_line_buf(buf_offset + 4);
3044 switch (cf->cinfo.col_fmt[i]) {
3049 switch (cf->cinfo.col_fmt[i + 1]) {
3054 strcat(line_bufp + buf_offset, " -> ");
3059 strcat(line_bufp + buf_offset, " ");
3065 case COL_DEF_DL_SRC:
3066 case COL_RES_DL_SRC:
3067 case COL_UNRES_DL_SRC:
3068 switch (cf->cinfo.col_fmt[i + 1]) {
3070 case COL_DEF_DL_DST:
3071 case COL_RES_DL_DST:
3072 case COL_UNRES_DL_DST:
3073 strcat(line_bufp + buf_offset, " -> ");
3078 strcat(line_bufp + buf_offset, " ");
3084 case COL_DEF_NET_SRC:
3085 case COL_RES_NET_SRC:
3086 case COL_UNRES_NET_SRC:
3087 switch (cf->cinfo.col_fmt[i + 1]) {
3089 case COL_DEF_NET_DST:
3090 case COL_RES_NET_DST:
3091 case COL_UNRES_NET_DST:
3092 strcat(line_bufp + buf_offset, " -> ");
3097 strcat(line_bufp + buf_offset, " ");
3106 switch (cf->cinfo.col_fmt[i + 1]) {
3111 strcat(line_bufp + buf_offset, " <- ");
3116 strcat(line_bufp + buf_offset, " ");
3122 case COL_DEF_DL_DST:
3123 case COL_RES_DL_DST:
3124 case COL_UNRES_DL_DST:
3125 switch (cf->cinfo.col_fmt[i + 1]) {
3127 case COL_DEF_DL_SRC:
3128 case COL_RES_DL_SRC:
3129 case COL_UNRES_DL_SRC:
3130 strcat(line_bufp + buf_offset, " <- ");
3135 strcat(line_bufp + buf_offset, " ");
3141 case COL_DEF_NET_DST:
3142 case COL_RES_NET_DST:
3143 case COL_UNRES_NET_DST:
3144 switch (cf->cinfo.col_fmt[i + 1]) {
3146 case COL_DEF_NET_SRC:
3147 case COL_RES_NET_SRC:
3148 case COL_UNRES_NET_SRC:
3149 strcat(line_bufp + buf_offset, " <- ");
3154 strcat(line_bufp + buf_offset, " ");
3161 strcat(line_bufp + buf_offset, " ");
3167 return print_line(print_stream, 0, line_bufp);
3171 print_packet(capture_file *cf, epan_dissect_t *edt)
3173 print_args_t print_args;
3176 /* Print the information in the protocol tree. */
3177 switch (output_action) {
3180 print_args.to_file = TRUE;
3181 print_args.format = print_format;
3182 print_args.print_summary = !verbose;
3183 print_args.print_hex = verbose && print_hex;
3184 print_args.print_formfeed = FALSE;
3185 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
3187 /* init the packet range */
3188 packet_range_init(&print_args.range);
3190 if (!proto_tree_print(&print_args, edt, print_stream))
3193 /* "print_hex_data()" will put out a leading blank line, as well
3194 as a trailing one; print one here, to separate the packets,
3195 only if "print_hex_data()" won't be called. */
3196 if (!print_line(print_stream, 0, ""))
3202 proto_tree_write_pdml(edt, stdout);
3204 return !ferror(stdout);
3206 proto_tree_write_fields(output_fields, edt, stdout);
3208 return !ferror(stdout);
3211 /* Just fill in the columns. */
3212 epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3214 /* Now print them. */
3215 switch (output_action) {
3218 if (!print_columns(cf))
3223 proto_tree_write_psml(edt, stdout);
3224 return !ferror(stdout);
3225 case WRITE_FIELDS: /*No non-verbose "fields" format */
3226 g_assert_not_reached();
3231 if (!print_hex_data(print_stream, edt))
3233 if (!print_line(print_stream, 0, ""))
3242 switch (output_action) {
3245 return print_finale(print_stream);
3249 write_pdml_finale(stdout);
3251 write_psml_finale(stdout);
3252 return !ferror(stdout);
3255 write_fields_finale(output_fields, stdout);
3256 return !ferror(stdout);
3259 g_assert_not_reached();
3265 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3269 char err_msg[2048+1];
3271 wth = wtap_open_offline(fname, err, &err_info, perform_two_pass_analysis);
3275 /* The open succeeded. Fill in the information for this file. */
3277 /* Cleanup all data structures used for dissection. */
3278 cleanup_dissection();
3279 /* Initialize all data structures used for dissection. */
3283 cf->f_datalen = 0; /* not used, but set it anyway */
3285 /* Set the file name because we need it to set the follow stream filter.
3286 XXX - is that still true? We need it for other reasons, though,
3288 cf->filename = g_strdup(fname);
3290 /* Indicate whether it's a permanent or temporary file. */
3291 cf->is_tempfile = is_tempfile;
3293 /* If it's a temporary capture buffer file, mark it as not saved. */
3294 cf->user_saved = !is_tempfile;
3296 cf->cd_t = wtap_file_type(cf->wth);
3298 cf->drops_known = FALSE;
3300 cf->snap = wtap_snapshot_length(cf->wth);
3301 if (cf->snap == 0) {
3302 /* Snapshot length not known. */
3303 cf->has_snap = FALSE;
3304 cf->snap = WTAP_MAX_PACKET_SIZE;
3306 cf->has_snap = TRUE;
3307 nstime_set_zero(&cf->elapsed_time);
3308 nstime_set_unset(&first_ts);
3309 nstime_set_unset(&prev_dis_ts);
3310 nstime_set_unset(&prev_cap_ts);
3312 cf->state = FILE_READ_IN_PROGRESS;
3317 g_snprintf(err_msg, sizeof err_msg,
3318 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3319 cmdarg_err("%s", err_msg);
3324 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3326 char *save_file_string;
3328 save_file_string = output_file_description(fname);
3333 cmdarg_err("Not all the packets could be written to the %s because there is "
3334 "no space left on the file system.",
3340 cmdarg_err("Not all the packets could be written to the %s because you are "
3341 "too close to, or over your disk quota.",
3346 case WTAP_ERR_CANT_CLOSE:
3347 cmdarg_err("The %s couldn't be closed for some unknown reason.",
3351 case WTAP_ERR_SHORT_WRITE:
3352 cmdarg_err("Not all the packets could be written to the %s.",
3358 cmdarg_err("The %s could not be closed: %s.", save_file_string,
3359 wtap_strerror(err));
3361 cmdarg_err("An error occurred while writing to the %s: %s.",
3362 save_file_string, wtap_strerror(err));
3366 g_free(save_file_string);
3370 show_print_file_io_error(int err)
3375 cmdarg_err("Not all the packets could be printed because there is "
3376 "no space left on the file system.");
3381 cmdarg_err("Not all the packets could be printed because you are "
3382 "too close to, or over your disk quota.");
3387 cmdarg_err("An error occurred while printing packets: %s.",
3394 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
3398 static char errmsg_errno[1024+1];
3401 /* Wiretap error. */
3404 case WTAP_ERR_NOT_REGULAR_FILE:
3405 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3408 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3409 /* Seen only when opening a capture file for reading. */
3410 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
3413 case WTAP_ERR_UNSUPPORTED:
3414 /* Seen only when opening a capture file for reading. */
3415 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3416 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
3419 errmsg = errmsg_errno;
3422 case WTAP_ERR_CANT_WRITE_TO_PIPE:
3423 /* Seen only when opening a capture file for writing. */
3424 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3425 "The file \"%%s\" is a pipe, and %s capture files can't be "
3426 "written to a pipe.", wtap_file_type_string(file_type));
3427 errmsg = errmsg_errno;
3430 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3431 /* Seen only when opening a capture file for writing. */
3432 errmsg = "TShark doesn't support writing capture files in that format.";
3435 case WTAP_ERR_UNSUPPORTED_ENCAP:
3437 errmsg = "TShark can't save this capture in that format.";
3439 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3440 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3443 errmsg = errmsg_errno;
3447 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3449 errmsg = "TShark can't save this capture in that format.";
3451 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3454 case WTAP_ERR_BAD_RECORD:
3455 /* Seen only when opening a capture file for reading. */
3456 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3457 "The file \"%%s\" appears to be damaged or corrupt.\n"
3460 errmsg = errmsg_errno;
3463 case WTAP_ERR_CANT_OPEN:
3465 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3467 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3470 case WTAP_ERR_SHORT_READ:
3471 errmsg = "The file \"%s\" appears to have been cut short"
3472 " in the middle of a packet or other data.";
3475 case WTAP_ERR_SHORT_WRITE:
3476 errmsg = "A full header couldn't be written to the file \"%s\".";
3480 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3481 "The file \"%%s\" could not be %s: %s.",
3482 for_writing ? "created" : "opened",
3483 wtap_strerror(err));
3484 errmsg = errmsg_errno;
3488 errmsg = file_open_error_message(err, for_writing);
3493 * Open/create errors are reported with an console message in TShark.
3496 open_failure_message(const char *filename, int err, gboolean for_writing)
3498 fprintf(stderr, "tshark: ");
3499 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3500 fprintf(stderr, "\n");
3505 * General errors are reported with an console message in TShark.
3508 failure_message(const char *msg_format, va_list ap)
3510 fprintf(stderr, "tshark: ");
3511 vfprintf(stderr, msg_format, ap);
3512 fprintf(stderr, "\n");
3516 * Read errors are reported with an console message in TShark.
3519 read_failure_message(const char *filename, int err)
3521 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3522 filename, strerror(err));
3526 * Write errors are reported with an console message in TShark.
3529 write_failure_message(const char *filename, int err)
3531 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3532 filename, strerror(err));
3536 * Print to the standard error. This is a command-line tool, so there's
3537 * no need to pop up a console.
3540 vfprintf_stderr(const char *fmt, va_list ap)
3542 vfprintf(stderr, fmt, ap);
3546 fprintf_stderr(const char *fmt, ...)
3551 vfprintf_stderr(fmt, ap);
3556 * Report an error in command-line arguments.
3559 cmdarg_err(const char *fmt, ...)
3564 failure_message(fmt, ap);
3569 * Report additional information for an error in command-line arguments.
3572 cmdarg_err_cont(const char *fmt, ...)
3577 vfprintf(stderr, fmt, ap);
3578 fprintf(stderr, "\n");