5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * Text-mode variant, by Gilbert Ramirez <gram@alumni.rice.edu>
10 * and Guy Harris <guy@alum.mit.edu>.
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
63 #include <epan/epan.h>
64 #include <epan/filesystem.h>
65 #include <epan/privileges.h>
66 #include <wiretap/file_util.h>
69 #include <epan/timestamp.h>
70 #include <epan/packet.h>
72 #include "disabled_protos.h"
73 #include <epan/prefs.h>
74 #include <epan/column.h>
76 #include <epan/addr_resolv.h>
78 #include "clopts_common.h"
79 #include "cmdarg_err.h"
80 #include "version_info.h"
81 #include <epan/conversation.h>
82 #include <epan/plugins.h>
84 #include <epan/epan_dissect.h>
86 #include <epan/stat_cmd_args.h>
87 #include <epan/timestamp.h>
88 #include <epan/ex-opt.h>
91 #include "capture_ui_utils.h"
93 #include "capture-pcap-util.h"
95 #include "capture-wpcap.h"
96 #include "capture_errs.h"
98 #include "capture_sync.h"
99 #endif /* HAVE_LIBPCAP */
100 #include "epan/emem.h"
102 #include <epan/funnel.h>
106 * This is the template for the decode as option; it is shared between the
107 * various functions that output the usage for this parameter.
109 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
111 static nstime_t first_ts;
112 static nstime_t prev_dis_ts;
113 static nstime_t prev_cap_ts;
114 static GString *comp_info_str, *runtime_info_str;
116 static gboolean print_packet_info; /* TRUE if we're to print packet information */
118 * The way the packet decode is to be written.
121 WRITE_TEXT, /* summary or detail text */
122 WRITE_XML, /* PDML or PSML */
123 WRITE_FIELDS /* User defined list of fields */
124 /* Add CSV and the like here */
126 static output_action_e output_action;
127 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
128 static gboolean verbose;
129 static gboolean print_hex;
130 static gboolean line_buffered;
131 static guint32 cum_bytes = 0;
132 static print_format_e print_format = PR_FMT_TEXT;
133 static print_stream_t *print_stream;
135 static output_fields_t* output_fields = NULL;
138 * Standard secondary message for unexpected errors.
140 static const char please_report[] =
141 "Please report this to the Wireshark developers";
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 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 int 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,
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);
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");
228 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
230 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
231 fprintf(output, " -D print list of interfaces and exit\n");
232 fprintf(output, " -L print list of link-layer types of iface and exit\n");
233 fprintf(output, "\n");
234 fprintf(output, "Capture stop conditions:\n");
235 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
236 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
237 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
238 fprintf(output, " files:NUM - stop after NUM files\n");
239 /*fprintf(output, "\n");*/
240 fprintf(output, "Capture output:\n");
241 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
242 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
243 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
244 #endif /* HAVE_LIBPCAP */
246 /*fprintf(output, "\n");*/
247 fprintf(output, "Input file:\n");
248 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
250 fprintf(output, "\n");
251 fprintf(output, "Processing:\n");
252 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
253 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
254 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
255 fprintf(output, " -d %s ...\n", decode_as_arg_template);
256 fprintf(output, " \"Decode As\", see the man page for details\n");
257 fprintf(output, " Example: tcp.port==8888,http\n");
259 /*fprintf(output, "\n");*/
260 fprintf(output, "Output:\n");
261 fprintf(output, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
262 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
263 fprintf(output, " an empty \"-F\" option will list the file types\n");
264 fprintf(output, " -V add output of packet tree (Packet Details)\n");
265 fprintf(output, " -S display packets even when writing to a file\n");
266 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
267 fprintf(output, " -T pdml|ps|psml|text|fields\n");
268 fprintf(output, " format of text output (def: text)\n");
269 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
270 fprintf(output, " this option can be repeated to print multiple fields\n");
271 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
272 fprintf(output, " header=y|n switch headers on and off\n");
273 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
274 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
275 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
276 fprintf(output, " -l flush standard output after each packet\n");
277 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
278 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
279 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
281 fprintf(output, "\n");
282 fprintf(output, "Miscellaneous:\n");
283 fprintf(output, " -h display this help and exit\n");
284 fprintf(output, " -v display version info and exit\n");
285 fprintf(output, " -o <name>:<value> ... override preference setting\n");
289 * For a dissector table, print on the stream described by output,
290 * its short name (which is what's used in the "-d" option) and its
294 display_dissector_table_names(const char *table_name, const char *ui_name,
297 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
301 * For a dissector handle, print on the stream described by output,
302 * the filter name (which is what's used in the "-d" option) and the full
303 * name for the protocol that corresponds to this handle.
306 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
309 const gchar* proto_filter_name;
310 const gchar* proto_ui_name;
312 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
314 if (proto_id != -1) {
315 proto_filter_name = proto_get_protocol_filter_name(proto_id);
316 proto_ui_name = proto_get_protocol_name(proto_id);
317 g_assert(proto_filter_name != NULL);
318 g_assert(proto_ui_name != NULL);
320 fprintf((FILE *)output, "\t%s (%s)\n",
327 * The protocol_name_search structure is used by find_protocol_name_func()
328 * to pass parameters and store results
330 struct protocol_name_search{
331 gchar *searched_name; /* Protocol filter name we are looking for */
332 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
333 guint nb_match; /* How many dissectors matched searched_name */
335 typedef struct protocol_name_search *protocol_name_search_t;
338 * This function parses all dissectors associated with a table to find the
339 * one whose protocol has the specified filter name. It is called
340 * as a reference function in a call to dissector_table_foreach_handle.
341 * The name we are looking for, as well as the results, are stored in the
342 * protocol_name_search struct pointed to by user_data.
343 * If called using dissector_table_foreach_handle, we actually parse the
344 * whole list of dissectors.
347 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
351 const gchar *protocol_filter_name;
352 protocol_name_search_t search_info;
356 search_info = (protocol_name_search_t)user_data;
358 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
359 if (proto_id != -1) {
360 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
361 g_assert(protocol_filter_name != NULL);
362 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
364 if (search_info->nb_match == 0) {
365 /* Record this handle only if this is the first match */
366 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
368 search_info->nb_match++;
374 * Print all layer type names supported.
375 * We send the output to the stream described by the handle output.
379 fprint_all_layer_types(FILE *output)
382 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
386 * Print all protocol names supported for a specific layer type.
387 * table_name contains the layer type name in which the search is performed.
388 * We send the output to the stream described by the handle output.
392 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
395 dissector_table_foreach_handle(table_name,
396 display_dissector_names,
401 * The function below parses the command-line parameters for the decode as
402 * feature (a string pointer by cl_param).
403 * It checks the format of the command-line, searches for a matching table
404 * and dissector. If a table/dissector match is not found, we display a
405 * summary of the available tables/dissectors (on stderr) and return FALSE.
406 * If everything is fine, we get the "Decode as" preference activated,
407 * then we return TRUE.
410 add_decode_as(const gchar *cl_param)
414 gchar *decoded_param;
415 gchar *remaining_param;
417 gchar *dissector_str;
418 dissector_handle_t dissector_matching;
419 dissector_table_t table_matching;
420 ftenum_t dissector_table_selector_type;
421 struct protocol_name_search user_protocol_name;
423 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
426 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
427 g_assert(decoded_param);
428 strcpy(decoded_param, cl_param);
431 /* The lines below will parse this string (modifying it) to extract all
432 necessary information. Note that decoded_param is still needed since
433 strings are not copied - we just save pointers. */
435 /* This section extracts a layer type (table_name) from decoded_param */
436 table_name = decoded_param; /* Layer type string starts from beginning */
438 remaining_param = strchr(table_name, '=');
439 if (remaining_param == NULL) {
440 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
441 /* If the argument does not follow the template, carry on anyway to check
442 if the table name is at least correct. If remaining_param is NULL,
443 we'll exit anyway further down */
446 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
449 /* Remove leading and trailing spaces from the table name */
450 while ( table_name[0] == ' ' )
452 while ( table_name[strlen(table_name) - 1] == ' ' )
453 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
455 /* The following part searches a table matching with the layer type specified */
456 table_matching = NULL;
458 /* Look for the requested table */
459 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
460 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
463 table_matching = find_dissector_table(table_name);
464 if (!table_matching) {
465 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
469 if (!table_matching) {
470 /* Display a list of supported layer types to help the user, if the
471 specified layer type was not found */
472 cmdarg_err("Valid layer types are:");
473 fprint_all_layer_types(stderr);
475 if (remaining_param == NULL || !table_matching) {
476 /* Exit if the layer type was not found, or if no '=' separator was found
478 g_free(decoded_param);
482 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
483 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
486 remaining_param++; /* Move to the second '=' */
487 *remaining_param = '\0'; /* Remove the second '=' */
489 remaining_param++; /* Position after the layer type string */
491 /* This section extracts a selector value (selector_str) from decoded_param */
493 selector_str = remaining_param; /* Next part starts with the selector number */
495 remaining_param = strchr(selector_str, ',');
496 if (remaining_param == NULL) {
497 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
498 /* If the argument does not follow the template, carry on anyway to check
499 if the selector value is at least correct. If remaining_param is NULL,
500 we'll exit anyway further down */
503 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
506 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
508 switch (dissector_table_selector_type) {
514 /* The selector for this table is an unsigned number. Parse it as such.
515 There's no need to remove leading and trailing spaces from the
516 selector number string, because sscanf will do that for us. */
517 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
518 cmdarg_err("Invalid selector number \"%s\"", selector_str);
519 g_free(decoded_param);
527 /* The selector for this table is a string. */
531 /* There are currently no dissector tables with any types other
532 than the ones listed above. */
533 g_assert_not_reached();
536 if (remaining_param == NULL) {
537 /* Exit if no ',' separator was found (see above) */
538 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
539 fprint_all_protocols_for_layer_types(stderr, table_name);
540 g_free(decoded_param);
544 remaining_param++; /* Position after the selector number string */
546 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
548 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
550 /* Remove leading and trailing spaces from the dissector name */
551 while ( dissector_str[0] == ' ' )
553 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
554 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
556 dissector_matching = NULL;
558 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
559 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 */
560 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
563 user_protocol_name.nb_match = 0;
564 user_protocol_name.searched_name = dissector_str;
565 user_protocol_name.matched_handle = NULL;
567 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 */
569 if (user_protocol_name.nb_match != 0) {
570 dissector_matching = user_protocol_name.matched_handle;
571 if (user_protocol_name.nb_match > 1) {
572 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
576 /* OK, check whether the problem is that there isn't any such
577 protocol, or that there is but it's not specified as a protocol
578 that's valid for that dissector table.
579 Note, we don't exit here, but dissector_matching will remain NULL,
581 if (proto_get_id_by_filter_name(dissector_str) == -1) {
582 /* No such protocol */
583 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
585 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
586 dissector_str, table_name);
591 if (!dissector_matching) {
592 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
593 fprint_all_protocols_for_layer_types(stderr, table_name);
594 g_free(decoded_param);
598 /* This is the end of the code that parses the command-line options.
599 All information is now stored in the variables:
603 The above variables that are strings are still pointing to areas within
604 decoded_parm. decoded_parm thus still needs to be kept allocated in
605 until we stop needing these variables
606 decoded_param will be deallocated at each exit point of this function */
609 /* We now have a pointer to the handle for the requested dissector
610 (requested protocol) inside the variable dissector_matching */
611 switch (dissector_table_selector_type) {
617 /* The selector for this table is an unsigned number. */
618 dissector_change(table_name, selector, dissector_matching);
624 /* The selector for this table is a string. */
625 dissector_change_string(table_name, selector_str, dissector_matching);
629 /* There are currently no dissector tables with any types other
630 than the ones listed above. */
631 g_assert_not_reached();
633 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
638 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
639 const gchar *message _U_, gpointer user_data _U_)
644 output_file_description(const char *fname)
646 char *save_file_string;
648 /* Get a string that describes what we're writing to */
649 if (strcmp(fname, "-") == 0) {
650 /* We're writing to the standard output */
651 save_file_string = g_strdup("standard output");
653 /* We're writing to a file with the name in save_file */
654 save_file_string = g_strdup_printf("file \"%s\"", fname);
656 return save_file_string;
660 print_current_user(void) {
661 gchar *cur_user, *cur_group;
662 if (started_with_special_privs()) {
663 cur_user = get_cur_username();
664 cur_group = get_cur_groupname();
665 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
666 cur_user, cur_group);
669 if (running_with_special_privs()) {
670 fprintf(stderr, " This could be dangerous.");
672 fprintf(stderr, "\n");
677 check_capture_privs(void) {
680 /* Warn the user if npf.sys isn't loaded. */
681 if (!npf_sys_is_running() && get_os_major_version() >= 6) {
682 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
683 "capturing or\nlisting interfaces.\n");
691 main(int argc, char *argv[])
693 char *init_progfile_dir_error;
696 gboolean arg_error = FALSE;
702 char *gpf_path, *pf_path;
703 char *gdp_path, *dp_path;
704 int gpf_open_errno, gpf_read_errno;
705 int pf_open_errno, pf_read_errno;
706 int gdp_open_errno, gdp_read_errno;
707 int dp_open_errno, dp_read_errno;
710 gboolean list_link_layer_types = FALSE;
711 gboolean start_capture = FALSE;
714 gboolean capture_option_specified = FALSE;
716 gboolean quiet = FALSE;
717 int out_file_type = WTAP_FILE_PCAP;
718 gchar *cf_name = NULL, *rfilter = NULL;
719 #ifdef HAVE_PCAP_OPEN_DEAD
720 struct bpf_program fcode;
722 dfilter_t *rfcode = NULL;
725 GLogLevelFlags log_flags;
728 #define OPTSTRING_INIT "a:b:c:d:De:E:f:F:G:hi:lLnN:o:pqr:R:s:St:T:vVw:xX:y:z:"
731 #define OPTSTRING_WIN32 "B:"
733 #define OPTSTRING_WIN32 ""
736 #define OPTSTRING_WIN32 ""
737 #endif /* HAVE_LIBPCAP */
739 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
742 * Get credential information for later use.
744 get_credential_info();
747 * Attempt to get the pathname of the executable file.
749 init_progfile_dir_error = init_progfile_dir(argv[0]);
750 if (init_progfile_dir_error != NULL) {
751 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
752 init_progfile_dir_error);
756 * In order to have the -X opts assigned before the wslua machine starts
757 * we need to call getopts before epan_init() gets called.
760 optind_initial = optind;
762 while ((opt = getopt(argc, argv, optstring)) != -1) {
772 optind = optind_initial;
775 /* nothing more than the standard GLib handler, but without a warning */
782 g_log_set_handler(NULL,
784 log_func_ignore, NULL /* user_data */);
785 g_log_set_handler(LOG_DOMAIN_CAPTURE,
787 log_func_ignore, NULL /* user_data */);
789 initialize_funnel_ops();
792 capture_opts_init(&capture_opts, NULL /* cfile */);
795 timestamp_set_type(TS_RELATIVE);
796 timestamp_set_precision(TS_PREC_AUTO);
798 /* Register all dissectors; we must do this before checking for the
799 "-G" flag, as the "-G" flag dumps information registered by the
800 dissectors, and we must do it before we read the preferences, in
801 case any dissectors register preferences. */
802 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
803 failure_message, open_failure_message, read_failure_message);
805 /* Register all tap listeners; we do this before we parse the arguments,
806 as the "-z" argument can specify a registered tap. */
808 /* we register the plugin taps before the other taps because
809 stats_tree taps plugins will be registered as tap listeners
810 by stats_tree_stat.c and need to registered before that */
812 register_all_plugin_tap_listeners();
814 register_all_tap_listeners();
816 /* Now register the preferences for any non-dissector modules.
817 We must do that before we read the preferences as well. */
818 prefs_register_modules();
820 /* If invoked with the "-G" flag, we dump out information based on
821 the argument to the "-G" flag; if no argument is specified,
822 for backwards compatibility we dump out a glossary of display
825 XXX - we do this here, for now, to support "-G" with no arguments.
826 If none of our build or other processes uses "-G" with no arguments,
827 we can just process it with the other arguments. */
828 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
830 proto_registrar_dump_fields(1);
832 if (strcmp(argv[2], "fields") == 0)
833 proto_registrar_dump_fields(1);
834 else if (strcmp(argv[2], "fields2") == 0)
835 proto_registrar_dump_fields(2);
836 else if (strcmp(argv[2], "fields3") == 0)
837 proto_registrar_dump_fields(3);
838 else if (strcmp(argv[2], "protocols") == 0)
839 proto_registrar_dump_protocols();
840 else if (strcmp(argv[2], "values") == 0)
841 proto_registrar_dump_values();
842 else if (strcmp(argv[2], "decodes") == 0)
843 dissector_dump_decodes();
844 else if (strcmp(argv[2], "defaultprefs") == 0)
846 else if (strcmp(argv[2], "currentprefs") == 0) {
847 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
848 &pf_open_errno, &pf_read_errno, &pf_path);
851 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
858 /* Set the C-language locale to the native environment. */
859 setlocale(LC_ALL, "");
861 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
862 &pf_open_errno, &pf_read_errno, &pf_path);
863 if (gpf_path != NULL) {
864 if (gpf_open_errno != 0) {
865 cmdarg_err("Can't open global preferences file \"%s\": %s.",
866 pf_path, strerror(gpf_open_errno));
868 if (gpf_read_errno != 0) {
869 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
870 pf_path, strerror(gpf_read_errno));
873 if (pf_path != NULL) {
874 if (pf_open_errno != 0) {
875 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
876 strerror(pf_open_errno));
878 if (pf_read_errno != 0) {
879 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
880 pf_path, strerror(pf_read_errno));
886 /* Set the name resolution code's flags from the preferences. */
887 g_resolv_flags = prefs->name_resolve;
889 /* Read the disabled protocols file. */
890 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
891 &dp_path, &dp_open_errno, &dp_read_errno);
892 if (gdp_path != NULL) {
893 if (gdp_open_errno != 0) {
894 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
895 gdp_path, strerror(gdp_open_errno));
897 if (gdp_read_errno != 0) {
898 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
899 gdp_path, strerror(gdp_read_errno));
903 if (dp_path != NULL) {
904 if (dp_open_errno != 0) {
906 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
907 strerror(dp_open_errno));
909 if (dp_read_errno != 0) {
911 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
912 strerror(dp_read_errno));
917 check_capture_privs();
919 init_cap_file(&cfile);
921 /* Assemble the compile-time version information string */
922 comp_info_str = g_string_new("Compiled ");
923 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
925 /* Assemble the run-time version information string */
926 runtime_info_str = g_string_new("Running ");
927 get_runtime_version_info(runtime_info_str, NULL);
929 /* Print format defaults to this. */
930 print_format = PR_FMT_TEXT;
932 output_fields = output_fields_new();
934 /* Now get our args */
935 while ((opt = getopt(argc, argv, optstring)) != -1) {
937 case 'a': /* autostop criteria */
938 case 'b': /* Ringbuffer option */
939 case 'c': /* Capture x packets */
940 case 'f': /* capture filter */
941 case 'i': /* Use interface x */
942 case 'p': /* Don't capture in promiscuous mode */
943 case 's': /* Set the snapshot (capture) length */
944 case 'w': /* Write to capture file x */
945 case 'y': /* Set the pcap data link type */
947 case 'B': /* Buffer size */
950 status = capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
955 capture_option_specified = TRUE;
959 case 'd': /* Decode as rule */
960 if (!add_decode_as(optarg))
963 case 'D': /* Print a list of capture devices and exit */
965 status = capture_opts_list_interfaces(FALSE);
968 capture_option_specified = TRUE;
974 output_fields_add(output_fields, optarg);
978 if(!output_fields_set_option(output_fields, optarg)) {
979 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
980 output_fields_list_options(stderr);
985 out_file_type = wtap_short_string_to_file_type(optarg);
986 if (out_file_type < 0) {
987 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
988 list_capture_types();
992 case 'h': /* Print help and exit */
996 case 'l': /* "Line-buffer" standard output */
997 /* This isn't line-buffering, strictly speaking, it's just
998 flushing the standard output after the information for
999 each packet is printed; however, that should be good
1000 enough for all the purposes to which "-l" is put (and
1001 is probably actually better for "-V", as it does fewer
1004 See the comment in "process_packet()" for an explanation of
1005 why we do that, and why we don't just use "setvbuf()" to
1006 make the standard output line-buffered (short version: in
1007 Windows, "line-buffered" is the same as "fully-buffered",
1008 and the output buffer is only flushed when it fills up). */
1009 line_buffered = TRUE;
1011 case 'L': /* Print list of link-layer types and exit */
1013 list_link_layer_types = TRUE;
1016 capture_option_specified = TRUE;
1020 case 'n': /* No name resolution */
1021 g_resolv_flags = RESOLV_NONE;
1023 case 'N': /* Select what types of addresses/port #s to resolve */
1024 if (g_resolv_flags == RESOLV_ALL)
1025 g_resolv_flags = RESOLV_NONE;
1026 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1027 if (badopt != '\0') {
1028 cmdarg_err("-N specifies unknown resolving option '%c';",
1030 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1034 case 'o': /* Override preference from command line */
1035 switch (prefs_set_pref(optarg)) {
1040 case PREFS_SET_SYNTAX_ERR:
1041 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1045 case PREFS_SET_NO_SUCH_PREF:
1046 case PREFS_SET_OBSOLETE:
1047 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1052 case 'q': /* Quiet */
1055 case 'r': /* Read capture file x */
1056 cf_name = g_strdup(optarg);
1058 case 'R': /* Read file filter */
1061 case 'S': /* show packets in real time */
1062 print_packet_info = TRUE;
1064 case 't': /* Time stamp type */
1065 if (strcmp(optarg, "r") == 0)
1066 timestamp_set_type(TS_RELATIVE);
1067 else if (strcmp(optarg, "a") == 0)
1068 timestamp_set_type(TS_ABSOLUTE);
1069 else if (strcmp(optarg, "ad") == 0)
1070 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1071 else if (strcmp(optarg, "d") == 0)
1072 timestamp_set_type(TS_DELTA);
1073 else if (strcmp(optarg, "dd") == 0)
1074 timestamp_set_type(TS_DELTA_DIS);
1075 else if (strcmp(optarg, "e") == 0)
1076 timestamp_set_type(TS_EPOCH);
1078 cmdarg_err("Invalid time stamp type \"%s\"",
1080 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1081 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1085 case 'T': /* printing Type */
1086 if (strcmp(optarg, "text") == 0) {
1087 output_action = WRITE_TEXT;
1088 print_format = PR_FMT_TEXT;
1089 } else if (strcmp(optarg, "ps") == 0) {
1090 output_action = WRITE_TEXT;
1091 print_format = PR_FMT_PS;
1092 } else if (strcmp(optarg, "pdml") == 0) {
1093 output_action = WRITE_XML;
1095 } else if (strcmp(optarg, "psml") == 0) {
1096 output_action = WRITE_XML;
1098 } else if(strcmp(optarg, "fields") == 0) {
1099 output_action = WRITE_FIELDS;
1100 verbose = TRUE; /* Need full tree info */
1102 cmdarg_err("Invalid -T parameter.");
1103 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1107 case 'v': /* Show version and exit */
1108 printf("TShark " VERSION "%s\n"
1115 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
1116 runtime_info_str->str);
1119 case 'V': /* Verbose */
1122 case 'x': /* Print packet data in hex (and ASCII) */
1128 /* We won't call the init function for the stat this soon
1129 as it would disallow MATE's fields (which are registered
1130 by the preferences set callback) from being used as
1131 part of a tap filter. Instead, we just add the argument
1132 to a list of stat arguments. */
1133 if (!process_stat_cmd_arg(optarg)) {
1134 cmdarg_err("invalid -z argument.");
1135 cmdarg_err_cont(" -z argument must be one of :");
1136 list_stat_cmd_args();
1141 case '?': /* Bad flag - print usage message */
1144 list_capture_types();
1154 /* If we specified output fields, but not the output field type... */
1155 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1156 cmdarg_err("Output fields were specified with \"-e\", "
1157 "but \"-Tfields\" was not specified.");
1159 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1160 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1161 "specified with \"-e\".");
1166 /* If no capture filter or read filter has been specified, and there are
1167 still command-line arguments, treat them as the tokens of a capture
1168 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1169 flag was specified. */
1170 if (optind < argc) {
1171 if (cf_name != NULL) {
1172 if (rfilter != NULL) {
1173 cmdarg_err("Read filters were specified both with \"-R\" "
1174 "and with additional command-line arguments");
1177 rfilter = get_args_as_string(argc, argv, optind);
1180 if (capture_opts.has_cfilter) {
1181 cmdarg_err("Capture filters were specified both with \"-f\""
1182 " and with additional command-line arguments");
1185 capture_opts.has_cfilter = TRUE;
1186 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1188 capture_option_specified = TRUE;
1194 if (!capture_opts.saving_to_file) {
1195 /* We're not saving the capture to a file; if "-q" wasn't specified,
1196 we should print packet information */
1198 print_packet_info = TRUE;
1200 /* We're saving to a file; if we're writing to the standard output.
1201 and we'll also be writing dissected packets to the standard
1202 output, reject the request. At best, we could redirect that
1203 to the standard error; we *can't* write both to the standard
1204 output and have either of them be useful. */
1205 if (strcmp(capture_opts.save_file, "-") == 0 && print_packet_info) {
1206 cmdarg_err("You can't write both raw packet data and dissected packets"
1207 " to the standard output.");
1212 /* We're not saving the capture to a file; if "-q" wasn't specified,
1213 we should print packet information */
1215 print_packet_info = TRUE;
1218 #ifndef HAVE_LIBPCAP
1219 if (capture_option_specified)
1220 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1227 /* We don't support capture filters when reading from a capture file
1228 (the BPF compiler doesn't support all link-layer types that we
1229 support in capture files we read). */
1231 if (cf_name != NULL) {
1232 if (capture_opts.has_cfilter) {
1233 cmdarg_err("Only read filters, not capture filters, "
1234 "can be specified when reading a capture file.");
1241 if (output_action != WRITE_TEXT) {
1242 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1248 if (list_link_layer_types) {
1249 /* We're supposed to list the link-layer types for an interface;
1250 did the user also specify a capture file to be read? */
1252 /* Yes - that's bogus. */
1253 cmdarg_err("You can't specify -L and a capture file to be read.");
1256 /* No - did they specify a ring buffer option? */
1257 if (capture_opts.multi_files_on) {
1258 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1264 * "-r" was specified, so we're reading a capture file.
1265 * Capture options don't apply here.
1267 if (capture_opts.multi_files_on) {
1268 cmdarg_err("Multiple capture files requested, but "
1269 "a capture isn't being done.");
1272 if (capture_opts.has_file_duration) {
1273 cmdarg_err("Switching capture files after a time interval was specified, but "
1274 "a capture isn't being done.");
1277 if (capture_opts.has_ring_num_files) {
1278 cmdarg_err("A ring buffer of capture files was specified, but "
1279 "a capture isn't being done.");
1282 if (capture_opts.has_autostop_files) {
1283 cmdarg_err("A maximum number of capture files was specified, but "
1284 "a capture isn't being done.");
1288 /* Note: TShark now allows the restriction of a _read_ file by packet count
1289 * and byte count as well as a write file. Other autostop options remain valid
1290 * only for a write file.
1292 if (capture_opts.has_autostop_duration) {
1293 cmdarg_err("A maximum capture time was specified, but "
1294 "a capture isn't being done.");
1299 * "-r" wasn't specified, so we're doing a live capture.
1301 if (capture_opts.saving_to_file) {
1302 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1304 /* When capturing, we only support writing libpcap format. */
1305 if (out_file_type != WTAP_FILE_PCAP) {
1306 cmdarg_err("Live captures can only be saved in libpcap format.");
1309 if (capture_opts.multi_files_on) {
1310 /* Multiple-file mode doesn't work under certain conditions:
1311 a) it doesn't work if you're writing to the standard output;
1312 b) it doesn't work if you're writing to a pipe;
1314 if (strcmp(capture_opts.save_file, "-") == 0) {
1315 cmdarg_err("Multiple capture files requested, but "
1316 "the capture is being written to the standard output.");
1319 if (capture_opts.output_to_pipe) {
1320 cmdarg_err("Multiple capture files requested, but "
1321 "the capture file is a pipe.");
1324 if (!capture_opts.has_autostop_filesize &&
1325 !capture_opts.has_file_duration) {
1326 cmdarg_err("Multiple capture files requested, but "
1327 "no maximum capture file size or duration was specified.");
1332 /* They didn't specify a "-w" flag, so we won't be saving to a
1333 capture file. Check for options that only make sense if
1334 we're saving to a file. */
1335 if (capture_opts.has_autostop_filesize) {
1336 cmdarg_err("Maximum capture file size specified, but "
1337 "capture isn't being saved to a file.");
1340 if (capture_opts.multi_files_on) {
1341 cmdarg_err("Multiple capture files requested, but "
1342 "the capture isn't being saved to a file.");
1351 /* Start windows sockets */
1352 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1355 /* Notify all registered modules that have had any of their preferences
1356 changed either from one of the preferences file or from the command
1357 line that their preferences have changed. */
1360 /* At this point MATE will have registered its field array so we can
1361 have a tap filter with one of MATE's late-registered fields as part
1362 of the filter. We can now process all the "-z" arguments. */
1363 start_requested_stats();
1365 /* disabled protocols as per configuration file */
1366 if (gdp_path == NULL && dp_path == NULL) {
1367 set_disabled_protos_list();
1370 /* Build the column format array */
1371 col_setup(&cfile.cinfo, prefs->num_cols);
1372 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1373 cfile.cinfo.col_fmt[i] = get_column_format(i);
1374 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1375 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1377 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1378 cfile.cinfo.col_data[i] = NULL;
1379 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1380 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1382 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1383 cfile.cinfo.col_fence[i] = 0;
1384 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1385 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1388 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1391 for (j = 0; j < NUM_COL_FMTS; j++) {
1392 if (!cfile.cinfo.fmt_matx[i][j])
1395 if (cfile.cinfo.col_first[j] == -1)
1396 cfile.cinfo.col_first[j] = i;
1397 cfile.cinfo.col_last[j] = i;
1402 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1403 capture_opts_trim_ring_num_files(&capture_opts);
1406 if (rfilter != NULL) {
1407 if (!dfilter_compile(rfilter, &rfcode)) {
1408 cmdarg_err("%s", dfilter_error_msg);
1410 #ifdef HAVE_PCAP_OPEN_DEAD
1414 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1416 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1418 " Note: That display filter code looks like a valid capture filter;");
1420 " maybe you mixed them up?");
1429 cfile.rfcode = rfcode;
1431 if (print_packet_info) {
1432 /* If we're printing as text or PostScript, we have
1433 to create a print stream. */
1434 if (output_action == WRITE_TEXT) {
1435 switch (print_format) {
1438 print_stream = print_stream_text_stdio_new(stdout);
1442 print_stream = print_stream_ps_stdio_new(stdout);
1446 g_assert_not_reached();
1451 /* We have to dissect each packet if:
1453 we're printing information about each packet;
1455 we're using a read filter on the packets;
1457 we're using any taps. */
1458 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1462 * We're reading a capture file.
1466 * Immediately relinquish any special privileges we have; we must not
1467 * be allowed to read any capture files the user running TShark
1470 relinquish_special_privs_perm();
1471 print_current_user();
1473 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1478 /* Set timestamp precision; there should arguably be a command-line
1479 option to let the user set this. */
1480 switch(wtap_file_tsprecision(cfile.wth)) {
1481 case(WTAP_FILE_TSPREC_SEC):
1482 timestamp_set_precision(TS_PREC_AUTO_SEC);
1484 case(WTAP_FILE_TSPREC_DSEC):
1485 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1487 case(WTAP_FILE_TSPREC_CSEC):
1488 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1490 case(WTAP_FILE_TSPREC_MSEC):
1491 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1493 case(WTAP_FILE_TSPREC_USEC):
1494 timestamp_set_precision(TS_PREC_AUTO_USEC);
1496 case(WTAP_FILE_TSPREC_NSEC):
1497 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1500 g_assert_not_reached();
1503 /* Process the packets in the file */
1505 err = load_cap_file(&cfile, capture_opts.save_file, out_file_type,
1506 capture_opts.has_autostop_packets ? capture_opts.autostop_packets : 0,
1507 capture_opts.has_autostop_filesize ? capture_opts.autostop_filesize : 0);
1509 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1517 /* No capture file specified, so we're supposed to do a live capture
1518 (or get a list of link-layer types for a live capture device);
1519 do we have support for live captures? */
1526 cmdarg_err("WinPcap couldn't be found.");
1527 detailed_err = cant_load_winpcap_err("TShark");
1528 cmdarg_err_cont("%s", detailed_err);
1529 g_free(detailed_err);
1534 /* trim the interface name and exit if that failed */
1535 if (!capture_opts_trim_iface(&capture_opts,
1536 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1540 /* if requested, list the link layer types and exit */
1541 if (list_link_layer_types) {
1542 status = capture_opts_list_link_layer_types(&capture_opts, FALSE);
1546 if (print_packet_info) {
1547 if (!write_preamble(NULL)) {
1549 show_print_file_io_error(err);
1552 } else if (!quiet) {
1554 * We're not printing information for each packet, and the user
1555 * didn't ask us not to print a count of packets as they arrive,
1556 * so print that count so the user knows that packets are arriving.
1558 * XXX - what if the user wants to do a live capture, doesn't want
1559 * to save it to a file, doesn't want information printed for each
1560 * packet, does want some "-z" statistic, and wants packet counts
1561 * so they know whether they're seeing any packets?
1563 print_packet_counts = TRUE;
1566 /* For now, assume libpcap gives microsecond precision. */
1567 timestamp_set_precision(TS_PREC_AUTO_USEC);
1571 if (print_packet_info) {
1572 if (!write_finale()) {
1574 show_print_file_io_error(err);
1578 /* No - complain. */
1579 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1584 draw_tap_listeners(TRUE);
1585 funnel_dump_all_text_windows();
1588 output_fields_free(output_fields);
1589 output_fields = NULL;
1594 /*#define USE_BROKEN_G_MAIN_LOOP*/
1596 #ifdef USE_BROKEN_G_MAIN_LOOP
1599 gboolean loop_running = FALSE;
1601 guint32 packet_count = 0;
1604 /* XXX - move to the right position / file */
1605 /* read from a pipe (callback) */
1606 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1608 typedef struct pipe_input_tag {
1612 pipe_input_cb_t input_cb;
1613 guint pipe_input_id;
1615 GStaticMutex callback_running;
1619 static pipe_input_t pipe_input;
1622 /* The timer has expired, see if there's stuff to read from the pipe,
1623 if so, do the callback */
1625 pipe_timer_cb(gpointer data)
1629 gboolean result, result1;
1631 pipe_input_t *pipe_input = data;
1632 gint iterations = 0;
1635 g_static_mutex_lock (&pipe_input->callback_running);
1637 /* try to read data from the pipe only 5 times, to avoid blocking */
1638 while(iterations < 5) {
1639 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1641 /* Oddly enough although Named pipes don't work on win9x,
1642 PeekNamedPipe does !!! */
1643 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1644 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1646 /* Get the child process exit status */
1647 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1650 /* If the Peek returned an error, or there are bytes to be read
1651 or the childwatcher thread has terminated then call the normal
1653 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1655 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1657 /* And call the real handler */
1658 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1659 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1660 /* pipe closed, return false so that the timer is stopped */
1661 g_static_mutex_unlock (&pipe_input->callback_running);
1666 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1667 /* No data, stop now */
1674 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1676 g_static_mutex_unlock (&pipe_input->callback_running);
1678 /* we didn't stopped the timer, so let it run */
1685 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1688 pipe_input.source = source;
1689 pipe_input.child_process = child_process;
1690 pipe_input.user_data = user_data;
1691 pipe_input.input_cb = input_cb;
1694 g_static_mutex_init(&pipe_input.callback_running);
1695 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1696 do this but that doesn't cover all win32 platforms. GTK can do
1697 this but doesn't seem to work over processes. Attempt to do
1698 something similar here, start a timer and check for data on every
1700 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1701 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1711 #ifdef USE_TSHARK_SELECT
1715 struct sigaction action, oldaction;
1719 * XXX - dropping privileges is still required, until code cleanup is done
1721 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1722 * when it's done, we don't need special privileges to run tshark at all,
1723 * therefore we don't need to drop these privileges
1724 * The only thing we might want to keep is a warning if tshark is run as root,
1725 * as it's no longer necessary and potentially dangerous.
1727 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1728 * We've opened the capture device, so we shouldn't need any special
1729 * privileges any more; relinquish those privileges.
1731 * XXX - if we have saved set-user-ID support, we should give up those
1732 * privileges immediately, and then reclaim them long enough to get
1733 * a list of network interfaces and to open one, and then give them
1734 * up again, so that stuff we do while processing the argument list,
1735 * reading the user's preferences, loading and starting plugins
1736 * (especially *user* plugins), etc. is done with the user's privileges,
1737 * not special privileges.
1739 relinquish_special_privs_perm();
1740 print_current_user();
1742 /* Initialize all data structures used for dissection. */
1746 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1747 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1749 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1751 action.sa_handler = capture_cleanup;
1752 action.sa_flags = 0;
1753 sigemptyset(&action.sa_mask);
1754 sigaction(SIGTERM, &action, NULL);
1755 sigaction(SIGINT, &action, NULL);
1756 sigaction(SIGHUP, NULL, &oldaction);
1757 if (oldaction.sa_handler == SIG_DFL)
1758 sigaction(SIGHUP, &action, NULL);
1761 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1762 quiet mode, report the number of packets we've captured. */
1763 action.sa_handler = report_counts_siginfo;
1764 action.sa_flags = 0;
1765 sigemptyset(&action.sa_mask);
1766 sigaction(SIGINFO, &action, NULL);
1767 #endif /* SIGINFO */
1770 capture_opts.state = CAPTURE_PREPARING;
1772 /* Let the user know what interface was chosen. */
1773 capture_opts.iface_descr = get_interface_descriptive_name(capture_opts.iface);
1774 fprintf(stderr, "Capturing on %s\n", capture_opts.iface_descr);
1776 ret = sync_pipe_start(&capture_opts);
1781 /* the actual capture loop
1783 * XXX - glib doesn't seem to provide any event based loop handling.
1785 * XXX - for whatever reason,
1786 * calling g_main_loop_new() ends up in 100% cpu load.
1788 * But that doesn't matter: in UNIX we can use select() to find an input
1789 * source with something to do.
1791 * But that doesn't matter because we're in a CLI (that doesn't need to
1792 * update a GUI or something at the same time) so it's OK if we block
1793 * trying to read from the pipe.
1795 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1796 * wrong (but I leave it there in case I am...).
1799 #ifdef USE_TSHARK_SELECT
1801 FD_SET(pipe_input.source, &readfds);
1804 loop_running = TRUE;
1806 while (loop_running)
1808 #ifdef USE_TSHARK_SELECT
1809 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
1815 } else if (ret == 1) {
1817 /* Call the real handler */
1818 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
1819 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
1822 #ifdef USE_TSHARK_SELECT
1831 /* XXX - move the call to main_window_update() out of capture_sync.c */
1832 /* dummy for capture_sync.c to make linker happy */
1833 void main_window_update(void)
1837 /* XXX - move the call to simple_dialog() out of capture_sync.c */
1838 #include "simple_dialog.h"
1840 /* capture_sync.c want's to tell us an error */
1841 gpointer simple_dialog(ESD_TYPE_E type _U_, gint btn_mask _U_,
1842 const gchar *msg_format, ...)
1846 /* XXX - do we need to display buttons and alike? */
1847 va_start(ap, msg_format);
1848 fprintf(stderr, "tshark: ");
1849 vfprintf(stderr, msg_format, ap);
1850 fprintf(stderr, "\n");
1857 /* capture child detected an error */
1859 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
1861 cmdarg_err("%s", error_msg);
1862 cmdarg_err_cont("%s", secondary_error_msg);
1866 /* capture child detected an capture filter related error */
1868 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
1870 dfilter_t *rfcode = NULL;
1873 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
1875 "Invalid capture filter: \"%s\"!\n"
1877 "That string looks like a valid display filter; however, it isn't a valid\n"
1878 "capture filter (%s).\n"
1880 "Note that display filters and capture filters don't have the same syntax,\n"
1881 "so you can't use most display filter expressions as capture filters.\n"
1883 "See the User's Guide for a description of the capture filter syntax.",
1884 capture_opts->cfilter, error_message);
1885 dfilter_free(rfcode);
1888 "Invalid capture filter: \"%s\"!\n"
1890 "That string isn't a valid capture filter (%s).\n"
1891 "See the User's Guide for a description of the capture filter syntax.",
1892 capture_opts->cfilter, error_message);
1897 /* capture child tells us we have a new (or the first) capture file */
1899 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
1901 gboolean is_tempfile;
1905 if(capture_opts->state == CAPTURE_PREPARING) {
1906 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
1908 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
1910 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
1912 capture_opts->cf = &cfile;
1914 /* free the old filename */
1915 if(capture_opts->save_file != NULL) {
1916 /* we start a new capture file, close the old one (if we had one before) */
1917 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
1918 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
1919 wtap_close(((capture_file *) capture_opts->cf)->wth);
1922 g_free(capture_opts->save_file);
1923 is_tempfile = FALSE;
1925 /* we didn't had a save_file before, must be a tempfile */
1929 /* save the new filename */
1930 capture_opts->save_file = g_strdup(new_file);
1932 /* if we are in real-time mode, open the new file now */
1934 /* Attempt to open the capture file and set up to read from it. */
1935 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
1939 /* Don't unlink (delete) the save file - leave it around,
1940 for debugging purposes. */
1941 g_free(capture_opts->save_file);
1942 capture_opts->save_file = NULL;
1948 capture_opts->state = CAPTURE_RUNNING;
1954 /* capture child tells us we have new packets to read */
1956 capture_input_new_packets(capture_options *capture_opts, int to_read)
1962 capture_file *cf = capture_opts->cf;
1967 * Prevent a SIGINFO handler from writing to stdout while we're
1968 * doing so; instead, have it just set a flag telling us to print
1969 * that information when we're done.
1972 #endif /* SIGINFO */
1975 while (to_read-- && cf->wth) {
1976 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
1978 /* read from file failed, tell the capture child to stop */
1979 sync_pipe_stop(capture_opts);
1980 wtap_close(cf->wth);
1983 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
1984 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth));
1987 /* packet sucessfully read and gone through the "Read Filter" */
1993 * Dumpcap's doing all the work; we're not doing any dissection.
1994 * Count all the packets it wrote.
1996 packet_count += to_read;
1999 if (print_packet_counts) {
2000 /* We're printing packet counts. */
2001 if (packet_count != 0) {
2002 fprintf(stderr, "\r%u ", packet_count);
2003 /* stderr could be line buffered */
2010 * Allow SIGINFO handlers to write.
2015 * If a SIGINFO handler asked us to write out capture counts, do so.
2019 #endif /* SIGINFO */
2025 if (!print_packet_counts) {
2026 /* Report the count only if we aren't printing a packet count
2027 as packets arrive. */
2028 fprintf(stderr, "%u packet%s captured\n", packet_count,
2029 plurality(packet_count, "", "s"));
2032 infoprint = FALSE; /* we just reported it */
2033 #endif /* SIGINFO */
2038 report_counts_siginfo(int signum _U_)
2040 int sav_errno = errno;
2041 /* If we've been told to delay printing, just set a flag asking
2042 that we print counts (if we're supposed to), otherwise print
2043 the count of packets captured (if we're supposed to). */
2050 #endif /* SIGINFO */
2053 /* capture child detected any packet drops? */
2055 capture_input_drops(capture_options *capture_opts _U_, int dropped)
2057 if (print_packet_counts) {
2058 /* We're printing packet counts to stderr.
2059 Send a newline so that we move to the line after the packet count. */
2060 fprintf(stderr, "\n");
2064 /* We're printing packet counts to stderr.
2065 Send a newline so that we move to the line after the packet count. */
2066 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2071 /* capture child closed its side of the pipe, do the required cleanup */
2073 capture_input_closed(capture_options *capture_opts)
2077 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2078 wtap_close(((capture_file *) capture_opts->cf)->wth);
2080 #ifdef USE_BROKEN_G_MAIN_LOOP
2081 /*g_main_loop_quit(loop);*/
2084 loop_running = FALSE;
2093 capture_cleanup(DWORD ctrltype _U_)
2095 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2096 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2097 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2098 like SIGTERM at least when the machine's shutting down.
2100 For now, we handle them all as indications that we should clean up
2101 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2104 However, as handlers run in a new thread, we can't just longjmp
2105 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2106 no other handler - such as one that would terminate the process -
2109 XXX - for some reason, typing ^C to TShark, if you run this in
2110 a Cygwin console window in at least some versions of Cygwin,
2111 causes TShark to terminate immediately; this routine gets
2112 called, but the main loop doesn't get a chance to run and
2113 exit cleanly, at least if this is compiled with Microsoft Visual
2114 C++ (i.e., it's a property of the Cygwin console window or Bash;
2115 it happens if TShark is not built with Cygwin - for all I know,
2116 building it with Cygwin may make the problem go away). */
2118 /* tell the capture child to stop */
2119 sync_pipe_stop(&capture_opts);
2121 /* don't stop our own loop already here, otherwise status messages and
2122 * cleanup wouldn't be done properly. The child will indicate the stop of
2123 * everything by calling capture_input_closed() later */
2129 capture_cleanup(int signum _U_)
2131 /* tell the capture child to stop */
2132 sync_pipe_stop(&capture_opts);
2135 #endif /* HAVE_LIBPCAP */
2138 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2139 int max_packet_count, gint64 max_byte_count)
2142 int snapshot_length;
2147 char *save_file_string = NULL;
2149 linktype = wtap_file_encap(cf->wth);
2150 if (save_file != NULL) {
2151 /* Get a string that describes what we're writing to */
2152 save_file_string = output_file_description(save_file);
2154 /* Set up to write to the capture file. */
2155 snapshot_length = wtap_snapshot_length(cf->wth);
2156 if (snapshot_length == 0) {
2157 /* Snapshot length of input file not known. */
2158 snapshot_length = WTAP_MAX_PACKET_SIZE;
2160 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2161 FALSE /* compressed */, &err);
2164 /* We couldn't set up to write to the capture file. */
2167 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2168 cmdarg_err("Capture files can't be written in that format.");
2171 case WTAP_ERR_UNSUPPORTED_ENCAP:
2172 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2173 cmdarg_err("The capture file being read can't be written in "
2177 case WTAP_ERR_CANT_OPEN:
2178 cmdarg_err("The %s couldn't be created for some "
2179 "unknown reason.", save_file_string);
2182 case WTAP_ERR_SHORT_WRITE:
2183 cmdarg_err("A full header couldn't be written to the %s.",
2188 cmdarg_err("The %s could not be created: %s.", save_file_string,
2189 wtap_strerror(err));
2195 if (print_packet_info) {
2196 if (!write_preamble(cf)) {
2198 show_print_file_io_error(err);
2204 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2205 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2206 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2207 /* Either there's no read filtering or this packet passed the
2208 filter, so, if we're writing to a capture file, write
2211 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2212 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2214 /* Error writing to a capture file */
2215 show_capture_file_io_error(save_file, err, FALSE);
2216 wtap_dump_close(pdh, &err);
2220 /* Stop reading if we have the maximum number of packets;
2221 * note that a zero max_packet_count will never be matched
2222 * (unless we roll over the packet number?)
2224 if(max_packet_count == cf->count || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2225 err = 0; /* This is not an error */
2231 /* Print a message noting that the read failed somewhere along the line. */
2234 case WTAP_ERR_UNSUPPORTED_ENCAP:
2235 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2236 cf->filename, err_info);
2239 case WTAP_ERR_CANT_READ:
2240 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2244 case WTAP_ERR_SHORT_READ:
2245 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2249 case WTAP_ERR_BAD_RECORD:
2250 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2251 cf->filename, err_info);
2255 cmdarg_err("An error occurred while reading \"%s\": %s.",
2256 cf->filename, wtap_strerror(err));
2259 if (save_file != NULL) {
2260 /* Now close the capture file. */
2261 if (!wtap_dump_close(pdh, &err))
2262 show_capture_file_io_error(save_file, err, TRUE);
2265 if (save_file != NULL) {
2266 /* Now close the capture file. */
2267 if (!wtap_dump_close(pdh, &err))
2268 show_capture_file_io_error(save_file, err, TRUE);
2270 if (print_packet_info) {
2271 if (!write_finale()) {
2273 show_print_file_io_error(err);
2280 wtap_close(cf->wth);
2283 if (save_file_string != NULL)
2284 g_free(save_file_string);
2290 fill_in_fdata(frame_data *fdata, capture_file *cf,
2291 const struct wtap_pkthdr *phdr, gint64 offset)
2296 fdata->num = cf->count;
2297 fdata->pkt_len = phdr->len;
2298 cum_bytes += phdr->len;
2299 fdata->cum_bytes = cum_bytes;
2300 fdata->cap_len = phdr->caplen;
2301 fdata->file_off = offset;
2302 fdata->lnk_t = phdr->pkt_encap;
2303 fdata->abs_ts.secs = phdr->ts.secs;
2304 fdata->abs_ts.nsecs = phdr->ts.nsecs;
2305 fdata->flags.passed_dfilter = 0;
2306 fdata->flags.encoding = CHAR_ASCII;
2307 fdata->flags.visited = 0;
2308 fdata->flags.marked = 0;
2309 fdata->flags.ref_time = 0;
2310 fdata->color_filter = NULL;
2312 /* If we don't have the time stamp of the first packet in the
2313 capture, it's because this is the first packet. Save the time
2314 stamp of this packet as the time stamp of the first packet. */
2315 if (nstime_is_unset(&first_ts)) {
2316 first_ts = fdata->abs_ts;
2319 /* If we don't have the time stamp of the previous captured packet,
2320 it's because this is the first packet. Save the time
2321 stamp of this packet as the time stamp of the previous captured
2323 if (nstime_is_unset(&prev_cap_ts)) {
2324 prev_cap_ts = fdata->abs_ts;
2327 /* Get the time elapsed between the first packet and this packet. */
2328 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2330 /* If it's greater than the current elapsed time, set the elapsed time
2331 to it (we check for "greater than" so as not to be confused by
2332 time moving backwards). */
2333 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2334 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2335 cf->elapsed_time = fdata->rel_ts;
2338 /* Get the time elapsed between the previous displayed packet and
2340 if (nstime_is_unset(&prev_dis_ts))
2341 nstime_set_zero(&fdata->del_dis_ts);
2343 nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
2345 /* Get the time elapsed between the previous captured packet and
2347 nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &prev_cap_ts);
2348 prev_cap_ts = fdata->abs_ts;
2351 /* Free up all data attached to a "frame_data" structure. */
2353 clear_fdata(frame_data *fdata)
2356 g_slist_free(fdata->pfd);
2360 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2361 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2364 gboolean create_proto_tree;
2365 epan_dissect_t *edt;
2368 /* Count this packet. */
2371 /* If we're going to print packet information, or we're going to
2372 run a read filter, or we're going to process taps, set up to
2373 do a dissection and do so. */
2374 if (do_dissection) {
2375 fill_in_fdata(&fdata, cf, whdr, offset);
2377 if (print_packet_info) {
2378 /* Grab any resolved addresses */
2380 if (g_resolv_flags) {
2381 host_name_lookup_process(NULL);
2386 if (cf->rfcode || verbose || num_tap_filters!=0)
2387 create_proto_tree = TRUE;
2389 create_proto_tree = FALSE;
2390 /* The protocol tree will be "visible", i.e., printed, only if we're
2391 printing packet details, which is true if we're printing stuff
2392 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2394 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2396 /* If we're running a read filter, prime the epan_dissect_t with that
2399 epan_dissect_prime_dfilter(edt, cf->rfcode);
2401 tap_queue_init(edt);
2403 /* We only need the columns if we're printing packet info but we're
2404 *not* verbose; in verbose mode, we print the protocol tree, not
2405 the protocol summary. */
2406 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2407 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2409 tap_push_tapped_queue(edt);
2411 /* Run the read filter if we have one. */
2413 passed = dfilter_apply_edt(cf->rfcode, edt);
2417 /* We're not running a display filter and we're not printing any
2418 packet information, so we don't need to do a dissection, and all
2419 packets are processed. */
2425 /* Keep the time of the current packet if the packet passed
2426 the read filter so that the delta time since last displayed
2427 packet can be calculated */
2428 prev_dis_ts = fdata.abs_ts;
2430 /* Process this packet. */
2431 if (print_packet_info) {
2432 /* We're printing packet information; print the information for
2434 print_packet(cf, edt);
2436 /* The ANSI C standard does not appear to *require* that a line-buffered
2437 stream be flushed to the host environment whenever a newline is
2438 written, it just says that, on such a stream, characters "are
2439 intended to be transmitted to or from the host environment as a
2440 block when a new-line character is encountered".
2442 The Visual C++ 6.0 C implementation doesn't do what is intended;
2443 even if you set a stream to be line-buffered, it still doesn't
2444 flush the buffer at the end of every line.
2446 So, if the "-l" flag was specified, we flush the standard output
2447 at the end of a packet. This will do the right thing if we're
2448 printing packet summary lines, and, as we print the entire protocol
2449 tree for a single packet without waiting for anything to happen,
2450 it should be as good as line-buffered mode if we're printing
2451 protocol trees. (The whole reason for the "-l" flag in either
2452 tcpdump or TShark is to allow the output of a live capture to
2453 be piped to a program or script and to have that script see the
2454 information for the packet as soon as it's printed, rather than
2455 having to wait until a standard I/O buffer fills up. */
2459 if (ferror(stdout)) {
2460 show_print_file_io_error(errno);
2466 if (do_dissection) {
2467 epan_dissect_free(edt);
2468 clear_fdata(&fdata);
2474 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2476 char *save_file_string;
2478 save_file_string = output_file_description(fname);
2483 cmdarg_err("Not all the packets could be written to the %s because there is "
2484 "no space left on the file system.",
2490 cmdarg_err("Not all the packets could be written to the %s because you are "
2491 "too close to, or over your disk quota.",
2496 case WTAP_ERR_CANT_CLOSE:
2497 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2501 case WTAP_ERR_SHORT_WRITE:
2502 cmdarg_err("Not all the packets could be written to the %s.",
2508 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2509 wtap_strerror(err));
2511 cmdarg_err("An error occurred while writing to the %s: %s.",
2512 save_file_string, wtap_strerror(err));
2516 g_free(save_file_string);
2520 write_preamble(capture_file *cf)
2522 switch (output_action) {
2525 return print_preamble(print_stream, cf ? cf->filename : NULL);
2530 write_pdml_preamble(stdout);
2532 write_psml_preamble(stdout);
2533 return !ferror(stdout);
2536 write_fields_preamble(output_fields, stdout);
2537 return !ferror(stdout);
2540 g_assert_not_reached();
2546 get_line_buf(size_t len)
2548 static char *line_bufp = NULL;
2549 static size_t line_buf_len = 256;
2550 size_t new_line_buf_len;
2552 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2553 new_line_buf_len *= 2)
2555 if (line_bufp == NULL) {
2556 line_buf_len = new_line_buf_len;
2557 line_bufp = g_malloc(line_buf_len + 1);
2559 if (new_line_buf_len > line_buf_len) {
2560 line_buf_len = new_line_buf_len;
2561 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2568 print_columns(capture_file *cf)
2575 line_bufp = get_line_buf(256);
2578 for (i = 0; i < cf->cinfo.num_cols; i++) {
2579 switch (cf->cinfo.col_fmt[i]) {
2583 * Don't print this if we're doing a live capture from a network
2584 * interface - if we're doing a live capture, you won't be
2585 * able to look at the capture in the future (it's not being
2586 * saved anywhere), so the frame numbers are unlikely to be
2589 * (XXX - it might be nice to be able to save and print at
2590 * the same time, sort of like an "Update list of packets
2591 * in real time" capture in Wireshark.)
2593 if (capture_opts.iface != NULL)
2596 column_len = strlen(cf->cinfo.col_data[i]);
2599 line_bufp = get_line_buf(buf_offset + column_len);
2600 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2606 case COL_ABS_DATE_TIME: /* XXX - wider */
2607 column_len = strlen(cf->cinfo.col_data[i]);
2608 if (column_len < 10)
2610 line_bufp = get_line_buf(buf_offset + column_len);
2611 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2617 case COL_DEF_DL_SRC:
2618 case COL_RES_DL_SRC:
2619 case COL_UNRES_DL_SRC:
2620 case COL_DEF_NET_SRC:
2621 case COL_RES_NET_SRC:
2622 case COL_UNRES_NET_SRC:
2623 column_len = strlen(cf->cinfo.col_data[i]);
2624 if (column_len < 12)
2626 line_bufp = get_line_buf(buf_offset + column_len);
2627 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2633 case COL_DEF_DL_DST:
2634 case COL_RES_DL_DST:
2635 case COL_UNRES_DL_DST:
2636 case COL_DEF_NET_DST:
2637 case COL_RES_NET_DST:
2638 case COL_UNRES_NET_DST:
2639 column_len = strlen(cf->cinfo.col_data[i]);
2640 if (column_len < 12)
2642 line_bufp = get_line_buf(buf_offset + column_len);
2643 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2647 column_len = strlen(cf->cinfo.col_data[i]);
2648 line_bufp = get_line_buf(buf_offset + column_len);
2649 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2652 buf_offset += column_len;
2653 if (i != cf->cinfo.num_cols - 1) {
2655 * This isn't the last column, so we need to print a
2656 * separator between this column and the next.
2658 * If we printed a network source and are printing a
2659 * network destination of the same type next, separate
2660 * them with "->"; if we printed a network destination
2661 * and are printing a network source of the same type
2662 * next, separate them with "<-"; otherwise separate them
2665 * We add enough space to the buffer for " <- " or " -> ",
2666 * even if we're only adding " ".
2668 line_bufp = get_line_buf(buf_offset + 4);
2669 switch (cf->cinfo.col_fmt[i]) {
2674 switch (cf->cinfo.col_fmt[i + 1]) {
2679 strcat(line_bufp + buf_offset, " -> ");
2684 strcat(line_bufp + buf_offset, " ");
2690 case COL_DEF_DL_SRC:
2691 case COL_RES_DL_SRC:
2692 case COL_UNRES_DL_SRC:
2693 switch (cf->cinfo.col_fmt[i + 1]) {
2695 case COL_DEF_DL_DST:
2696 case COL_RES_DL_DST:
2697 case COL_UNRES_DL_DST:
2698 strcat(line_bufp + buf_offset, " -> ");
2703 strcat(line_bufp + buf_offset, " ");
2709 case COL_DEF_NET_SRC:
2710 case COL_RES_NET_SRC:
2711 case COL_UNRES_NET_SRC:
2712 switch (cf->cinfo.col_fmt[i + 1]) {
2714 case COL_DEF_NET_DST:
2715 case COL_RES_NET_DST:
2716 case COL_UNRES_NET_DST:
2717 strcat(line_bufp + buf_offset, " -> ");
2722 strcat(line_bufp + buf_offset, " ");
2731 switch (cf->cinfo.col_fmt[i + 1]) {
2736 strcat(line_bufp + buf_offset, " <- ");
2741 strcat(line_bufp + buf_offset, " ");
2747 case COL_DEF_DL_DST:
2748 case COL_RES_DL_DST:
2749 case COL_UNRES_DL_DST:
2750 switch (cf->cinfo.col_fmt[i + 1]) {
2752 case COL_DEF_DL_SRC:
2753 case COL_RES_DL_SRC:
2754 case COL_UNRES_DL_SRC:
2755 strcat(line_bufp + buf_offset, " <- ");
2760 strcat(line_bufp + buf_offset, " ");
2766 case COL_DEF_NET_DST:
2767 case COL_RES_NET_DST:
2768 case COL_UNRES_NET_DST:
2769 switch (cf->cinfo.col_fmt[i + 1]) {
2771 case COL_DEF_NET_SRC:
2772 case COL_RES_NET_SRC:
2773 case COL_UNRES_NET_SRC:
2774 strcat(line_bufp + buf_offset, " <- ");
2779 strcat(line_bufp + buf_offset, " ");
2786 strcat(line_bufp + buf_offset, " ");
2792 return print_line(print_stream, 0, line_bufp);
2796 print_packet(capture_file *cf, epan_dissect_t *edt)
2798 print_args_t print_args;
2801 /* Print the information in the protocol tree. */
2802 switch (output_action) {
2805 print_args.to_file = TRUE;
2806 print_args.format = print_format;
2807 print_args.print_summary = !verbose;
2808 print_args.print_hex = verbose && print_hex;
2809 print_args.print_formfeed = FALSE;
2810 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2812 /* init the packet range */
2813 packet_range_init(&print_args.range);
2815 if (!proto_tree_print(&print_args, edt, print_stream))
2818 /* "print_hex_data()" will put out a leading blank line, as well
2819 as a trailing one; print one here, to separate the packets,
2820 only if "print_hex_data()" won't be called. */
2821 if (!print_line(print_stream, 0, ""))
2827 proto_tree_write_pdml(edt, stdout);
2829 return !ferror(stdout);
2831 proto_tree_write_fields(output_fields, edt, stdout);
2833 return !ferror(stdout);
2836 /* Just fill in the columns. */
2837 epan_dissect_fill_in_columns(edt);
2839 /* Now print them. */
2840 switch (output_action) {
2843 if (!print_columns(cf))
2848 proto_tree_write_psml(edt, stdout);
2849 return !ferror(stdout);
2850 case WRITE_FIELDS: /*No non-verbose "fields" format */
2851 g_assert_not_reached();
2856 if (!print_hex_data(print_stream, edt))
2858 if (!print_line(print_stream, 0, ""))
2867 switch (output_action) {
2870 return print_finale(print_stream);
2875 write_pdml_finale(stdout);
2877 write_psml_finale(stdout);
2878 return !ferror(stdout);
2881 write_fields_finale(output_fields, stdout);
2882 return !ferror(stdout);
2885 g_assert_not_reached();
2891 show_print_file_io_error(int err)
2896 cmdarg_err("Not all the packets could be printed because there is "
2897 "no space left on the file system.");
2902 cmdarg_err("Not all the packets could be printed because you are "
2903 "too close to, or over your disk quota.");
2908 cmdarg_err("An error occurred while printing packets: %s.",
2915 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2919 static char errmsg_errno[1024+1];
2922 /* Wiretap error. */
2925 case WTAP_ERR_NOT_REGULAR_FILE:
2926 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2929 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2930 /* Seen only when opening a capture file for reading. */
2931 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
2934 case WTAP_ERR_UNSUPPORTED:
2935 /* Seen only when opening a capture file for reading. */
2936 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2937 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
2940 errmsg = errmsg_errno;
2943 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2944 /* Seen only when opening a capture file for writing. */
2945 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2946 "The file \"%%s\" is a pipe, and %s capture files can't be "
2947 "written to a pipe.", wtap_file_type_string(file_type));
2948 errmsg = errmsg_errno;
2951 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2952 /* Seen only when opening a capture file for writing. */
2953 errmsg = "TShark doesn't support writing capture files in that format.";
2956 case WTAP_ERR_UNSUPPORTED_ENCAP:
2958 errmsg = "TShark can't save this capture in that format.";
2960 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2961 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
2964 errmsg = errmsg_errno;
2968 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2970 errmsg = "TShark can't save this capture in that format.";
2972 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
2975 case WTAP_ERR_BAD_RECORD:
2976 /* Seen only when opening a capture file for reading. */
2977 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2978 "The file \"%%s\" appears to be damaged or corrupt.\n"
2981 errmsg = errmsg_errno;
2984 case WTAP_ERR_CANT_OPEN:
2986 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2988 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2991 case WTAP_ERR_SHORT_READ:
2992 errmsg = "The file \"%s\" appears to have been cut short"
2993 " in the middle of a packet or other data.";
2996 case WTAP_ERR_SHORT_WRITE:
2997 errmsg = "A full header couldn't be written to the file \"%s\".";
3001 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3002 "The file \"%%s\" could not be %s: %s.",
3003 for_writing ? "created" : "opened",
3004 wtap_strerror(err));
3005 errmsg = errmsg_errno;
3009 errmsg = file_open_error_message(err, for_writing);
3014 * Open/create errors are reported with an console message in TShark.
3017 open_failure_message(const char *filename, int err, gboolean for_writing)
3019 fprintf(stderr, "tshark: ");
3020 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3021 fprintf(stderr, "\n");
3025 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3029 char err_msg[2048+1];
3031 wth = wtap_open_offline(fname, err, &err_info, FALSE);
3035 /* The open succeeded. Fill in the information for this file. */
3037 /* Initialize all data structures used for dissection. */
3041 cf->f_datalen = 0; /* not used, but set it anyway */
3043 /* Set the file name because we need it to set the follow stream filter.
3044 XXX - is that still true? We need it for other reasons, though,
3046 cf->filename = g_strdup(fname);
3048 /* Indicate whether it's a permanent or temporary file. */
3049 cf->is_tempfile = is_tempfile;
3051 /* If it's a temporary capture buffer file, mark it as not saved. */
3052 cf->user_saved = !is_tempfile;
3054 cf->cd_t = wtap_file_type(cf->wth);
3056 cf->drops_known = FALSE;
3058 cf->snap = wtap_snapshot_length(cf->wth);
3059 if (cf->snap == 0) {
3060 /* Snapshot length not known. */
3061 cf->has_snap = FALSE;
3062 cf->snap = WTAP_MAX_PACKET_SIZE;
3064 cf->has_snap = TRUE;
3065 nstime_set_zero(&cf->elapsed_time);
3066 nstime_set_unset(&first_ts);
3067 nstime_set_unset(&prev_dis_ts);
3068 nstime_set_unset(&prev_cap_ts);
3073 g_snprintf(err_msg, sizeof err_msg,
3074 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3075 cmdarg_err("%s", err_msg);
3081 * General errors are reported with an console message in TShark.
3084 failure_message(const char *msg_format, va_list ap)
3086 fprintf(stderr, "tshark: ");
3087 vfprintf(stderr, msg_format, ap);
3088 fprintf(stderr, "\n");
3092 * Read errors are reported with an console message in TShark.
3095 read_failure_message(const char *filename, int err)
3097 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3098 filename, strerror(err));
3102 * Report an error in command-line arguments.
3105 cmdarg_err(const char *fmt, ...)
3110 fprintf(stderr, "tshark: ");
3111 vfprintf(stderr, fmt, ap);
3112 fprintf(stderr, "\n");
3117 * Report additional information for an error in command-line arguments.
3120 cmdarg_err_cont(const char *fmt, ...)
3125 vfprintf(stderr, fmt, ap);
3126 fprintf(stderr, "\n");