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
63 #include <epan/epan.h>
64 #include <epan/filesystem.h>
65 #include <wsutil/privileges.h>
68 #include <epan/timestamp.h>
69 #include <epan/packet.h>
71 #include "disabled_protos.h"
72 #include <epan/prefs.h>
73 #include <epan/column.h>
75 #include <epan/addr_resolv.h>
77 #include "clopts_common.h"
78 #include "cmdarg_err.h"
79 #include "version_info.h"
80 #include <epan/plugins.h>
82 #include <epan/epan_dissect.h>
84 #include <epan/stat_cmd_args.h>
85 #include <epan/timestamp.h>
86 #include <epan/ex-opt.h>
89 #include "capture_ui_utils.h"
91 #include "capture-pcap-util.h"
93 #include "capture-wpcap.h"
94 #include "capture_errs.h"
96 #include "capture_sync.h"
97 #endif /* HAVE_LIBPCAP */
99 #include <epan/funnel.h>
103 * This is the template for the decode as option; it is shared between the
104 * various functions that output the usage for this parameter.
106 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
108 static nstime_t first_ts;
109 static nstime_t prev_dis_ts;
110 static nstime_t prev_cap_ts;
111 static GString *comp_info_str, *runtime_info_str;
113 static gboolean print_packet_info; /* TRUE if we're to print packet information */
115 * The way the packet decode is to be written.
118 WRITE_TEXT, /* summary or detail text */
119 WRITE_XML, /* PDML or PSML */
120 WRITE_FIELDS /* User defined list of fields */
121 /* Add CSV and the like here */
123 static output_action_e output_action;
124 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
125 static gboolean verbose;
126 static gboolean print_hex;
127 static gboolean line_buffered;
128 static guint32 cum_bytes = 0;
129 static print_format_e print_format = PR_FMT_TEXT;
130 static print_stream_t *print_stream;
132 static output_fields_t* output_fields = NULL;
135 * Standard secondary message for unexpected errors.
137 static const char please_report[] =
138 "Please report this to the Wireshark developers";
142 * TRUE if we're to print packet counts to keep track of captured packets.
144 static gboolean print_packet_counts;
147 static capture_options global_capture_opts;
150 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
151 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
154 static int capture(void);
155 static void report_counts(void);
157 static BOOL WINAPI capture_cleanup(DWORD);
159 static void capture_cleanup(int);
161 static void report_counts_siginfo(int);
164 #endif /* HAVE_LIBPCAP */
166 static int load_cap_file(capture_file *, char *, int, int, gint64);
167 static gboolean process_packet(capture_file *cf, gint64 offset,
168 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
170 static void show_capture_file_io_error(const char *, int, gboolean);
171 static void show_print_file_io_error(int err);
172 static gboolean write_preamble(capture_file *cf);
173 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
174 static gboolean write_finale(void);
175 static const char *cf_open_error_message(int err, gchar *err_info,
176 gboolean for_writing, int file_type);
178 static void open_failure_message(const char *filename, int err,
179 gboolean for_writing);
180 static void failure_message(const char *msg_format, va_list ap);
181 static void read_failure_message(const char *filename, int err);
182 static void write_failure_message(const char *filename, int err);
187 * Mark a particular frame.
191 cf_mark_frame(capture_file *cf, frame_data *frame)
193 if (! frame->flags.marked) {
194 frame->flags.marked = TRUE;
195 if (cf->count > cf->marked_count)
201 * Unmark a particular frame.
205 cf_unmark_frame(capture_file *cf, frame_data *frame)
207 if (frame->flags.marked) {
208 frame->flags.marked = FALSE;
209 if (cf->marked_count > 0)
215 static void list_capture_types(void) {
218 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
219 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
220 if (wtap_dump_can_open(i))
221 fprintf(stderr, " %s - %s\n",
222 wtap_file_type_short_string(i), wtap_file_type_string(i));
227 print_usage(gboolean print_ver)
234 "TShark " VERSION "%s\n"
235 "Dump and analyze network traffic.\n"
236 "See http://www.wireshark.org for more information.\n"
239 wireshark_svnversion, get_copyright_info());
243 fprintf(output, "\n");
244 fprintf(output, "Usage: tshark [options] ...\n");
245 fprintf(output, "\n");
248 fprintf(output, "Capture interface:\n");
249 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
250 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
251 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
252 fprintf(output, " -p don't capture in promiscuous mode\n");
254 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
256 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
257 fprintf(output, " -D print list of interfaces and exit\n");
258 fprintf(output, " -L print list of link-layer types of iface and exit\n");
259 fprintf(output, "\n");
260 fprintf(output, "Capture stop conditions:\n");
261 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
262 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
263 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
264 fprintf(output, " files:NUM - stop after NUM files\n");
265 /*fprintf(output, "\n");*/
266 fprintf(output, "Capture output:\n");
267 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
268 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
269 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
270 #endif /* HAVE_LIBPCAP */
272 /*fprintf(output, "\n");*/
273 fprintf(output, "Input file:\n");
274 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
276 fprintf(output, "\n");
277 fprintf(output, "Processing:\n");
278 fprintf(output, " -R <read filter> packet filter in Wireshark display filter syntax\n");
279 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
280 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
281 fprintf(output, " -d %s ...\n", decode_as_arg_template);
282 fprintf(output, " \"Decode As\", see the man page for details\n");
283 fprintf(output, " Example: tcp.port==8888,http\n");
285 /*fprintf(output, "\n");*/
286 fprintf(output, "Output:\n");
287 fprintf(output, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
288 fprintf(output, " -C <config profile> start with specified configuration profile\n");
289 fprintf(output, " -F <output file type> set the output file type, default is libpcap\n");
290 fprintf(output, " an empty \"-F\" option will list the file types\n");
291 fprintf(output, " -V add output of packet tree (Packet Details)\n");
292 fprintf(output, " -S display packets even when writing to a file\n");
293 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
294 fprintf(output, " -T pdml|ps|psml|text|fields\n");
295 fprintf(output, " format of text output (def: text)\n");
296 fprintf(output, " -e <field> field to print if -Tfields selected (e.g. tcp.port);\n");
297 fprintf(output, " this option can be repeated to print multiple fields\n");
298 fprintf(output, " -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
299 fprintf(output, " header=y|n switch headers on and off\n");
300 fprintf(output, " separator=/t|/s|<char> select tab, space, printable character as separator\n");
301 fprintf(output, " quote=d|s|n select double, single, no quotes for values\n");
302 fprintf(output, " -t ad|a|r|d|dd|e output format of time stamps (def: r: rel. to first)\n");
303 fprintf(output, " -l flush standard output after each packet\n");
304 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
305 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
306 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
308 fprintf(output, "\n");
309 fprintf(output, "Miscellaneous:\n");
310 fprintf(output, " -h display this help and exit\n");
311 fprintf(output, " -v display version info and exit\n");
312 fprintf(output, " -o <name>:<value> ... override preference setting\n");
313 fprintf(output, " -K <keytab> keytab file to use for kerberos decryption\n");
317 * For a dissector table, print on the stream described by output,
318 * its short name (which is what's used in the "-d" option) and its
322 display_dissector_table_names(const char *table_name, const char *ui_name,
325 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
329 * For a dissector handle, print on the stream described by output,
330 * the filter name (which is what's used in the "-d" option) and the full
331 * name for the protocol that corresponds to this handle.
334 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
337 const gchar* proto_filter_name;
338 const gchar* proto_ui_name;
340 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
342 if (proto_id != -1) {
343 proto_filter_name = proto_get_protocol_filter_name(proto_id);
344 proto_ui_name = proto_get_protocol_name(proto_id);
345 g_assert(proto_filter_name != NULL);
346 g_assert(proto_ui_name != NULL);
348 fprintf((FILE *)output, "\t%s (%s)\n",
355 * The protocol_name_search structure is used by find_protocol_name_func()
356 * to pass parameters and store results
358 struct protocol_name_search{
359 gchar *searched_name; /* Protocol filter name we are looking for */
360 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
361 guint nb_match; /* How many dissectors matched searched_name */
363 typedef struct protocol_name_search *protocol_name_search_t;
366 * This function parses all dissectors associated with a table to find the
367 * one whose protocol has the specified filter name. It is called
368 * as a reference function in a call to dissector_table_foreach_handle.
369 * The name we are looking for, as well as the results, are stored in the
370 * protocol_name_search struct pointed to by user_data.
371 * If called using dissector_table_foreach_handle, we actually parse the
372 * whole list of dissectors.
375 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
379 const gchar *protocol_filter_name;
380 protocol_name_search_t search_info;
384 search_info = (protocol_name_search_t)user_data;
386 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
387 if (proto_id != -1) {
388 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
389 g_assert(protocol_filter_name != NULL);
390 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
392 if (search_info->nb_match == 0) {
393 /* Record this handle only if this is the first match */
394 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
396 search_info->nb_match++;
402 * Print all layer type names supported.
403 * We send the output to the stream described by the handle output.
407 fprint_all_layer_types(FILE *output)
410 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
414 * Print all protocol names supported for a specific layer type.
415 * table_name contains the layer type name in which the search is performed.
416 * We send the output to the stream described by the handle output.
420 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
423 dissector_table_foreach_handle(table_name,
424 display_dissector_names,
429 * The function below parses the command-line parameters for the decode as
430 * feature (a string pointer by cl_param).
431 * It checks the format of the command-line, searches for a matching table
432 * and dissector. If a table/dissector match is not found, we display a
433 * summary of the available tables/dissectors (on stderr) and return FALSE.
434 * If everything is fine, we get the "Decode as" preference activated,
435 * then we return TRUE.
438 add_decode_as(const gchar *cl_param)
442 gchar *decoded_param;
443 gchar *remaining_param;
445 gchar *dissector_str;
446 dissector_handle_t dissector_matching;
447 dissector_table_t table_matching;
448 ftenum_t dissector_table_selector_type;
449 struct protocol_name_search user_protocol_name;
451 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
454 decoded_param = g_strdup(cl_param);
455 g_assert(decoded_param);
458 /* The lines below will parse this string (modifying it) to extract all
459 necessary information. Note that decoded_param is still needed since
460 strings are not copied - we just save pointers. */
462 /* This section extracts a layer type (table_name) from decoded_param */
463 table_name = decoded_param; /* Layer type string starts from beginning */
465 remaining_param = strchr(table_name, '=');
466 if (remaining_param == NULL) {
467 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
468 /* If the argument does not follow the template, carry on anyway to check
469 if the table name is at least correct. If remaining_param is NULL,
470 we'll exit anyway further down */
473 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
476 /* Remove leading and trailing spaces from the table name */
477 while ( table_name[0] == ' ' )
479 while ( table_name[strlen(table_name) - 1] == ' ' )
480 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
482 /* The following part searches a table matching with the layer type specified */
483 table_matching = NULL;
485 /* Look for the requested table */
486 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
487 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
490 table_matching = find_dissector_table(table_name);
491 if (!table_matching) {
492 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
496 if (!table_matching) {
497 /* Display a list of supported layer types to help the user, if the
498 specified layer type was not found */
499 cmdarg_err("Valid layer types are:");
500 fprint_all_layer_types(stderr);
502 if (remaining_param == NULL || !table_matching) {
503 /* Exit if the layer type was not found, or if no '=' separator was found
505 g_free(decoded_param);
509 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
510 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
513 remaining_param++; /* Move to the second '=' */
514 *remaining_param = '\0'; /* Remove the second '=' */
516 remaining_param++; /* Position after the layer type string */
518 /* This section extracts a selector value (selector_str) from decoded_param */
520 selector_str = remaining_param; /* Next part starts with the selector number */
522 remaining_param = strchr(selector_str, ',');
523 if (remaining_param == NULL) {
524 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
525 /* If the argument does not follow the template, carry on anyway to check
526 if the selector value is at least correct. If remaining_param is NULL,
527 we'll exit anyway further down */
530 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
533 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
535 switch (dissector_table_selector_type) {
541 /* The selector for this table is an unsigned number. Parse it as such.
542 There's no need to remove leading and trailing spaces from the
543 selector number string, because sscanf will do that for us. */
544 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
545 cmdarg_err("Invalid selector number \"%s\"", selector_str);
546 g_free(decoded_param);
554 /* The selector for this table is a string. */
558 /* There are currently no dissector tables with any types other
559 than the ones listed above. */
560 g_assert_not_reached();
563 if (remaining_param == NULL) {
564 /* Exit if no ',' separator was found (see above) */
565 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
566 fprint_all_protocols_for_layer_types(stderr, table_name);
567 g_free(decoded_param);
571 remaining_param++; /* Position after the selector number string */
573 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
575 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
577 /* Remove leading and trailing spaces from the dissector name */
578 while ( dissector_str[0] == ' ' )
580 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
581 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
583 dissector_matching = NULL;
585 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
586 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 */
587 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
590 user_protocol_name.nb_match = 0;
591 user_protocol_name.searched_name = dissector_str;
592 user_protocol_name.matched_handle = NULL;
594 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 */
596 if (user_protocol_name.nb_match != 0) {
597 dissector_matching = user_protocol_name.matched_handle;
598 if (user_protocol_name.nb_match > 1) {
599 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
603 /* OK, check whether the problem is that there isn't any such
604 protocol, or that there is but it's not specified as a protocol
605 that's valid for that dissector table.
606 Note, we don't exit here, but dissector_matching will remain NULL,
608 if (proto_get_id_by_filter_name(dissector_str) == -1) {
609 /* No such protocol */
610 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
612 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
613 dissector_str, table_name);
618 if (!dissector_matching) {
619 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
620 fprint_all_protocols_for_layer_types(stderr, table_name);
621 g_free(decoded_param);
625 /* This is the end of the code that parses the command-line options.
626 All information is now stored in the variables:
630 The above variables that are strings are still pointing to areas within
631 decoded_parm. decoded_parm thus still needs to be kept allocated in
632 until we stop needing these variables
633 decoded_param will be deallocated at each exit point of this function */
636 /* We now have a pointer to the handle for the requested dissector
637 (requested protocol) inside the variable dissector_matching */
638 switch (dissector_table_selector_type) {
644 /* The selector for this table is an unsigned number. */
645 dissector_change(table_name, selector, dissector_matching);
651 /* The selector for this table is a string. */
652 dissector_change_string(table_name, selector_str, dissector_matching);
656 /* There are currently no dissector tables with any types other
657 than the ones listed above. */
658 g_assert_not_reached();
660 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
665 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
666 const gchar *message _U_, gpointer user_data _U_)
671 output_file_description(const char *fname)
673 char *save_file_string;
675 /* Get a string that describes what we're writing to */
676 if (strcmp(fname, "-") == 0) {
677 /* We're writing to the standard output */
678 save_file_string = g_strdup("standard output");
680 /* We're writing to a file with the name in save_file */
681 save_file_string = g_strdup_printf("file \"%s\"", fname);
683 return save_file_string;
687 print_current_user(void) {
688 gchar *cur_user, *cur_group;
689 if (started_with_special_privs()) {
690 cur_user = get_cur_username();
691 cur_group = get_cur_groupname();
692 fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
693 cur_user, cur_group);
696 if (running_with_special_privs()) {
697 fprintf(stderr, " This could be dangerous.");
699 fprintf(stderr, "\n");
704 check_capture_privs(void) {
707 /* Warn the user if npf.sys isn't loaded. */
708 if (!npf_sys_is_running() && get_os_major_version() >= 6) {
709 fprintf(stderr, "The NPF driver isn't running. You may have trouble "
710 "capturing or\nlisting interfaces.\n");
718 main(int argc, char *argv[])
720 char *init_progfile_dir_error;
723 gboolean arg_error = FALSE;
729 char *gpf_path, *pf_path;
730 char *gdp_path, *dp_path;
731 int gpf_open_errno, gpf_read_errno;
732 int pf_open_errno, pf_read_errno;
733 int gdp_open_errno, gdp_read_errno;
734 int dp_open_errno, dp_read_errno;
737 gboolean list_link_layer_types = FALSE;
738 gboolean start_capture = FALSE;
741 gboolean capture_option_specified = FALSE;
743 gboolean quiet = FALSE;
744 int out_file_type = WTAP_FILE_PCAP;
745 gchar *cf_name = NULL, *rfilter = NULL;
746 #ifdef HAVE_PCAP_OPEN_DEAD
747 struct bpf_program fcode;
749 dfilter_t *rfcode = NULL;
752 GLogLevelFlags log_flags;
755 #define OPTSTRING_INIT "a:b:c:C:d:De:E:f:F:G:hi:K:lLnN:o:pqr:R:s:St:T:vVw:xX:y:z:"
758 #define OPTSTRING_WIN32 "B:"
760 #define OPTSTRING_WIN32 ""
763 #define OPTSTRING_WIN32 ""
764 #endif /* HAVE_LIBPCAP */
766 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
769 * Get credential information for later use.
771 get_credential_info();
774 * Attempt to get the pathname of the executable file.
776 init_progfile_dir_error = init_progfile_dir(argv[0],
778 if (init_progfile_dir_error != NULL) {
779 fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
780 init_progfile_dir_error);
784 * In order to have the -X opts assigned before the wslua machine starts
785 * we need to call getopts before epan_init() gets called.
788 optind_initial = optind;
790 while ((opt = getopt(argc, argv, optstring)) != -1) {
792 case 'C': /* Configuration Profile */
793 if (profile_exists (optarg)) {
794 set_profile_name (optarg);
796 cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
808 optind = optind_initial;
811 /* nothing more than the standard GLib handler, but without a warning */
818 g_log_set_handler(NULL,
820 log_func_ignore, NULL /* user_data */);
821 g_log_set_handler(LOG_DOMAIN_CAPTURE,
823 log_func_ignore, NULL /* user_data */);
825 initialize_funnel_ops();
828 capture_opts_init(&global_capture_opts, &cfile);
831 timestamp_set_type(TS_RELATIVE);
832 timestamp_set_precision(TS_PREC_AUTO);
834 /* Register all dissectors; we must do this before checking for the
835 "-G" flag, as the "-G" flag dumps information registered by the
836 dissectors, and we must do it before we read the preferences, in
837 case any dissectors register preferences. */
838 epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
839 failure_message, open_failure_message, read_failure_message,
840 write_failure_message);
842 /* Register all tap listeners; we do this before we parse the arguments,
843 as the "-z" argument can specify a registered tap. */
845 /* we register the plugin taps before the other taps because
846 stats_tree taps plugins will be registered as tap listeners
847 by stats_tree_stat.c and need to registered before that */
849 register_all_plugin_tap_listeners();
851 register_all_tap_listeners();
853 /* Now register the preferences for any non-dissector modules.
854 We must do that before we read the preferences as well. */
855 prefs_register_modules();
857 /* If invoked with the "-G" flag, we dump out information based on
858 the argument to the "-G" flag; if no argument is specified,
859 for backwards compatibility we dump out a glossary of display
862 XXX - we do this here, for now, to support "-G" with no arguments.
863 If none of our build or other processes uses "-G" with no arguments,
864 we can just process it with the other arguments. */
865 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
866 proto_initialize_all_prefixes();
869 proto_registrar_dump_fields(1);
871 if (strcmp(argv[2], "fields") == 0)
872 proto_registrar_dump_fields(1);
873 else if (strcmp(argv[2], "fields2") == 0)
874 proto_registrar_dump_fields(2);
875 else if (strcmp(argv[2], "fields3") == 0)
876 proto_registrar_dump_fields(3);
877 else if (strcmp(argv[2], "protocols") == 0)
878 proto_registrar_dump_protocols();
879 else if (strcmp(argv[2], "values") == 0)
880 proto_registrar_dump_values();
881 else if (strcmp(argv[2], "decodes") == 0)
882 dissector_dump_decodes();
883 else if (strcmp(argv[2], "defaultprefs") == 0)
885 else if (strcmp(argv[2], "currentprefs") == 0) {
886 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
887 &pf_open_errno, &pf_read_errno, &pf_path);
890 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
897 /* Set the C-language locale to the native environment. */
898 setlocale(LC_ALL, "");
900 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
901 &pf_open_errno, &pf_read_errno, &pf_path);
902 if (gpf_path != NULL) {
903 if (gpf_open_errno != 0) {
904 cmdarg_err("Can't open global preferences file \"%s\": %s.",
905 pf_path, strerror(gpf_open_errno));
907 if (gpf_read_errno != 0) {
908 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
909 pf_path, strerror(gpf_read_errno));
912 if (pf_path != NULL) {
913 if (pf_open_errno != 0) {
914 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
915 strerror(pf_open_errno));
917 if (pf_read_errno != 0) {
918 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
919 pf_path, strerror(pf_read_errno));
925 /* Set the name resolution code's flags from the preferences. */
926 g_resolv_flags = prefs->name_resolve;
928 /* Read the disabled protocols file. */
929 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
930 &dp_path, &dp_open_errno, &dp_read_errno);
931 if (gdp_path != NULL) {
932 if (gdp_open_errno != 0) {
933 cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
934 gdp_path, strerror(gdp_open_errno));
936 if (gdp_read_errno != 0) {
937 cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
938 gdp_path, strerror(gdp_read_errno));
942 if (dp_path != NULL) {
943 if (dp_open_errno != 0) {
945 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
946 strerror(dp_open_errno));
948 if (dp_read_errno != 0) {
950 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
951 strerror(dp_read_errno));
956 check_capture_privs();
958 init_cap_file(&cfile);
960 /* Assemble the compile-time version information string */
961 comp_info_str = g_string_new("Compiled ");
962 get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
964 /* Assemble the run-time version information string */
965 runtime_info_str = g_string_new("Running ");
966 get_runtime_version_info(runtime_info_str, NULL);
968 /* Print format defaults to this. */
969 print_format = PR_FMT_TEXT;
971 output_fields = output_fields_new();
973 /* Now get our args */
974 while ((opt = getopt(argc, argv, optstring)) != -1) {
976 case 'a': /* autostop criteria */
977 case 'b': /* Ringbuffer option */
978 case 'c': /* Capture x packets */
979 case 'f': /* capture filter */
980 case 'i': /* Use interface x */
981 case 'p': /* Don't capture in promiscuous mode */
982 case 's': /* Set the snapshot (capture) length */
983 case 'w': /* Write to capture file x */
984 case 'y': /* Set the pcap data link type */
986 case 'B': /* Buffer size */
989 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
994 capture_option_specified = TRUE;
999 /* Configuration profile settings were already processed just ignore them this time*/
1001 case 'd': /* Decode as rule */
1002 if (!add_decode_as(optarg))
1005 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1006 case 'K': /* Kerberos keytab file */
1007 read_keytab_file(optarg);
1010 case 'D': /* Print a list of capture devices and exit */
1012 status = capture_opts_list_interfaces(FALSE);
1015 capture_option_specified = TRUE;
1021 output_fields_add(output_fields, optarg);
1025 if(!output_fields_set_option(output_fields, optarg)) {
1026 cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1027 output_fields_list_options(stderr);
1032 out_file_type = wtap_short_string_to_file_type(optarg);
1033 if (out_file_type < 0) {
1034 cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1035 list_capture_types();
1039 case 'h': /* Print help and exit */
1043 case 'l': /* "Line-buffer" standard output */
1044 /* This isn't line-buffering, strictly speaking, it's just
1045 flushing the standard output after the information for
1046 each packet is printed; however, that should be good
1047 enough for all the purposes to which "-l" is put (and
1048 is probably actually better for "-V", as it does fewer
1051 See the comment in "process_packet()" for an explanation of
1052 why we do that, and why we don't just use "setvbuf()" to
1053 make the standard output line-buffered (short version: in
1054 Windows, "line-buffered" is the same as "fully-buffered",
1055 and the output buffer is only flushed when it fills up). */
1056 line_buffered = TRUE;
1058 case 'L': /* Print list of link-layer types and exit */
1060 list_link_layer_types = TRUE;
1062 capture_option_specified = TRUE;
1066 case 'n': /* No name resolution */
1067 g_resolv_flags = RESOLV_NONE;
1069 case 'N': /* Select what types of addresses/port #s to resolve */
1070 if (g_resolv_flags == RESOLV_ALL)
1071 g_resolv_flags = RESOLV_NONE;
1072 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1073 if (badopt != '\0') {
1074 cmdarg_err("-N specifies unknown resolving option '%c';",
1076 cmdarg_err_cont( " Valid options are 'm', 'n', 't', and 'C'");
1080 case 'o': /* Override preference from command line */
1081 switch (prefs_set_pref(optarg)) {
1086 case PREFS_SET_SYNTAX_ERR:
1087 cmdarg_err("Invalid -o flag \"%s\"", optarg);
1091 case PREFS_SET_NO_SUCH_PREF:
1092 case PREFS_SET_OBSOLETE:
1093 cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1098 case 'q': /* Quiet */
1101 case 'r': /* Read capture file x */
1102 cf_name = g_strdup(optarg);
1104 case 'R': /* Read file filter */
1107 case 'S': /* show packets in real time */
1108 print_packet_info = TRUE;
1110 case 't': /* Time stamp type */
1111 if (strcmp(optarg, "r") == 0)
1112 timestamp_set_type(TS_RELATIVE);
1113 else if (strcmp(optarg, "a") == 0)
1114 timestamp_set_type(TS_ABSOLUTE);
1115 else if (strcmp(optarg, "ad") == 0)
1116 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1117 else if (strcmp(optarg, "d") == 0)
1118 timestamp_set_type(TS_DELTA);
1119 else if (strcmp(optarg, "dd") == 0)
1120 timestamp_set_type(TS_DELTA_DIS);
1121 else if (strcmp(optarg, "e") == 0)
1122 timestamp_set_type(TS_EPOCH);
1124 cmdarg_err("Invalid time stamp type \"%s\"",
1126 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1127 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1131 case 'T': /* printing Type */
1132 if (strcmp(optarg, "text") == 0) {
1133 output_action = WRITE_TEXT;
1134 print_format = PR_FMT_TEXT;
1135 } else if (strcmp(optarg, "ps") == 0) {
1136 output_action = WRITE_TEXT;
1137 print_format = PR_FMT_PS;
1138 } else if (strcmp(optarg, "pdml") == 0) {
1139 output_action = WRITE_XML;
1141 } else if (strcmp(optarg, "psml") == 0) {
1142 output_action = WRITE_XML;
1144 } else if(strcmp(optarg, "fields") == 0) {
1145 output_action = WRITE_FIELDS;
1146 verbose = TRUE; /* Need full tree info */
1148 cmdarg_err("Invalid -T parameter.");
1149 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1153 case 'v': /* Show version and exit */
1154 printf("TShark " VERSION "%s\n"
1161 wireshark_svnversion, get_copyright_info(), comp_info_str->str,
1162 runtime_info_str->str);
1165 case 'V': /* Verbose */
1168 case 'x': /* Print packet data in hex (and ASCII) */
1174 /* We won't call the init function for the stat this soon
1175 as it would disallow MATE's fields (which are registered
1176 by the preferences set callback) from being used as
1177 part of a tap filter. Instead, we just add the argument
1178 to a list of stat arguments. */
1179 if (!process_stat_cmd_arg(optarg)) {
1180 cmdarg_err("invalid -z argument.");
1181 cmdarg_err_cont(" -z argument must be one of :");
1182 list_stat_cmd_args();
1187 case '?': /* Bad flag - print usage message */
1190 list_capture_types();
1200 /* If we specified output fields, but not the output field type... */
1201 if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1202 cmdarg_err("Output fields were specified with \"-e\", "
1203 "but \"-Tfields\" was not specified.");
1205 } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1206 cmdarg_err("\"-Tfields\" was specified, but no fields were "
1207 "specified with \"-e\".");
1212 /* If no capture filter or read filter has been specified, and there are
1213 still command-line arguments, treat them as the tokens of a capture
1214 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1215 flag was specified. */
1216 if (optind < argc) {
1217 if (cf_name != NULL) {
1218 if (rfilter != NULL) {
1219 cmdarg_err("Read filters were specified both with \"-R\" "
1220 "and with additional command-line arguments");
1223 rfilter = get_args_as_string(argc, argv, optind);
1226 if (global_capture_opts.has_cfilter) {
1227 cmdarg_err("Capture filters were specified both with \"-f\""
1228 " and with additional command-line arguments");
1231 global_capture_opts.has_cfilter = TRUE;
1232 global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1234 capture_option_specified = TRUE;
1240 if (!global_capture_opts.saving_to_file) {
1241 /* We're not saving the capture to a file; if "-q" wasn't specified,
1242 we should print packet information */
1244 print_packet_info = TRUE;
1246 /* We're saving to a file; if we're writing to the standard output.
1247 and we'll also be writing dissected packets to the standard
1248 output, reject the request. At best, we could redirect that
1249 to the standard error; we *can't* write both to the standard
1250 output and have either of them be useful. */
1251 if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1252 cmdarg_err("You can't write both raw packet data and dissected packets"
1253 " to the standard output.");
1258 /* We're not saving the capture to a file; if "-q" wasn't specified,
1259 we should print packet information */
1261 print_packet_info = TRUE;
1264 #ifndef HAVE_LIBPCAP
1265 if (capture_option_specified)
1266 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1273 /* We don't support capture filters when reading from a capture file
1274 (the BPF compiler doesn't support all link-layer types that we
1275 support in capture files we read). */
1277 if (cf_name != NULL) {
1278 if (global_capture_opts.has_cfilter) {
1279 cmdarg_err("Only read filters, not capture filters, "
1280 "can be specified when reading a capture file.");
1287 if (output_action != WRITE_TEXT) {
1288 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1294 if (list_link_layer_types) {
1295 /* We're supposed to list the link-layer types for an interface;
1296 did the user also specify a capture file to be read? */
1298 /* Yes - that's bogus. */
1299 cmdarg_err("You can't specify -L and a capture file to be read.");
1302 /* No - did they specify a ring buffer option? */
1303 if (global_capture_opts.multi_files_on) {
1304 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1310 * "-r" was specified, so we're reading a capture file.
1311 * Capture options don't apply here.
1313 if (global_capture_opts.multi_files_on) {
1314 cmdarg_err("Multiple capture files requested, but "
1315 "a capture isn't being done.");
1318 if (global_capture_opts.has_file_duration) {
1319 cmdarg_err("Switching capture files after a time interval was specified, but "
1320 "a capture isn't being done.");
1323 if (global_capture_opts.has_ring_num_files) {
1324 cmdarg_err("A ring buffer of capture files was specified, but "
1325 "a capture isn't being done.");
1328 if (global_capture_opts.has_autostop_files) {
1329 cmdarg_err("A maximum number of capture files was specified, but "
1330 "a capture isn't being done.");
1334 /* Note: TShark now allows the restriction of a _read_ file by packet count
1335 * and byte count as well as a write file. Other autostop options remain valid
1336 * only for a write file.
1338 if (global_capture_opts.has_autostop_duration) {
1339 cmdarg_err("A maximum capture time was specified, but "
1340 "a capture isn't being done.");
1345 * "-r" wasn't specified, so we're doing a live capture.
1347 if (global_capture_opts.saving_to_file) {
1348 /* They specified a "-w" flag, so we'll be saving to a capture file. */
1350 /* When capturing, we only support writing libpcap format. */
1351 if (out_file_type != WTAP_FILE_PCAP) {
1352 cmdarg_err("Live captures can only be saved in libpcap format.");
1355 if (global_capture_opts.multi_files_on) {
1356 /* Multiple-file mode doesn't work under certain conditions:
1357 a) it doesn't work if you're writing to the standard output;
1358 b) it doesn't work if you're writing to a pipe;
1360 if (strcmp(global_capture_opts.save_file, "-") == 0) {
1361 cmdarg_err("Multiple capture files requested, but "
1362 "the capture is being written to the standard output.");
1365 if (global_capture_opts.output_to_pipe) {
1366 cmdarg_err("Multiple capture files requested, but "
1367 "the capture file is a pipe.");
1370 if (!global_capture_opts.has_autostop_filesize &&
1371 !global_capture_opts.has_file_duration) {
1372 cmdarg_err("Multiple capture files requested, but "
1373 "no maximum capture file size or duration was specified.");
1378 /* They didn't specify a "-w" flag, so we won't be saving to a
1379 capture file. Check for options that only make sense if
1380 we're saving to a file. */
1381 if (global_capture_opts.has_autostop_filesize) {
1382 cmdarg_err("Maximum capture file size specified, but "
1383 "capture isn't being saved to a file.");
1386 if (global_capture_opts.multi_files_on) {
1387 cmdarg_err("Multiple capture files requested, but "
1388 "the capture isn't being saved to a file.");
1397 /* Start windows sockets */
1398 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1401 /* Notify all registered modules that have had any of their preferences
1402 changed either from one of the preferences file or from the command
1403 line that their preferences have changed. */
1406 /* At this point MATE will have registered its field array so we can
1407 have a tap filter with one of MATE's late-registered fields as part
1408 of the filter. We can now process all the "-z" arguments. */
1409 start_requested_stats();
1411 /* disabled protocols as per configuration file */
1412 if (gdp_path == NULL && dp_path == NULL) {
1413 set_disabled_protos_list();
1416 /* Build the column format array */
1417 col_setup(&cfile.cinfo, prefs->num_cols);
1418 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1419 cfile.cinfo.col_fmt[i] = get_column_format(i);
1420 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1421 if (cfile.cinfo.col_fmt[i] == COL_CUSTOM) {
1422 cfile.cinfo.col_custom_field[i] = g_strdup(get_column_custom_field(i));
1424 cfile.cinfo.col_custom_field[i] = NULL;
1426 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1428 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1429 cfile.cinfo.col_data[i] = NULL;
1430 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1431 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1433 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1434 cfile.cinfo.col_fence[i] = 0;
1435 cfile.cinfo.col_expr.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1436 cfile.cinfo.col_expr.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1439 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1442 for (j = 0; j < NUM_COL_FMTS; j++) {
1443 if (!cfile.cinfo.fmt_matx[i][j])
1446 if (cfile.cinfo.col_first[j] == -1)
1447 cfile.cinfo.col_first[j] = i;
1448 cfile.cinfo.col_last[j] = i;
1453 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1454 capture_opts_trim_ring_num_files(&global_capture_opts);
1457 if (rfilter != NULL) {
1458 if (!dfilter_compile(rfilter, &rfcode)) {
1459 cmdarg_err("%s", dfilter_error_msg);
1461 #ifdef HAVE_PCAP_OPEN_DEAD
1465 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1467 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1469 " Note: That display filter code looks like a valid capture filter;");
1471 " maybe you mixed them up?");
1480 cfile.rfcode = rfcode;
1482 if (print_packet_info) {
1483 /* If we're printing as text or PostScript, we have
1484 to create a print stream. */
1485 if (output_action == WRITE_TEXT) {
1486 switch (print_format) {
1489 print_stream = print_stream_text_stdio_new(stdout);
1493 print_stream = print_stream_ps_stdio_new(stdout);
1497 g_assert_not_reached();
1502 /* We have to dissect each packet if:
1504 we're printing information about each packet;
1506 we're using a read filter on the packets;
1508 we're using any taps. */
1509 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1513 * We're reading a capture file.
1517 * Immediately relinquish any special privileges we have; we must not
1518 * be allowed to read any capture files the user running TShark
1521 relinquish_special_privs_perm();
1522 print_current_user();
1524 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1529 /* Set timestamp precision; there should arguably be a command-line
1530 option to let the user set this. */
1531 switch(wtap_file_tsprecision(cfile.wth)) {
1532 case(WTAP_FILE_TSPREC_SEC):
1533 timestamp_set_precision(TS_PREC_AUTO_SEC);
1535 case(WTAP_FILE_TSPREC_DSEC):
1536 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1538 case(WTAP_FILE_TSPREC_CSEC):
1539 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1541 case(WTAP_FILE_TSPREC_MSEC):
1542 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1544 case(WTAP_FILE_TSPREC_USEC):
1545 timestamp_set_precision(TS_PREC_AUTO_USEC);
1547 case(WTAP_FILE_TSPREC_NSEC):
1548 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1551 g_assert_not_reached();
1554 /* Process the packets in the file */
1556 err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1557 global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1558 global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1560 err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1568 /* No capture file specified, so we're supposed to do a live capture
1569 (or get a list of link-layer types for a live capture device);
1570 do we have support for live captures? */
1577 cmdarg_err("WinPcap couldn't be found.");
1578 detailed_err = cant_load_winpcap_err("TShark");
1579 cmdarg_err_cont("%s", detailed_err);
1580 g_free(detailed_err);
1585 /* trim the interface name and exit if that failed */
1586 if (!capture_opts_trim_iface(&global_capture_opts,
1587 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1591 /* if requested, list the link layer types and exit */
1592 if (list_link_layer_types) {
1593 status = capture_opts_list_link_layer_types(&global_capture_opts, FALSE);
1597 if (print_packet_info) {
1598 if (!write_preamble(NULL)) {
1600 show_print_file_io_error(err);
1603 } else if (!quiet) {
1605 * We're not printing information for each packet, and the user
1606 * didn't ask us not to print a count of packets as they arrive,
1607 * so print that count so the user knows that packets are arriving.
1609 * XXX - what if the user wants to do a live capture, doesn't want
1610 * to save it to a file, doesn't want information printed for each
1611 * packet, does want some "-z" statistic, and wants packet counts
1612 * so they know whether they're seeing any packets?
1614 print_packet_counts = TRUE;
1617 /* For now, assume libpcap gives microsecond precision. */
1618 timestamp_set_precision(TS_PREC_AUTO_USEC);
1622 if (print_packet_info) {
1623 if (!write_finale()) {
1625 show_print_file_io_error(err);
1629 /* No - complain. */
1630 cmdarg_err("This version of TShark was not built with support for capturing packets.");
1635 draw_tap_listeners(TRUE);
1636 funnel_dump_all_text_windows();
1639 output_fields_free(output_fields);
1640 output_fields = NULL;
1645 /*#define USE_BROKEN_G_MAIN_LOOP*/
1647 #ifdef USE_BROKEN_G_MAIN_LOOP
1650 gboolean loop_running = FALSE;
1652 guint32 packet_count = 0;
1655 /* XXX - move to the right position / file */
1656 /* read from a pipe (callback) */
1657 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1659 typedef struct pipe_input_tag {
1663 pipe_input_cb_t input_cb;
1664 guint pipe_input_id;
1666 GStaticMutex callback_running;
1670 static pipe_input_t pipe_input;
1673 /* The timer has expired, see if there's stuff to read from the pipe,
1674 if so, do the callback */
1676 pipe_timer_cb(gpointer data)
1680 gboolean result, result1;
1682 pipe_input_t *pipe_input = data;
1683 gint iterations = 0;
1686 g_static_mutex_lock (&pipe_input->callback_running);
1688 /* try to read data from the pipe only 5 times, to avoid blocking */
1689 while(iterations < 5) {
1690 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1692 /* Oddly enough although Named pipes don't work on win9x,
1693 PeekNamedPipe does !!! */
1694 handle = (HANDLE) _get_osfhandle (pipe_input->source);
1695 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1697 /* Get the child process exit status */
1698 result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1701 /* If the Peek returned an error, or there are bytes to be read
1702 or the childwatcher thread has terminated then call the normal
1704 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1706 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1708 /* And call the real handler */
1709 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1710 g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1711 /* pipe closed, return false so that the timer is stopped */
1712 g_static_mutex_unlock (&pipe_input->callback_running);
1717 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1718 /* No data, stop now */
1725 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1727 g_static_mutex_unlock (&pipe_input->callback_running);
1729 /* we didn't stopped the timer, so let it run */
1736 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1739 pipe_input.source = source;
1740 pipe_input.child_process = child_process;
1741 pipe_input.user_data = user_data;
1742 pipe_input.input_cb = input_cb;
1745 g_static_mutex_init(&pipe_input.callback_running);
1746 /* Tricky to use pipes in win9x, as no concept of wait. NT can
1747 do this but that doesn't cover all win32 platforms. GTK can do
1748 this but doesn't seem to work over processes. Attempt to do
1749 something similar here, start a timer and check for data on every
1751 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1752 pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1762 #ifdef USE_TSHARK_SELECT
1766 struct sigaction action, oldaction;
1770 * XXX - dropping privileges is still required, until code cleanup is done
1772 * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1773 * when it's done, we don't need special privileges to run tshark at all,
1774 * therefore we don't need to drop these privileges
1775 * The only thing we might want to keep is a warning if tshark is run as root,
1776 * as it's no longer necessary and potentially dangerous.
1778 * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1779 * We've opened the capture device, so we shouldn't need any special
1780 * privileges any more; relinquish those privileges.
1782 * XXX - if we have saved set-user-ID support, we should give up those
1783 * privileges immediately, and then reclaim them long enough to get
1784 * a list of network interfaces and to open one, and then give them
1785 * up again, so that stuff we do while processing the argument list,
1786 * reading the user's preferences, loading and starting plugins
1787 * (especially *user* plugins), etc. is done with the user's privileges,
1788 * not special privileges.
1790 relinquish_special_privs_perm();
1791 print_current_user();
1793 /* Initialize all data structures used for dissection. */
1797 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1798 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1800 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1802 action.sa_handler = capture_cleanup;
1803 action.sa_flags = 0;
1804 sigemptyset(&action.sa_mask);
1805 sigaction(SIGTERM, &action, NULL);
1806 sigaction(SIGINT, &action, NULL);
1807 sigaction(SIGHUP, NULL, &oldaction);
1808 if (oldaction.sa_handler == SIG_DFL)
1809 sigaction(SIGHUP, &action, NULL);
1812 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1813 quiet mode, report the number of packets we've captured. */
1814 action.sa_handler = report_counts_siginfo;
1815 action.sa_flags = 0;
1816 sigemptyset(&action.sa_mask);
1817 sigaction(SIGINFO, &action, NULL);
1818 #endif /* SIGINFO */
1821 global_capture_opts.state = CAPTURE_PREPARING;
1823 /* Let the user know what interface was chosen. */
1824 global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1825 fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1827 ret = sync_pipe_start(&global_capture_opts);
1832 /* the actual capture loop
1834 * XXX - glib doesn't seem to provide any event based loop handling.
1836 * XXX - for whatever reason,
1837 * calling g_main_loop_new() ends up in 100% cpu load.
1839 * But that doesn't matter: in UNIX we can use select() to find an input
1840 * source with something to do.
1842 * But that doesn't matter because we're in a CLI (that doesn't need to
1843 * update a GUI or something at the same time) so it's OK if we block
1844 * trying to read from the pipe.
1846 * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1847 * wrong (but I leave it there in case I am...).
1850 #ifdef USE_TSHARK_SELECT
1852 FD_SET(pipe_input.source, &readfds);
1855 loop_running = TRUE;
1857 while (loop_running)
1859 #ifdef USE_TSHARK_SELECT
1860 ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
1866 } else if (ret == 1) {
1868 /* Call the real handler */
1869 if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
1870 g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
1873 #ifdef USE_TSHARK_SELECT
1882 /* XXX - move the call to main_window_update() out of capture_sync.c */
1883 /* dummy for capture_sync.c to make linker happy */
1884 void main_window_update(void)
1888 /* capture child detected an error */
1890 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
1892 cmdarg_err("%s", error_msg);
1893 cmdarg_err_cont("%s", secondary_error_msg);
1897 /* capture child detected an capture filter related error */
1899 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
1901 dfilter_t *rfcode = NULL;
1904 if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
1906 "Invalid capture filter: \"%s\"!\n"
1908 "That string looks like a valid display filter; however, it isn't a valid\n"
1909 "capture filter (%s).\n"
1911 "Note that display filters and capture filters don't have the same syntax,\n"
1912 "so you can't use most display filter expressions as capture filters.\n"
1914 "See the User's Guide for a description of the capture filter syntax.",
1915 capture_opts->cfilter, error_message);
1916 dfilter_free(rfcode);
1919 "Invalid capture filter: \"%s\"!\n"
1921 "That string isn't a valid capture filter (%s).\n"
1922 "See the User's Guide for a description of the capture filter syntax.",
1923 capture_opts->cfilter, error_message);
1928 /* capture child tells us we have a new (or the first) capture file */
1930 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
1932 gboolean is_tempfile;
1936 if(capture_opts->state == CAPTURE_PREPARING) {
1937 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
1939 g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
1941 g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
1943 /* free the old filename */
1944 if (capture_opts->save_file != NULL) {
1946 /* we start a new capture file, close the old one (if we had one before) */
1947 if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
1948 if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
1949 wtap_close(((capture_file *) capture_opts->cf)->wth);
1951 ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
1954 g_free(capture_opts->save_file);
1955 is_tempfile = FALSE;
1957 /* we didn't had a save_file before, must be a tempfile */
1961 /* save the new filename */
1962 capture_opts->save_file = g_strdup(new_file);
1964 /* if we are in real-time mode, open the new file now */
1966 /* Attempt to open the capture file and set up to read from it. */
1967 switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
1971 /* Don't unlink (delete) the save file - leave it around,
1972 for debugging purposes. */
1973 g_free(capture_opts->save_file);
1974 capture_opts->save_file = NULL;
1979 capture_opts->state = CAPTURE_RUNNING;
1985 /* capture child tells us we have new packets to read */
1987 capture_input_new_packets(capture_options *capture_opts, int to_read)
1993 capture_file *cf = capture_opts->cf;
1998 * Prevent a SIGINFO handler from writing to stdout while we're
1999 * doing so; instead, have it just set a flag telling us to print
2000 * that information when we're done.
2003 #endif /* SIGINFO */
2006 while (to_read-- && cf->wth) {
2007 ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2009 /* read from file failed, tell the capture child to stop */
2010 sync_pipe_stop(capture_opts);
2011 wtap_close(cf->wth);
2014 ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2015 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth));
2018 /* packet sucessfully read and gone through the "Read Filter" */
2024 * Dumpcap's doing all the work; we're not doing any dissection.
2025 * Count all the packets it wrote.
2027 packet_count += to_read;
2030 if (print_packet_counts) {
2031 /* We're printing packet counts. */
2032 if (packet_count != 0) {
2033 fprintf(stderr, "\r%u ", packet_count);
2034 /* stderr could be line buffered */
2041 * Allow SIGINFO handlers to write.
2046 * If a SIGINFO handler asked us to write out capture counts, do so.
2050 #endif /* SIGINFO */
2056 if (!print_packet_counts) {
2057 /* Report the count only if we aren't printing a packet count
2058 as packets arrive. */
2059 fprintf(stderr, "%u packet%s captured\n", packet_count,
2060 plurality(packet_count, "", "s"));
2063 infoprint = FALSE; /* we just reported it */
2064 #endif /* SIGINFO */
2069 report_counts_siginfo(int signum _U_)
2071 int sav_errno = errno;
2072 /* If we've been told to delay printing, just set a flag asking
2073 that we print counts (if we're supposed to), otherwise print
2074 the count of packets captured (if we're supposed to). */
2081 #endif /* SIGINFO */
2084 /* capture child detected any packet drops? */
2086 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2088 if (print_packet_counts) {
2089 /* We're printing packet counts to stderr.
2090 Send a newline so that we move to the line after the packet count. */
2091 fprintf(stderr, "\n");
2095 /* We're printing packet counts to stderr.
2096 Send a newline so that we move to the line after the packet count. */
2097 fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2102 /* capture child closed its side of the pipe, do the required cleanup */
2104 capture_input_closed(capture_options *capture_opts)
2108 if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2109 wtap_close(((capture_file *) capture_opts->cf)->wth);
2111 #ifdef USE_BROKEN_G_MAIN_LOOP
2112 /*g_main_loop_quit(loop);*/
2115 loop_running = FALSE;
2124 capture_cleanup(DWORD ctrltype _U_)
2126 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2127 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2128 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2129 like SIGTERM at least when the machine's shutting down.
2131 For now, we handle them all as indications that we should clean up
2132 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2135 However, as handlers run in a new thread, we can't just longjmp
2136 out; we have to set "ld.go" to FALSE, and must return TRUE so that
2137 no other handler - such as one that would terminate the process -
2140 XXX - for some reason, typing ^C to TShark, if you run this in
2141 a Cygwin console window in at least some versions of Cygwin,
2142 causes TShark to terminate immediately; this routine gets
2143 called, but the main loop doesn't get a chance to run and
2144 exit cleanly, at least if this is compiled with Microsoft Visual
2145 C++ (i.e., it's a property of the Cygwin console window or Bash;
2146 it happens if TShark is not built with Cygwin - for all I know,
2147 building it with Cygwin may make the problem go away). */
2149 /* tell the capture child to stop */
2150 sync_pipe_stop(&global_capture_opts);
2152 /* don't stop our own loop already here, otherwise status messages and
2153 * cleanup wouldn't be done properly. The child will indicate the stop of
2154 * everything by calling capture_input_closed() later */
2160 capture_cleanup(int signum _U_)
2162 /* tell the capture child to stop */
2163 sync_pipe_stop(&global_capture_opts);
2166 #endif /* HAVE_LIBPCAP */
2169 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2170 int max_packet_count, gint64 max_byte_count)
2173 int snapshot_length;
2178 char *save_file_string = NULL;
2180 linktype = wtap_file_encap(cf->wth);
2181 if (save_file != NULL) {
2182 /* Get a string that describes what we're writing to */
2183 save_file_string = output_file_description(save_file);
2185 /* Set up to write to the capture file. */
2186 snapshot_length = wtap_snapshot_length(cf->wth);
2187 if (snapshot_length == 0) {
2188 /* Snapshot length of input file not known. */
2189 snapshot_length = WTAP_MAX_PACKET_SIZE;
2191 pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2192 FALSE /* compressed */, &err);
2195 /* We couldn't set up to write to the capture file. */
2198 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2199 cmdarg_err("Capture files can't be written in that format.");
2202 case WTAP_ERR_UNSUPPORTED_ENCAP:
2203 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2204 cmdarg_err("The capture file being read can't be written in "
2208 case WTAP_ERR_CANT_OPEN:
2209 cmdarg_err("The %s couldn't be created for some "
2210 "unknown reason.", save_file_string);
2213 case WTAP_ERR_SHORT_WRITE:
2214 cmdarg_err("A full header couldn't be written to the %s.",
2219 cmdarg_err("The %s could not be created: %s.", save_file_string,
2220 wtap_strerror(err));
2226 if (print_packet_info) {
2227 if (!write_preamble(cf)) {
2229 show_print_file_io_error(err);
2235 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2236 if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2237 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth))) {
2238 /* Either there's no read filtering or this packet passed the
2239 filter, so, if we're writing to a capture file, write
2242 if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2243 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2245 /* Error writing to a capture file */
2246 show_capture_file_io_error(save_file, err, FALSE);
2247 wtap_dump_close(pdh, &err);
2251 /* Stop reading if we have the maximum number of packets;
2252 * When the -c option has not been used, max_packet_count
2253 * starts at 0, which practically means, never stop reading.
2254 * (unless we roll over max_packet_count ?)
2256 if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2257 err = 0; /* This is not an error */
2263 /* Print a message noting that the read failed somewhere along the line. */
2266 case WTAP_ERR_UNSUPPORTED_ENCAP:
2267 cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2268 cf->filename, err_info);
2272 case WTAP_ERR_CANT_READ:
2273 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2277 case WTAP_ERR_SHORT_READ:
2278 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2282 case WTAP_ERR_BAD_RECORD:
2283 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2284 cf->filename, err_info);
2289 cmdarg_err("An error occurred while reading \"%s\": %s.",
2290 cf->filename, wtap_strerror(err));
2293 if (save_file != NULL) {
2294 /* Now close the capture file. */
2295 if (!wtap_dump_close(pdh, &err))
2296 show_capture_file_io_error(save_file, err, TRUE);
2299 if (save_file != NULL) {
2300 /* Now close the capture file. */
2301 if (!wtap_dump_close(pdh, &err))
2302 show_capture_file_io_error(save_file, err, TRUE);
2304 if (print_packet_info) {
2305 if (!write_finale()) {
2307 show_print_file_io_error(err);
2314 wtap_close(cf->wth);
2317 g_free(save_file_string);
2323 fill_in_fdata(frame_data *fdata, capture_file *cf,
2324 const struct wtap_pkthdr *phdr, gint64 offset)
2329 fdata->num = cf->count;
2330 fdata->pkt_len = phdr->len;
2331 cum_bytes += phdr->len;
2332 fdata->cum_bytes = cum_bytes;
2333 fdata->cap_len = phdr->caplen;
2334 fdata->file_off = offset;
2335 fdata->lnk_t = phdr->pkt_encap;
2336 fdata->abs_ts.secs = phdr->ts.secs;
2337 fdata->abs_ts.nsecs = phdr->ts.nsecs;
2338 fdata->flags.passed_dfilter = 0;
2339 fdata->flags.encoding = CHAR_ASCII;
2340 fdata->flags.visited = 0;
2341 fdata->flags.marked = 0;
2342 fdata->flags.ref_time = 0;
2343 fdata->color_filter = NULL;
2345 /* If we don't have the time stamp of the first packet in the
2346 capture, it's because this is the first packet. Save the time
2347 stamp of this packet as the time stamp of the first packet. */
2348 if (nstime_is_unset(&first_ts)) {
2349 first_ts = fdata->abs_ts;
2352 /* If we don't have the time stamp of the previous captured packet,
2353 it's because this is the first packet. Save the time
2354 stamp of this packet as the time stamp of the previous captured
2356 if (nstime_is_unset(&prev_cap_ts)) {
2357 prev_cap_ts = fdata->abs_ts;
2360 /* Get the time elapsed between the first packet and this packet. */
2361 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2363 /* If it's greater than the current elapsed time, set the elapsed time
2364 to it (we check for "greater than" so as not to be confused by
2365 time moving backwards). */
2366 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2367 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2368 cf->elapsed_time = fdata->rel_ts;
2371 /* If we don't have the time stamp of the previous displayed packet,
2372 it's because this is the first packet that's being displayed. Save the time
2373 stamp of this packet as the time stamp of the previous displayed
2375 if (nstime_is_unset(&prev_dis_ts))
2376 prev_dis_ts = fdata->abs_ts;
2378 /* Get the time elapsed between the previous displayed packet and
2380 nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
2382 /* Get the time elapsed between the previous captured packet and
2384 nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &prev_cap_ts);
2385 prev_cap_ts = fdata->abs_ts;
2388 /* Free up all data attached to a "frame_data" structure. */
2390 clear_fdata(frame_data *fdata)
2393 g_slist_free(fdata->pfd);
2397 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2398 union wtap_pseudo_header *pseudo_header, const guchar *pd)
2401 gboolean create_proto_tree;
2402 epan_dissect_t *edt;
2405 /* Count this packet. */
2408 /* If we're going to print packet information, or we're going to
2409 run a read filter, or we're going to process taps, set up to
2410 do a dissection and do so. */
2411 if (do_dissection) {
2412 fill_in_fdata(&fdata, cf, whdr, offset);
2414 if (print_packet_info) {
2415 /* Grab any resolved addresses */
2417 if (g_resolv_flags) {
2418 host_name_lookup_process(NULL);
2423 if (cf->rfcode || verbose || num_tap_filters!=0 || have_custom_cols(&cf->cinfo))
2424 create_proto_tree = TRUE;
2426 create_proto_tree = FALSE;
2427 /* The protocol tree will be "visible", i.e., printed, only if we're
2428 printing packet details, which is true if we're printing stuff
2429 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2431 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2433 /* If we're running a read filter, prime the epan_dissect_t with that
2436 epan_dissect_prime_dfilter(edt, cf->rfcode);
2438 col_custom_prime_edt(edt, &cf->cinfo);
2440 tap_queue_init(edt);
2442 /* We only need the columns if we're printing packet info but we're
2443 *not* verbose; in verbose mode, we print the protocol tree, not
2444 the protocol summary. */
2445 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2446 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2448 tap_push_tapped_queue(edt);
2450 /* Run the read filter if we have one. */
2452 passed = dfilter_apply_edt(cf->rfcode, edt);
2456 /* We're not running a display filter and we're not printing any
2457 packet information, so we don't need to do a dissection, and all
2458 packets are processed. */
2464 /* Keep the time of the current packet if the packet passed
2465 the read filter so that the delta time since last displayed
2466 packet can be calculated */
2467 prev_dis_ts = fdata.abs_ts;
2469 /* Process this packet. */
2470 if (print_packet_info) {
2471 /* We're printing packet information; print the information for
2473 print_packet(cf, edt);
2475 /* The ANSI C standard does not appear to *require* that a line-buffered
2476 stream be flushed to the host environment whenever a newline is
2477 written, it just says that, on such a stream, characters "are
2478 intended to be transmitted to or from the host environment as a
2479 block when a new-line character is encountered".
2481 The Visual C++ 6.0 C implementation doesn't do what is intended;
2482 even if you set a stream to be line-buffered, it still doesn't
2483 flush the buffer at the end of every line.
2485 So, if the "-l" flag was specified, we flush the standard output
2486 at the end of a packet. This will do the right thing if we're
2487 printing packet summary lines, and, as we print the entire protocol
2488 tree for a single packet without waiting for anything to happen,
2489 it should be as good as line-buffered mode if we're printing
2490 protocol trees. (The whole reason for the "-l" flag in either
2491 tcpdump or TShark is to allow the output of a live capture to
2492 be piped to a program or script and to have that script see the
2493 information for the packet as soon as it's printed, rather than
2494 having to wait until a standard I/O buffer fills up. */
2498 if (ferror(stdout)) {
2499 show_print_file_io_error(errno);
2505 if (do_dissection) {
2506 epan_dissect_free(edt);
2507 clear_fdata(&fdata);
2513 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2515 char *save_file_string;
2517 save_file_string = output_file_description(fname);
2522 cmdarg_err("Not all the packets could be written to the %s because there is "
2523 "no space left on the file system.",
2529 cmdarg_err("Not all the packets could be written to the %s because you are "
2530 "too close to, or over your disk quota.",
2535 case WTAP_ERR_CANT_CLOSE:
2536 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2540 case WTAP_ERR_SHORT_WRITE:
2541 cmdarg_err("Not all the packets could be written to the %s.",
2547 cmdarg_err("The %s could not be closed: %s.", save_file_string,
2548 wtap_strerror(err));
2550 cmdarg_err("An error occurred while writing to the %s: %s.",
2551 save_file_string, wtap_strerror(err));
2555 g_free(save_file_string);
2559 write_preamble(capture_file *cf)
2561 switch (output_action) {
2564 return print_preamble(print_stream, cf ? cf->filename : NULL);
2568 write_pdml_preamble(stdout);
2570 write_psml_preamble(stdout);
2571 return !ferror(stdout);
2574 write_fields_preamble(output_fields, stdout);
2575 return !ferror(stdout);
2578 g_assert_not_reached();
2584 get_line_buf(size_t len)
2586 static char *line_bufp = NULL;
2587 static size_t line_buf_len = 256;
2588 size_t new_line_buf_len;
2590 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2591 new_line_buf_len *= 2)
2593 if (line_bufp == NULL) {
2594 line_buf_len = new_line_buf_len;
2595 line_bufp = g_malloc(line_buf_len + 1);
2597 if (new_line_buf_len > line_buf_len) {
2598 line_buf_len = new_line_buf_len;
2599 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2606 print_columns(capture_file *cf)
2613 line_bufp = get_line_buf(256);
2616 for (i = 0; i < cf->cinfo.num_cols; i++) {
2617 switch (cf->cinfo.col_fmt[i]) {
2621 * Don't print this if we're doing a live capture from a network
2622 * interface - if we're doing a live capture, you won't be
2623 * able to look at the capture in the future (it's not being
2624 * saved anywhere), so the frame numbers are unlikely to be
2627 * (XXX - it might be nice to be able to save and print at
2628 * the same time, sort of like an "Update list of packets
2629 * in real time" capture in Wireshark.)
2631 if (global_capture_opts.iface != NULL)
2634 column_len = strlen(cf->cinfo.col_data[i]);
2637 line_bufp = get_line_buf(buf_offset + column_len);
2638 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2644 case COL_ABS_DATE_TIME: /* XXX - wider */
2645 column_len = strlen(cf->cinfo.col_data[i]);
2646 if (column_len < 10)
2648 line_bufp = get_line_buf(buf_offset + column_len);
2649 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2655 case COL_DEF_DL_SRC:
2656 case COL_RES_DL_SRC:
2657 case COL_UNRES_DL_SRC:
2658 case COL_DEF_NET_SRC:
2659 case COL_RES_NET_SRC:
2660 case COL_UNRES_NET_SRC:
2661 column_len = strlen(cf->cinfo.col_data[i]);
2662 if (column_len < 12)
2664 line_bufp = get_line_buf(buf_offset + column_len);
2665 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2671 case COL_DEF_DL_DST:
2672 case COL_RES_DL_DST:
2673 case COL_UNRES_DL_DST:
2674 case COL_DEF_NET_DST:
2675 case COL_RES_NET_DST:
2676 case COL_UNRES_NET_DST:
2677 column_len = strlen(cf->cinfo.col_data[i]);
2678 if (column_len < 12)
2680 line_bufp = get_line_buf(buf_offset + column_len);
2681 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2685 column_len = strlen(cf->cinfo.col_data[i]);
2686 line_bufp = get_line_buf(buf_offset + column_len);
2687 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2690 buf_offset += column_len;
2691 if (i != cf->cinfo.num_cols - 1) {
2693 * This isn't the last column, so we need to print a
2694 * separator between this column and the next.
2696 * If we printed a network source and are printing a
2697 * network destination of the same type next, separate
2698 * them with "->"; if we printed a network destination
2699 * and are printing a network source of the same type
2700 * next, separate them with "<-"; otherwise separate them
2703 * We add enough space to the buffer for " <- " or " -> ",
2704 * even if we're only adding " ".
2706 line_bufp = get_line_buf(buf_offset + 4);
2707 switch (cf->cinfo.col_fmt[i]) {
2712 switch (cf->cinfo.col_fmt[i + 1]) {
2717 strcat(line_bufp + buf_offset, " -> ");
2722 strcat(line_bufp + buf_offset, " ");
2728 case COL_DEF_DL_SRC:
2729 case COL_RES_DL_SRC:
2730 case COL_UNRES_DL_SRC:
2731 switch (cf->cinfo.col_fmt[i + 1]) {
2733 case COL_DEF_DL_DST:
2734 case COL_RES_DL_DST:
2735 case COL_UNRES_DL_DST:
2736 strcat(line_bufp + buf_offset, " -> ");
2741 strcat(line_bufp + buf_offset, " ");
2747 case COL_DEF_NET_SRC:
2748 case COL_RES_NET_SRC:
2749 case COL_UNRES_NET_SRC:
2750 switch (cf->cinfo.col_fmt[i + 1]) {
2752 case COL_DEF_NET_DST:
2753 case COL_RES_NET_DST:
2754 case COL_UNRES_NET_DST:
2755 strcat(line_bufp + buf_offset, " -> ");
2760 strcat(line_bufp + buf_offset, " ");
2769 switch (cf->cinfo.col_fmt[i + 1]) {
2774 strcat(line_bufp + buf_offset, " <- ");
2779 strcat(line_bufp + buf_offset, " ");
2785 case COL_DEF_DL_DST:
2786 case COL_RES_DL_DST:
2787 case COL_UNRES_DL_DST:
2788 switch (cf->cinfo.col_fmt[i + 1]) {
2790 case COL_DEF_DL_SRC:
2791 case COL_RES_DL_SRC:
2792 case COL_UNRES_DL_SRC:
2793 strcat(line_bufp + buf_offset, " <- ");
2798 strcat(line_bufp + buf_offset, " ");
2804 case COL_DEF_NET_DST:
2805 case COL_RES_NET_DST:
2806 case COL_UNRES_NET_DST:
2807 switch (cf->cinfo.col_fmt[i + 1]) {
2809 case COL_DEF_NET_SRC:
2810 case COL_RES_NET_SRC:
2811 case COL_UNRES_NET_SRC:
2812 strcat(line_bufp + buf_offset, " <- ");
2817 strcat(line_bufp + buf_offset, " ");
2824 strcat(line_bufp + buf_offset, " ");
2830 return print_line(print_stream, 0, line_bufp);
2834 print_packet(capture_file *cf, epan_dissect_t *edt)
2836 print_args_t print_args;
2839 /* Print the information in the protocol tree. */
2840 switch (output_action) {
2843 print_args.to_file = TRUE;
2844 print_args.format = print_format;
2845 print_args.print_summary = !verbose;
2846 print_args.print_hex = verbose && print_hex;
2847 print_args.print_formfeed = FALSE;
2848 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2850 /* init the packet range */
2851 packet_range_init(&print_args.range);
2853 if (!proto_tree_print(&print_args, edt, print_stream))
2856 /* "print_hex_data()" will put out a leading blank line, as well
2857 as a trailing one; print one here, to separate the packets,
2858 only if "print_hex_data()" won't be called. */
2859 if (!print_line(print_stream, 0, ""))
2865 proto_tree_write_pdml(edt, stdout);
2867 return !ferror(stdout);
2869 proto_tree_write_fields(output_fields, edt, stdout);
2871 return !ferror(stdout);
2874 /* Just fill in the columns. */
2875 epan_dissect_fill_in_columns(edt);
2877 /* Now print them. */
2878 switch (output_action) {
2881 if (!print_columns(cf))
2886 proto_tree_write_psml(edt, stdout);
2887 return !ferror(stdout);
2888 case WRITE_FIELDS: /*No non-verbose "fields" format */
2889 g_assert_not_reached();
2894 if (!print_hex_data(print_stream, edt))
2896 if (!print_line(print_stream, 0, ""))
2905 switch (output_action) {
2908 return print_finale(print_stream);
2912 write_pdml_finale(stdout);
2914 write_psml_finale(stdout);
2915 return !ferror(stdout);
2918 write_fields_finale(output_fields, stdout);
2919 return !ferror(stdout);
2922 g_assert_not_reached();
2928 show_print_file_io_error(int err)
2933 cmdarg_err("Not all the packets could be printed because there is "
2934 "no space left on the file system.");
2939 cmdarg_err("Not all the packets could be printed because you are "
2940 "too close to, or over your disk quota.");
2945 cmdarg_err("An error occurred while printing packets: %s.",
2952 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2956 static char errmsg_errno[1024+1];
2959 /* Wiretap error. */
2962 case WTAP_ERR_NOT_REGULAR_FILE:
2963 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2966 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2967 /* Seen only when opening a capture file for reading. */
2968 errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
2971 case WTAP_ERR_UNSUPPORTED:
2972 /* Seen only when opening a capture file for reading. */
2973 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2974 "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
2977 errmsg = errmsg_errno;
2980 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2981 /* Seen only when opening a capture file for writing. */
2982 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2983 "The file \"%%s\" is a pipe, and %s capture files can't be "
2984 "written to a pipe.", wtap_file_type_string(file_type));
2985 errmsg = errmsg_errno;
2988 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2989 /* Seen only when opening a capture file for writing. */
2990 errmsg = "TShark doesn't support writing capture files in that format.";
2993 case WTAP_ERR_UNSUPPORTED_ENCAP:
2995 errmsg = "TShark can't save this capture in that format.";
2997 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2998 "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3001 errmsg = errmsg_errno;
3005 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3007 errmsg = "TShark can't save this capture in that format.";
3009 errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3012 case WTAP_ERR_BAD_RECORD:
3013 /* Seen only when opening a capture file for reading. */
3014 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3015 "The file \"%%s\" appears to be damaged or corrupt.\n"
3018 errmsg = errmsg_errno;
3021 case WTAP_ERR_CANT_OPEN:
3023 errmsg = "The file \"%s\" could not be created for some unknown reason.";
3025 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3028 case WTAP_ERR_SHORT_READ:
3029 errmsg = "The file \"%s\" appears to have been cut short"
3030 " in the middle of a packet or other data.";
3033 case WTAP_ERR_SHORT_WRITE:
3034 errmsg = "A full header couldn't be written to the file \"%s\".";
3038 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3039 "The file \"%%s\" could not be %s: %s.",
3040 for_writing ? "created" : "opened",
3041 wtap_strerror(err));
3042 errmsg = errmsg_errno;
3046 errmsg = file_open_error_message(err, for_writing);
3051 * Open/create errors are reported with an console message in TShark.
3054 open_failure_message(const char *filename, int err, gboolean for_writing)
3056 fprintf(stderr, "tshark: ");
3057 fprintf(stderr, file_open_error_message(err, for_writing), filename);
3058 fprintf(stderr, "\n");
3062 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3066 char err_msg[2048+1];
3068 wth = wtap_open_offline(fname, err, &err_info, FALSE);
3072 /* The open succeeded. Fill in the information for this file. */
3074 /* Initialize all data structures used for dissection. */
3078 cf->f_datalen = 0; /* not used, but set it anyway */
3080 /* Set the file name because we need it to set the follow stream filter.
3081 XXX - is that still true? We need it for other reasons, though,
3083 cf->filename = g_strdup(fname);
3085 /* Indicate whether it's a permanent or temporary file. */
3086 cf->is_tempfile = is_tempfile;
3088 /* If it's a temporary capture buffer file, mark it as not saved. */
3089 cf->user_saved = !is_tempfile;
3091 cf->cd_t = wtap_file_type(cf->wth);
3093 cf->drops_known = FALSE;
3095 cf->snap = wtap_snapshot_length(cf->wth);
3096 if (cf->snap == 0) {
3097 /* Snapshot length not known. */
3098 cf->has_snap = FALSE;
3099 cf->snap = WTAP_MAX_PACKET_SIZE;
3101 cf->has_snap = TRUE;
3102 nstime_set_zero(&cf->elapsed_time);
3103 nstime_set_unset(&first_ts);
3104 nstime_set_unset(&prev_dis_ts);
3105 nstime_set_unset(&prev_cap_ts);
3107 cf->state = FILE_READ_IN_PROGRESS;
3112 g_snprintf(err_msg, sizeof err_msg,
3113 cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3114 cmdarg_err("%s", err_msg);
3120 * General errors are reported with an console message in TShark.
3123 failure_message(const char *msg_format, va_list ap)
3125 fprintf(stderr, "tshark: ");
3126 vfprintf(stderr, msg_format, ap);
3127 fprintf(stderr, "\n");
3131 * Read errors are reported with an console message in TShark.
3134 read_failure_message(const char *filename, int err)
3136 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3137 filename, strerror(err));
3141 * Write errors are reported with an console message in TShark.
3144 write_failure_message(const char *filename, int err)
3146 cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3147 filename, strerror(err));
3151 * Report an error in command-line arguments.
3154 cmdarg_err(const char *fmt, ...)
3159 failure_message(fmt, ap);
3164 * Report additional information for an error in command-line arguments.
3167 cmdarg_err_cont(const char *fmt, ...)
3172 vfprintf(stderr, fmt, ap);
3173 fprintf(stderr, "\n");