5 * Ethereal - Network traffic analyzer
6 * By Gerald Combs <gerald@ethereal.com>
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 <wiretap/file_util.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/conversation.h>
81 #include <epan/plugins.h>
83 #include "conditions.h"
84 #include "capture_stop_conditions.h"
85 #include "ringbuffer.h"
86 #include "capture_ui_utils.h"
87 #include <epan/epan_dissect.h>
89 #include <epan/stat_cmd_args.h>
90 #include <epan/timestamp.h>
95 #include "capture-pcap-util.h"
96 #include <wiretap/wtap-capture.h>
97 #include <wiretap/libpcap.h>
99 #include "capture-wpcap.h"
100 #include "capture_errs.h"
103 #include "capture_loop.h"
104 #endif /* HAVE_LIBPCAP */
105 #include "epan/emem.h"
108 * This is the template for the decode as option; it is shared between the
109 * various functions that output the usage for this parameter.
111 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
113 static nstime_t first_ts;
114 static nstime_t prev_ts;
115 static GString *comp_info_str, *runtime_info_str;
117 static gboolean print_packet_info; /* TRUE if we're to print packet information */
119 * The way the packet decode is to be written.
122 WRITE_TEXT, /* summary or detail text */
123 WRITE_XML /* PDML or PSML */
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;
137 * TRUE if we're to print packet counts to keep track of captured packets.
139 static gboolean print_packet_counts;
145 static capture_options capture_opts;
149 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
150 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
152 #endif /* HAVE_LIBPCAP */
155 static int capture(char *, int);
156 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
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);
170 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
171 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
172 const guchar *pd, int *err);
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);
190 print_usage(gboolean print_ver)
197 fprintf(output, "This is t" PACKAGE " " VERSION "%s"
198 "\n (C) 1998-2005 Gerald Combs <gerald@ethereal.com>"
201 svnversion, comp_info_str->str, runtime_info_str->str);
206 fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
208 fprintf(output, "\t[ -b <capture ring buffer option> ] ...\n");
210 fprintf(output, "\t[ -B <capture buffer size> ]\n");
212 fprintf(output, "\t[ -c <capture packet count> ]\n");
213 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
214 fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
215 fprintf(output, "\t[ -i <capture interface> ] [ -N <name resolving flags> ]\n");
216 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
217 fprintf(output, "\t[ -R <read (display) filter> ] [ -s <capture snaplen> ]\n");
218 fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|psml|text ]\n");
219 fprintf(output, "\t[ -w <savefile> ] [ -y <capture link type> ] [ -z <statistics> ]\n");
221 fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
222 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
223 fprintf(output, "\t[ -F <output file type> ] [ -N <name resolving flags> ]\n");
224 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
225 fprintf(output, "\t[ -R <read (display) filter> ] \t[ -t <time stamp format> ]\n");
226 fprintf(output, "\t[ -T pdml|ps|psml|text ] [ -w <savefile> ] [ -z <statistics ]\n");
228 fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
229 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
230 if (wtap_dump_can_open(i))
231 fprintf(output, "\t%s - %s\n",
232 wtap_file_type_short_string(i), wtap_file_type_string(i));
234 fprintf(output, "\tdefault is libpcap\n");
238 * For a dissector table, print on the stream described by output,
239 * its short name (which is what's used in the "-d" option) and its
243 display_dissector_table_names(char *table_name, const char *ui_name,
246 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
250 * For a dissector handle, print on the stream described by output,
251 * the filter name (which is what's used in the "-d" option) and the full
252 * name for the protocol that corresponds to this handle.
255 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
258 const gchar* proto_filter_name;
259 const gchar* proto_ui_name;
261 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
263 if (proto_id != -1) {
264 proto_filter_name = proto_get_protocol_filter_name(proto_id);
265 proto_ui_name = proto_get_protocol_name(proto_id);
266 g_assert(proto_filter_name != NULL);
267 g_assert(proto_ui_name != NULL);
269 fprintf((FILE *)output, "\t%s (%s)\n",
276 * The protocol_name_search structure is used by find_protocol_name_func()
277 * to pass parameters and store results
279 struct protocol_name_search{
280 gchar *searched_name; /* Protocol filter name we are looking for */
281 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
282 guint nb_match; /* How many dissectors matched searched_name */
284 typedef struct protocol_name_search *protocol_name_search_t;
287 * This function parses all dissectors associated with a table to find the
288 * one whose protocol has the specified filter name. It is called
289 * as a reference function in a call to dissector_table_foreach_handle.
290 * The name we are looking for, as well as the results, are stored in the
291 * protocol_name_search struct pointed to by user_data.
292 * If called using dissector_table_foreach_handle, we actually parse the
293 * whole list of dissectors.
296 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
300 const gchar *protocol_filter_name;
301 protocol_name_search_t search_info;
305 search_info = (protocol_name_search_t)user_data;
307 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
308 if (proto_id != -1) {
309 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
310 g_assert(protocol_filter_name != NULL);
311 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
313 if (search_info->nb_match == 0) {
314 /* Record this handle only if this is the first match */
315 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
317 search_info->nb_match++;
323 * Print all layer type names supported.
324 * We send the output to the stream described by the handle output.
328 fprint_all_layer_types(FILE *output)
331 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
335 * Print all protocol names supported for a specific layer type.
336 * table_name contains the layer type name in which the search is performed.
337 * We send the output to the stream described by the handle output.
341 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
344 dissector_table_foreach_handle(table_name,
345 display_dissector_names,
350 * The function below parses the command-line parameters for the decode as
351 * feature (a string pointer by cl_param).
352 * It checks the format of the command-line, searches for a matching table
353 * and dissector. If a table/dissector match is not found, we display a
354 * summary of the available tables/dissectors (on stderr) and return FALSE.
355 * If everything is fine, we get the "Decode as" preference activated,
356 * then we return TRUE.
359 add_decode_as(const gchar *cl_param)
363 gchar *decoded_param;
364 gchar *remaining_param;
366 gchar *dissector_str;
367 dissector_handle_t dissector_matching;
368 dissector_table_t table_matching;
369 ftenum_t dissector_table_selector_type;
370 struct protocol_name_search user_protocol_name;
372 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
375 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
376 g_assert(decoded_param);
377 strcpy(decoded_param, cl_param);
380 /* The lines below will parse this string (modifying it) to extract all
381 necessary information. Note that decoded_param is still needed since
382 strings are not copied - we just save pointers. */
384 /* This section extracts a layer type (table_name) from decoded_param */
385 table_name = decoded_param; /* Layer type string starts from beginning */
387 remaining_param = strchr(table_name, '=');
388 if (remaining_param == NULL) {
389 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
390 /* If the argument does not follow the template, carry on anyway to check
391 if the table name is at least correct. If remaining_param is NULL,
392 we'll exit anyway further down */
395 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
398 /* Remove leading and trailing spaces from the table name */
399 while ( table_name[0] == ' ' )
401 while ( table_name[strlen(table_name) - 1] == ' ' )
402 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
404 /* The following part searches a table matching with the layer type specified */
405 table_matching = NULL;
407 /* Look for the requested table */
408 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
409 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
412 table_matching = find_dissector_table(table_name);
413 if (!table_matching) {
414 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
418 if (!table_matching) {
419 /* Display a list of supported layer types to help the user, if the
420 specified layer type was not found */
421 cmdarg_err("Valid layer types are:");
422 fprint_all_layer_types(stderr);
424 if (remaining_param == NULL || !table_matching) {
425 /* Exit if the layer type was not found, or if no '=' separator was found
427 g_free(decoded_param);
431 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
432 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
435 remaining_param++; /* Move to the second '=' */
436 *remaining_param = '\0'; /* Remove the second '=' */
438 remaining_param++; /* Position after the layer type string */
440 /* This section extracts a selector value (selector_str) from decoded_param */
442 selector_str = remaining_param; /* Next part starts with the selector number */
444 remaining_param = strchr(selector_str, ',');
445 if (remaining_param == NULL) {
446 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
447 /* If the argument does not follow the template, carry on anyway to check
448 if the selector value is at least correct. If remaining_param is NULL,
449 we'll exit anyway further down */
452 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
455 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
457 switch (dissector_table_selector_type) {
463 /* The selector for this table is an unsigned number. Parse it as such.
464 There's no need to remove leading and trailing spaces from the
465 selector number string, because sscanf will do that for us. */
466 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
467 cmdarg_err("Invalid selector number \"%s\"", selector_str);
468 g_free(decoded_param);
475 /* The selector for this table is a string. */
479 /* There are currently no dissector tables with any types other
480 than the ones listed above. */
481 g_assert_not_reached();
484 if (remaining_param == NULL) {
485 /* Exit if no ',' separator was found (see above) */
486 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
487 fprint_all_protocols_for_layer_types(stderr, table_name);
488 g_free(decoded_param);
492 remaining_param++; /* Position after the selector number string */
494 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
496 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
498 /* Remove leading and trailing spaces from the dissector name */
499 while ( dissector_str[0] == ' ' )
501 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
502 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
504 dissector_matching = NULL;
506 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
507 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 */
508 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
511 user_protocol_name.nb_match = 0;
512 user_protocol_name.searched_name = dissector_str;
513 user_protocol_name.matched_handle = NULL;
515 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 */
517 if (user_protocol_name.nb_match != 0) {
518 dissector_matching = user_protocol_name.matched_handle;
519 if (user_protocol_name.nb_match > 1) {
520 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
524 /* OK, check whether the problem is that there isn't any such
525 protocol, or that there is but it's not specified as a protocol
526 that's valid for that dissector table.
527 Note, we don't exit here, but dissector_matching will remain NULL,
529 if (proto_get_id_by_filter_name(dissector_str) == -1) {
530 /* No such protocol */
531 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
533 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
534 dissector_str, table_name);
539 if (!dissector_matching) {
540 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
541 fprint_all_protocols_for_layer_types(stderr, table_name);
542 g_free(decoded_param);
546 /* This is the end of the code that parses the command-line options.
547 All information is now stored in the variables:
551 The above variables that are strings are still pointing to areas within
552 decoded_parm. decoded_parm thus still needs to be kept allocated in
553 until we stop needing these variables
554 decoded_param will be deallocated at each exit point of this function */
557 /* We now have a pointer to the handle for the requested dissector
558 (requested protocol) inside the variable dissector_matching */
559 switch (dissector_table_selector_type) {
565 /* The selector for this table is an unsigned number. */
566 dissector_change(table_name, selector, dissector_matching);
571 /* The selector for this table is a string. */
572 dissector_change_string(table_name, selector_str, dissector_matching);
576 /* There are currently no dissector tables with any types other
577 than the ones listed above. */
578 g_assert_not_reached();
580 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
584 void log_func_ignore (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data)
589 main(int argc, char *argv[])
593 gboolean arg_error = FALSE;
599 char *gpf_path, *pf_path;
600 char *gdp_path, *dp_path;
601 int gpf_open_errno, gpf_read_errno;
602 int pf_open_errno, pf_read_errno;
603 int gdp_open_errno, gdp_read_errno;
604 int dp_open_errno, dp_read_errno;
607 gboolean capture_filter_specified = FALSE;
608 gboolean list_link_layer_types = FALSE;
609 gboolean start_capture = FALSE;
611 gboolean capture_option_specified = FALSE;
613 gboolean quiet = FALSE;
614 gchar *save_file = NULL;
615 int out_file_type = WTAP_FILE_PCAP;
616 gchar *cf_name = NULL, *rfilter = NULL;
617 #ifdef HAVE_PCAP_OPEN_DEAD
618 struct bpf_program fcode;
620 dfilter_t *rfcode = NULL;
623 GLogLevelFlags log_flags;
625 #define OPTSTRING_INIT "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vVw:xy:z:"
628 #define OPTSTRING_WIN32 "B:"
630 #define OPTSTRING_WIN32 ""
633 #define OPTSTRING_WIN32 ""
634 #endif /* HAVE_LIBPCAP */
636 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
638 /* nothing more than the standard GLib handler, but without a warning */
641 G_LOG_LEVEL_CRITICAL|
646 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
648 g_log_set_handler(NULL,
650 log_func_ignore, NULL /* user_data */);
652 /* initialize memory allocation subsystem */
657 capture_opts_init(&capture_opts, NULL /* cfile */);
660 timestamp_set_type(TS_RELATIVE);
661 timestamp_set_precision(TS_PREC_AUTO);
663 /* Register all dissectors; we must do this before checking for the
664 "-G" flag, as the "-G" flag dumps information registered by the
665 dissectors, and we must do it before we read the preferences, in
666 case any dissectors register preferences. */
667 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
668 failure_message,open_failure_message,read_failure_message);
670 /* Register all tap listeners; we do this before we parse the arguments,
671 as the "-z" argument can specify a registered tap. */
673 /* we register the plugin taps before the other taps because
674 stats_tree taps plugins will be registered as tap listeners
675 by stats_tree_stat.c and need to registered before that */
677 register_all_plugin_tap_listeners();
679 register_all_tap_listeners();
681 /* Now register the preferences for any non-dissector modules.
682 We must do that before we read the preferences as well. */
683 prefs_register_modules();
685 /* If invoked with the "-G" flag, we dump out information based on
686 the argument to the "-G" flag; if no argument is specified,
687 for backwards compatibility we dump out a glossary of display
690 XXX - we do this here, for now, to support "-G" with no arguments.
691 If none of our build or other processes uses "-G" with no arguments,
692 we can just process it with the other arguments. */
693 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
695 proto_registrar_dump_fields(1);
697 if (strcmp(argv[2], "fields") == 0)
698 proto_registrar_dump_fields(1);
699 else if (strcmp(argv[2], "fields2") == 0)
700 proto_registrar_dump_fields(2);
701 else if (strcmp(argv[2], "fields3") == 0)
702 proto_registrar_dump_fields(3);
703 else if (strcmp(argv[2], "protocols") == 0)
704 proto_registrar_dump_protocols();
705 else if (strcmp(argv[2], "values") == 0)
706 proto_registrar_dump_values();
707 else if (strcmp(argv[2], "decodes") == 0)
708 dissector_dump_decodes();
709 else if (strcmp(argv[2], "defaultprefs") == 0)
711 else if (strcmp(argv[2], "currentprefs") == 0) {
712 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
713 &pf_open_errno, &pf_read_errno, &pf_path);
716 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
723 /* Set the C-language locale to the native environment. */
724 setlocale(LC_ALL, "");
726 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
727 &pf_open_errno, &pf_read_errno, &pf_path);
728 if (gpf_path != NULL) {
729 if (gpf_open_errno != 0) {
730 cmdarg_err("Can't open global preferences file \"%s\": %s.",
731 pf_path, strerror(gpf_open_errno));
733 if (gpf_read_errno != 0) {
734 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
735 pf_path, strerror(gpf_read_errno));
738 if (pf_path != NULL) {
739 if (pf_open_errno != 0) {
740 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
741 strerror(pf_open_errno));
743 if (pf_read_errno != 0) {
744 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
745 pf_path, strerror(pf_read_errno));
751 /* Set the name resolution code's flags from the preferences. */
752 g_resolv_flags = prefs->name_resolve;
754 /* Read the disabled protocols file. */
755 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
756 &dp_path, &dp_open_errno, &dp_read_errno);
757 if (gdp_path != NULL) {
758 if (gdp_open_errno != 0) {
760 "Could not open global disabled protocols file\n\"%s\": %s.",
761 gdp_path, strerror(gdp_open_errno));
763 if (gdp_read_errno != 0) {
765 "I/O error reading global disabled protocols file\n\"%s\": %s.",
766 gdp_path, strerror(gdp_read_errno));
770 if (dp_path != NULL) {
771 if (dp_open_errno != 0) {
773 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
774 strerror(dp_open_errno));
776 if (dp_read_errno != 0) {
778 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
779 strerror(dp_read_errno));
785 /* Load Wpcap, if possible */
789 init_cap_file(&cfile);
791 /* Assemble the compile-time version information string */
792 comp_info_str = g_string_new("Compiled ");
793 get_compiled_version_info(comp_info_str);
795 /* Assemble the run-time version information string */
796 runtime_info_str = g_string_new("Running ");
797 get_runtime_version_info(runtime_info_str);
799 /* Print format defaults to this. */
800 print_format = PR_FMT_TEXT;
802 /* Now get our args */
803 while ((opt = getopt(argc, argv, optstring)) != -1) {
805 case 'a': /* autostop criteria */
806 case 'b': /* Ringbuffer option */
807 case 'c': /* Capture xxx packets */
808 case 'f': /* capture filter */
809 case 'i': /* Use interface xxx */
810 case 'p': /* Don't capture in promiscuous mode */
811 case 's': /* Set the snapshot (capture) length */
812 case 'y': /* Set the pcap data link type */
814 case 'B': /* Buffer size */
817 capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
819 capture_option_specified = TRUE;
823 case 'd': /* Decode as rule */
824 if (!add_decode_as(optarg))
827 case 'D': /* Print a list of capture devices and exit */
829 capture_opts_list_interfaces();
832 capture_option_specified = TRUE;
837 out_file_type = wtap_short_string_to_file_type(optarg);
838 if (out_file_type < 0) {
839 cmdarg_err("\"%s\" isn't a valid capture file type",
844 case 'h': /* Print help and exit */
848 case 'l': /* "Line-buffer" standard output */
849 /* This isn't line-buffering, strictly speaking, it's just
850 flushing the standard output after the information for
851 each packet is printed; however, that should be good
852 enough for all the purposes to which "-l" is put (and
853 is probably actually better for "-V", as it does fewer
856 See the comment in "process_packet()" for an explanation of
857 why we do that, and why we don't just use "setvbuf()" to
858 make the standard output line-buffered (short version: in
859 Windows, "line-buffered" is the same as "fully-buffered",
860 and the output buffer is only flushed when it fills up). */
861 line_buffered = TRUE;
863 case 'L': /* Print list of link-layer types and exit */
865 list_link_layer_types = TRUE;
868 capture_option_specified = TRUE;
872 case 'n': /* No name resolution */
873 g_resolv_flags = RESOLV_NONE;
875 case 'N': /* Select what types of addresses/port #s to resolve */
876 if (g_resolv_flags == RESOLV_ALL)
877 g_resolv_flags = RESOLV_NONE;
878 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
879 if (badopt != '\0') {
880 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
885 case 'o': /* Override preference from command line */
886 switch (prefs_set_pref(optarg)) {
888 case PREFS_SET_SYNTAX_ERR:
889 cmdarg_err("Invalid -o flag \"%s\"", optarg);
893 case PREFS_SET_NO_SUCH_PREF:
894 case PREFS_SET_OBSOLETE:
895 cmdarg_err("-o flag \"%s\" specifies unknown preference",
901 case 'q': /* Quiet */
904 case 'r': /* Read capture file xxx */
905 cf_name = g_strdup(optarg);
907 case 'R': /* Read file filter */
910 case 'S': /* show packets in real time */
911 print_packet_info = TRUE;
913 case 't': /* Time stamp type */
914 if (strcmp(optarg, "r") == 0)
915 timestamp_set_type(TS_RELATIVE);
916 else if (strcmp(optarg, "a") == 0)
917 timestamp_set_type(TS_ABSOLUTE);
918 else if (strcmp(optarg, "ad") == 0)
919 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
920 else if (strcmp(optarg, "d") == 0)
921 timestamp_set_type(TS_DELTA);
923 cmdarg_err("Invalid time stamp type \"%s\"",
925 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
926 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
930 case 'T': /* printing Type */
931 if (strcmp(optarg, "text") == 0) {
932 output_action = WRITE_TEXT;
933 print_format = PR_FMT_TEXT;
934 } else if (strcmp(optarg, "ps") == 0) {
935 output_action = WRITE_TEXT;
936 print_format = PR_FMT_PS;
937 } else if (strcmp(optarg, "pdml") == 0) {
938 output_action = WRITE_XML;
940 } else if (strcmp(optarg, "psml") == 0) {
941 output_action = WRITE_XML;
944 cmdarg_err("Invalid -T parameter.");
945 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", or \"psml\".");
949 case 'v': /* Show version and exit */
950 printf("t" PACKAGE " " VERSION "%s\n%s\n%s\n",
951 svnversion, comp_info_str->str, runtime_info_str->str);
954 case 'w': /* Write to capture file xxx */
955 save_file = g_strdup(optarg);
957 case 'V': /* Verbose */
960 case 'x': /* Print packet data in hex (and ASCII) */
964 /* We won't call the init function for the stat this soon
965 as it would disallow MATE's fields (which are registered
966 by the preferences set callback) from being used as
967 part of a tap filter. Instead, we just add the argument
968 to a list of stat arguments. */
969 if (!process_stat_cmd_arg(optarg)) {
970 cmdarg_err("invalid -z argument.");
971 cmdarg_err_cont(" -z argument must be one of :");
972 list_stat_cmd_args();
977 case '?': /* Bad flag - print usage message */
983 /* If no capture filter or read filter has been specified, and there are
984 still command-line arguments, treat them as the tokens of a capture
985 filter (if no "-r" flag was specified) or a read filter (if a "-r"
986 flag was specified. */
988 if (cf_name != NULL) {
989 if (rfilter != NULL) {
990 cmdarg_err("Read filters were specified both with \"-R\" "
991 "and with additional command-line arguments");
994 rfilter = get_args_as_string(argc, argv, optind);
997 if (capture_filter_specified) {
998 cmdarg_err("Capture filters were specified both with \"-f\""
999 " and with additional command-line arguments");
1002 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1004 capture_option_specified = TRUE;
1009 /* See if we're writing a capture file and the file is a pipe */
1011 ld.output_to_pipe = FALSE;
1013 if (save_file != NULL) {
1014 /* We're writing to a capture file. */
1015 if (strcmp(save_file, "-") == 0) {
1016 /* Write to the standard output. */
1018 save_file = g_strdup("");
1020 /* XXX - should we check whether it's a pipe? It's arguably
1021 silly to do "-w - >output_file" rather than "-w output_file",
1022 but by not checking we might be violating the Principle Of
1023 Least Astonishment. */
1024 ld.output_to_pipe = TRUE;
1029 err = test_for_fifo(save_file);
1032 case ENOENT: /* it doesn't exist, so we'll be creating it,
1033 and it won't be a FIFO */
1034 case 0: /* found it, but it's not a FIFO */
1037 case ESPIPE: /* it is a FIFO */
1038 ld.output_to_pipe = TRUE;
1041 default: /* couldn't stat it */
1042 cmdarg_err("Error testing whether capture file is a pipe: %s",
1049 /* We're not writing to a file, so we should print packet information
1050 unless "-q" was specified. */
1052 print_packet_info = TRUE;
1055 #ifndef HAVE_LIBPCAP
1056 if (capture_option_specified)
1057 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1064 /* We don't support capture filters when reading from a capture file
1065 (the BPF compiler doesn't support all link-layer types that we
1066 support in capture files we read). */
1068 if (cf_name != NULL) {
1069 if (capture_filter_specified) {
1070 cmdarg_err("Only read filters, not capture filters, "
1071 "can be specified when reading a capture file.");
1078 if (output_action != WRITE_TEXT) {
1079 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1085 if (list_link_layer_types) {
1086 /* We're supposed to list the link-layer types for an interface;
1087 did the user also specify a capture file to be read? */
1089 /* Yes - that's bogus. */
1090 cmdarg_err("You can't specify -L and a capture file to be read.");
1093 /* No - did they specify a ring buffer option? */
1094 if (capture_opts.multi_files_on) {
1095 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1099 /* If they didn't specify a "-w" flag, but specified a maximum capture
1100 file size, tell them that this doesn't work, and exit. */
1101 if (capture_opts.has_autostop_filesize && save_file == NULL) {
1102 cmdarg_err("Maximum capture file size specified, but "
1103 "capture isn't being saved to a file.");
1107 if (capture_opts.multi_files_on) {
1108 /* Ring buffer works only under certain conditions:
1109 a) ring buffer does not work if you're not saving the capture to
1111 b) ring buffer only works if you're saving in libpcap format;
1112 c) it makes no sense to enable the ring buffer if the maximum
1113 file size is set to "infinite";
1114 d) file must not be a pipe. */
1115 if (save_file == NULL) {
1116 cmdarg_err("Ring buffer requested, but capture isn't being saved to a file.");
1119 if (out_file_type != WTAP_FILE_PCAP) {
1120 cmdarg_err("Ring buffer requested, but "
1121 "capture isn't being saved in libpcap format.");
1124 if (!capture_opts.has_autostop_filesize) {
1125 cmdarg_err("Ring buffer requested, but "
1126 "no maximum capture file size was specified.");
1129 if (ld.output_to_pipe) {
1130 cmdarg_err("Ring buffer requested, but capture file is a pipe.");
1138 /* Start windows sockets */
1139 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1142 /* Notify all registered modules that have had any of their preferences
1143 changed either from one of the preferences file or from the command
1144 line that their preferences have changed. */
1147 /* At this point MATE will have registered its field array so we can
1148 have a tap filter with one of MATE's late-registered fields as part
1149 of the filter. We can now process all the "-z" arguments. */
1150 start_requested_stats();
1152 /* disabled protocols as per configuration file */
1153 if (gdp_path == NULL && dp_path == NULL) {
1154 set_disabled_protos_list();
1157 /* Build the column format array */
1158 col_setup(&cfile.cinfo, prefs->num_cols);
1159 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1160 cfile.cinfo.col_fmt[i] = get_column_format(i);
1161 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1162 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1164 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1165 cfile.cinfo.col_data[i] = NULL;
1166 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1167 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1169 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1170 cfile.cinfo.col_fence[i] = 0;
1171 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1172 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1175 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1178 for (j = 0; j < NUM_COL_FMTS; j++) {
1179 if (!cfile.cinfo.fmt_matx[i][j])
1182 if (cfile.cinfo.col_first[j] == -1)
1183 cfile.cinfo.col_first[j] = i;
1184 cfile.cinfo.col_last[j] = i;
1189 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1190 capture_opts_trim_ring_num_files(&capture_opts);
1193 if (rfilter != NULL) {
1194 if (!dfilter_compile(rfilter, &rfcode)) {
1195 cmdarg_err("%s", dfilter_error_msg);
1197 #ifdef HAVE_PCAP_OPEN_DEAD
1201 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1203 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1205 " Note: That display filter code looks like a valid capture filter;");
1207 " maybe you mixed them up?");
1216 cfile.rfcode = rfcode;
1218 if (print_packet_info) {
1219 /* If we're printing as text or PostScript, we have
1220 to create a print stream. */
1221 if (output_action == WRITE_TEXT) {
1222 switch (print_format) {
1225 print_stream = print_stream_text_stdio_new(stdout);
1229 print_stream = print_stream_ps_stdio_new(stdout);
1233 g_assert_not_reached();
1238 /* We have to dissect each packet if:
1240 we're printing information about each packet;
1242 we're using a read filter on the packets;
1244 we're using any taps. */
1245 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1249 * We're reading a capture file.
1254 * Immediately relinquish any set-UID or set-GID privileges we have;
1255 * we must not be allowed to read any capture files the user running
1256 * Tethereal can't open.
1262 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1267 /* Set timestamp precision; there should arguably be a command-line
1268 option to let the user set this. */
1269 switch(wtap_file_tsprecision(cfile.wth)) {
1270 case(WTAP_FILE_TSPREC_SEC):
1271 timestamp_set_precision(TS_PREC_AUTO_SEC);
1273 case(WTAP_FILE_TSPREC_DSEC):
1274 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1276 case(WTAP_FILE_TSPREC_CSEC):
1277 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1279 case(WTAP_FILE_TSPREC_MSEC):
1280 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1282 case(WTAP_FILE_TSPREC_USEC):
1283 timestamp_set_precision(TS_PREC_AUTO_USEC);
1285 case(WTAP_FILE_TSPREC_NSEC):
1286 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1289 g_assert_not_reached();
1292 /* Process the packets in the file */
1293 err = load_cap_file(&cfile, save_file, out_file_type);
1300 /* No capture file specified, so we're supposed to do a live capture
1301 (or get a list of link-layer types for a live capture device);
1302 do we have support for live captures? */
1309 cmdarg_err("WinPcap couldn't be found.");
1310 detailed_err = cant_load_winpcap_err("Tethereal");
1311 cmdarg_err_cont("%s", detailed_err);
1312 g_free(detailed_err);
1317 /* trim the interface name and exit if that failed */
1318 if (!capture_opts_trim_iface(&capture_opts,
1319 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1323 /* if requested, list the link layer types and exit */
1324 if (list_link_layer_types) {
1325 capture_opts_list_link_layer_types(&capture_opts);
1331 * The user didn't ask us not to print a count of packets as
1332 * they arrive, so do so.
1334 print_packet_counts = TRUE;
1337 /* For now, assume libpcap gives microsecond precision. */
1338 timestamp_set_precision(TS_PREC_AUTO_USEC);
1340 capture(save_file, out_file_type);
1342 if (capture_opts.multi_files_on) {
1346 /* No - complain. */
1347 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1352 draw_tap_listeners(TRUE);
1359 /* Do the low-level work of a capture.
1360 Returns TRUE if it succeeds, FALSE otherwise. */
1362 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1365 capture(char *save_file, int out_file_type)
1368 int volatile volatile_err = 0;
1369 int volatile inpkts = 0;
1371 char errmsg[1024+1];
1372 condition *volatile cnd_autostop_size = NULL;
1373 condition *volatile cnd_autostop_duration = NULL;
1376 void (*oldhandler)(int);
1377 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1379 struct pcap_stat stats;
1382 dfilter_t *rfcode = NULL;
1385 /* Initialize all data structures used for dissection. */
1388 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1390 ld.packet_cb = capture_pcap_cb;
1393 /* open the "input file" from network interface or capture pipe */
1394 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg)))
1401 * We've opened the capture device, so, if we're set-UID or set-GID,
1402 * relinquish those privileges.
1404 * XXX - if we have saved set-user-ID support, we should give up those
1405 * privileges immediately, and then reclaim them long enough to get
1406 * a list of network interfaces and to open one, and then give them
1407 * up again, so that stuff we do while processing the argument list,
1408 * reading the user's preferences, etc. is done as the real user and
1409 * group, not the effective user and group.
1415 capture_opts.save_file = save_file;
1417 /* open the output file (temporary/specified name/ringbuffer) */
1418 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1422 /* init the input filter from the network interface (capture pipe will do nothing) */
1423 if(!capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe,
1424 capture_opts.iface, capture_opts.cfilter, errmsg, sizeof errmsg))
1429 /* open the wiretap part of the output file (the output file is already open) */
1430 if(!capture_loop_init_wiretap_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg))
1437 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1438 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1440 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1442 XXX - deal with signal semantics on various UNIX platforms. Or just
1443 use "sigaction()" and be done with it? */
1444 signal(SIGTERM, capture_cleanup);
1445 signal(SIGINT, capture_cleanup);
1446 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1447 signal(SIGHUP, oldhandler);
1450 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1451 quiet mode, report the number of packets we've captured. */
1452 signal(SIGINFO, report_counts_siginfo);
1453 #endif /* SIGINFO */
1456 /* Let the user know what interface was chosen. */
1457 descr = get_interface_descriptive_name(capture_opts.iface);
1458 fprintf(stderr, "Capturing on %s\n", descr);
1461 /* initialize capture stop conditions */
1462 init_capture_stop_conditions();
1463 /* create stop conditions */
1464 if (capture_opts.has_autostop_filesize)
1465 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1466 (long)capture_opts.autostop_filesize * 1024);
1467 if (capture_opts.has_autostop_duration)
1468 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1469 (gint32)capture_opts.autostop_duration);
1471 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1472 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT,
1473 capture_opts.file_duration);
1475 if (!setjmp(ld.stopenv)) {
1477 ld.packet_count = 0;
1482 /* We need to be careful with automatic variables defined in the
1483 outer scope which are changed inside the loop. Most compilers
1484 don't try to roll them back to their original values after the
1485 longjmp which causes the loop to finish, but all that the
1486 standards say is that their values are indeterminate. If we
1487 don't want them to be rolled back, we should define them with the
1488 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1489 Programming in the UNIX Environment, p. 178).
1491 The "err" variable causes a particular problem. If we give it
1492 the volatile attribute, then when we pass a reference to it (as
1493 in "&err") to a function, GCC warns: "passing arg <n> of
1494 <function> discards qualifiers from pointer target type".
1495 Therefore within the loop and just beyond we don't use "err".
1496 Within the loop we define "loop_err", and assign its value to
1497 "volatile_err", which is in the outer scope and is checked when
1500 We also define "packet_count_prev" here to keep things tidy,
1501 since it's used only inside the loop. If it were defined in the
1502 outer scope, GCC would give a warning (unnecessary in this case)
1503 that it might be clobbered, and we'd need to give it the volatile
1504 attribute to suppress the warning. */
1507 int packet_count_prev = 0;
1509 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1510 /* We're not stopping at a particular capture file size, and we're
1511 not stopping after some particular amount of time has expired,
1512 so either we have no stop condition or the only stop condition
1513 is a maximum packet count.
1515 If there's no maximum packet count, pass it -1, meaning "until
1516 you run out of packets in the bufferful you read". Otherwise,
1517 pass it the number of packets we have left to capture.
1519 We don't call "pcap_loop()" as, if we're saving to a file that's
1520 a FIFO, we want to flush the FIFO after we're done processing
1521 this libpcap bufferful of packets, so that the program
1522 reading the FIFO sees the packets immediately and doesn't get
1523 any partial packet, forcing it to block in the middle of reading
1525 if (capture_opts.autostop_packets == 0)
1528 if (ld.packet_count >= capture_opts.autostop_packets) {
1529 /* XXX do we need this test here? */
1530 /* It appears there's nothing more to capture. */
1533 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1536 /* We need to check the capture file size or the timeout after
1541 if (ld.from_cap_pipe) {
1542 inpkts = cap_pipe_dispatch(ld.cap_pipe_fd, &ld, &ld.cap_pipe_hdr, &ld.cap_pipe_rechdr, pcap_data,
1543 errmsg, sizeof errmsg);
1546 inpkts = pcap_dispatch(ld.pcap_h, pcap_cnt, capture_pcap_cb, (u_char *) &ld);
1548 /* Error from "pcap_dispatch()", or error or "no more packets" from
1549 "cap_pipe_dispatch(). */
1551 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1552 /* The specified capture time has elapsed; stop the capture. */
1554 } else if (inpkts > 0) {
1555 if (capture_opts.autostop_packets != 0 &&
1556 ld.packet_count >= capture_opts.autostop_packets) {
1557 /* The specified number of packets have been captured and have
1558 passed both any capture filter in effect and any read filter
1561 } else if (cnd_autostop_size != NULL &&
1562 cnd_eval(cnd_autostop_size,
1563 (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))) {
1564 /* We're saving the capture to a file, and the capture file reached
1565 its maximum size. */
1566 if (capture_opts.multi_files_on) {
1567 /* Switch to the next ringbuffer file */
1568 if (ringbuf_switch_file(&ld.wtap_pdh, &save_file, &save_file_fd, &loop_err)) {
1569 /* File switch succeeded: reset the condition */
1570 cnd_reset(cnd_autostop_size);
1571 if (cnd_file_duration) {
1572 cnd_reset(cnd_file_duration);
1575 /* File switch failed: stop here */
1576 volatile_err = loop_err;
1580 /* No ringbuffer - just stop. */
1584 if (ld.output_to_pipe) {
1585 if (ld.packet_count > packet_count_prev) {
1586 wtap_dump_flush(ld.wtap_pdh);
1587 packet_count_prev = ld.packet_count;
1591 } /* while (ld.go) */
1593 /* delete stop conditions */
1594 if (cnd_autostop_size != NULL)
1595 cnd_delete(cnd_autostop_size);
1596 if (cnd_autostop_duration != NULL)
1597 cnd_delete(cnd_autostop_duration);
1598 if (cnd_file_duration != NULL)
1599 cnd_delete(cnd_file_duration);
1601 if (print_packet_counts) {
1602 /* We're printing packet counts to stderr.
1603 Send a newline so that we move to the line after the packet count. */
1604 fprintf(stderr, "\n");
1607 /* If we got an error while capturing, report it. */
1610 if (ld.from_cap_pipe) {
1611 if (ld.cap_pipe_err == PIPERR) {
1612 cmdarg_err("Error while capturing packets: %s",
1618 cmdarg_err("Error while capturing packets: %s",
1619 pcap_geterr(ld.pcap_h));
1623 if (volatile_err == 0)
1626 show_capture_file_io_error(save_file, volatile_err, FALSE);
1630 if (save_file != NULL) {
1631 /* We're saving to a file or files; close all files. */
1632 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1634 /* If we've displayed a message about a write error, there's no point
1635 in displaying another message about an error on close. */
1636 if (!close_ok && write_ok)
1637 show_capture_file_io_error(save_file, err, TRUE);
1641 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1642 eth_close(ld.cap_pipe_fd);
1646 /* Get the capture statistics, and, if any packets were dropped, report
1648 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1649 if (stats.ps_drop != 0) {
1650 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1653 cmdarg_err("Can't get packet-drop statistics: %s",
1654 pcap_geterr(ld.pcap_h));
1656 pcap_close(ld.pcap_h);
1659 /* Report the number of captured packets if not reported during capture
1660 and we are saving to a file. */
1666 if (capture_opts.multi_files_on) {
1667 ringbuf_error_cleanup();
1671 cmdarg_err("%s", errmsg);
1673 if (ld.from_cap_pipe) {
1674 if (ld.cap_pipe_fd >= 0)
1675 eth_close(ld.cap_pipe_fd);
1679 if (ld.pcap_h != NULL)
1680 pcap_close(ld.pcap_h);
1687 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1690 struct wtap_pkthdr whdr;
1691 union wtap_pseudo_header pseudo_header;
1692 loop_data *ld = (loop_data *) user;
1697 /* Convert from libpcap to Wiretap format.
1698 If that fails, ignore the packet (wtap_process_pcap_packet has
1699 written an error message). */
1700 pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1707 * Prevent a SIGINFO handler from writing to stdout while we're
1708 * doing so; instead, have it just set a flag telling us to print
1709 * that information when we're done.
1712 #endif /* SIGINFO */
1714 /* The current packet may have arrived after a very long silence,
1715 * way past the time to switch files. In order not to have
1716 * the first packet of a new series of events as the last
1717 * [or only] packet in the file, switch before writing!
1719 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1720 /* time elapsed for this ring file, switch to the next */
1721 if (ringbuf_switch_file(&ld->wtap_pdh, &ld->save_file, &save_file_fd, &loop_err)) {
1722 /* File switch succeeded: reset the condition */
1723 cnd_reset(cnd_file_duration);
1725 /* File switch failed: stop here */
1726 /* XXX - we should do something with "loop_err" */
1731 if (!process_packet(&cfile, ld->wtap_pdh, 0, &whdr, &pseudo_header, pd, &err)) {
1732 /* Error writing to a capture file */
1733 if (print_packet_counts) {
1734 /* We're printing counts of packets captured; move to the line after
1736 fprintf(stderr, "\n");
1738 show_capture_file_io_error(ld->save_file, err, FALSE);
1739 pcap_close(ld->pcap_h);
1740 wtap_dump_close(ld->wtap_pdh, &err);
1746 * Allow SIGINFO handlers to write.
1751 * If a SIGINFO handler asked us to write out capture counts, do so.
1755 #endif /* SIGINFO */
1760 capture_cleanup(DWORD ctrltype _U_)
1762 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1763 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1764 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1765 like SIGTERM at least when the machine's shutting down.
1767 For now, we handle them all as indications that we should clean up
1768 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1771 However, as handlers run in a new thread, we can't just longjmp
1772 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1773 no other handler - such as one that would terminate the process -
1776 XXX - for some reason, typing ^C to Tethereal, if you run this in
1777 a Cygwin console window in at least some versions of Cygwin,
1778 causes Tethereal to terminate immediately; this routine gets
1779 called, but the main loop doesn't get a chance to run and
1780 exit cleanly, at least if this is compiled with Microsoft Visual
1781 C++ (i.e., it's a property of the Cygwin console window or Bash;
1782 it happens if Tethereal is not built with Cygwin - for all I know,
1783 building it with Cygwin may make the problem go away). */
1789 capture_cleanup(int signum _U_)
1791 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1792 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1793 "ld.go" to FALSE and return, we won't break out of it and quit
1795 longjmp(ld.stopenv, 1);
1803 /* XXX - if we use sigaction, this doesn't have to be done.
1804 (Yes, this isn't necessary on BSD, but just in case a system
1805 where "signal()" has AT&T semantics adopts SIGINFO....) */
1806 signal(SIGINFO, report_counts_siginfo);
1807 #endif /* SIGINFO */
1809 if (!print_packet_counts) {
1810 /* Report the count only if we aren't printing a packet count
1811 as packets arrive. */
1812 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1815 infoprint = FALSE; /* we just reported it */
1816 #endif /* SIGINFO */
1821 report_counts_siginfo(int signum _U_)
1823 int sav_errno = errno;
1824 /* If we've been told to delay printing, just set a flag asking
1825 that we print counts (if we're supposed to), otherwise print
1826 the count of packets captured (if we're supposed to). */
1833 #endif /* SIGINFO */
1834 #endif /* HAVE_LIBPCAP */
1837 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
1840 int snapshot_length;
1846 linktype = wtap_file_encap(cf->wth);
1847 if (save_file != NULL) {
1848 /* Set up to write to the capture file. */
1849 snapshot_length = wtap_snapshot_length(cf->wth);
1850 if (snapshot_length == 0) {
1851 /* Snapshot length of input file not known. */
1852 snapshot_length = WTAP_MAX_PACKET_SIZE;
1854 pdh = wtap_dump_open(save_file, out_file_type,
1855 linktype, snapshot_length, FALSE /* compressed */, &err);
1858 /* We couldn't set up to write to the capture file. */
1861 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1862 cmdarg_err("Capture files can't be written in that format.");
1865 case WTAP_ERR_UNSUPPORTED_ENCAP:
1866 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1867 cmdarg_err("The capture file being read can't be written in "
1871 case WTAP_ERR_CANT_OPEN:
1872 cmdarg_err("The file \"%s\" couldn't be created for some "
1874 *save_file == '\0' ? "stdout" : save_file);
1877 case WTAP_ERR_SHORT_WRITE:
1878 cmdarg_err("A full header couldn't be written to the file \"%s\".",
1879 *save_file == '\0' ? "stdout" : save_file);
1883 cmdarg_err("The file \"%s\" could not be created: %s.",
1884 *save_file == '\0' ? "stdout" : save_file,
1885 wtap_strerror(err));
1891 if (print_packet_info) {
1892 if (!write_preamble(cf)) {
1894 show_print_file_io_error(err);
1900 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
1901 if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
1902 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
1904 /* Error writing to a capture file */
1905 show_capture_file_io_error(save_file, err, FALSE);
1906 wtap_dump_close(pdh, &err);
1911 /* Print a message noting that the read failed somewhere along the line. */
1914 case WTAP_ERR_UNSUPPORTED_ENCAP:
1915 cmdarg_err("\"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)",
1916 cf->filename, err_info);
1919 case WTAP_ERR_CANT_READ:
1920 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
1924 case WTAP_ERR_SHORT_READ:
1925 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
1929 case WTAP_ERR_BAD_RECORD:
1930 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
1931 cf->filename, err_info);
1935 cmdarg_err("An error occurred while reading \"%s\": %s.",
1936 cf->filename, wtap_strerror(err));
1939 if (save_file != NULL) {
1940 /* Now close the capture file. */
1941 if (!wtap_dump_close(pdh, &err))
1942 show_capture_file_io_error(save_file, err, TRUE);
1945 if (save_file != NULL) {
1946 /* Now close the capture file. */
1947 if (!wtap_dump_close(pdh, &err))
1948 show_capture_file_io_error(save_file, err, TRUE);
1950 if (print_packet_info) {
1951 if (!write_finale()) {
1953 show_print_file_io_error(err);
1960 wtap_close(cf->wth);
1967 fill_in_fdata(frame_data *fdata, capture_file *cf,
1968 const struct wtap_pkthdr *phdr, long offset)
1973 fdata->num = cf->count;
1974 fdata->pkt_len = phdr->len;
1975 cum_bytes += phdr->len;
1976 fdata->cum_bytes = cum_bytes;
1977 fdata->cap_len = phdr->caplen;
1978 fdata->file_off = offset;
1979 fdata->lnk_t = phdr->pkt_encap;
1980 fdata->abs_ts = *((nstime_t *) &phdr->ts);
1981 fdata->flags.passed_dfilter = 0;
1982 fdata->flags.encoding = CHAR_ASCII;
1983 fdata->flags.visited = 0;
1984 fdata->flags.marked = 0;
1985 fdata->flags.ref_time = 0;
1987 /* If we don't have the time stamp of the first packet in the
1988 capture, it's because this is the first packet. Save the time
1989 stamp of this packet as the time stamp of the first packet. */
1990 if (nstime_is_zero(&first_ts)) {
1991 first_ts = fdata->abs_ts;
1994 /* If we don't have the time stamp of the previous displayed packet,
1995 it's because this is the first displayed packet. Save the time
1996 stamp of this packet as the time stamp of the previous displayed
1998 if (nstime_is_zero(&prev_ts)) {
1999 prev_ts = fdata->abs_ts;
2002 /* Get the time elapsed between the first packet and this packet. */
2003 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2005 /* If it's greater than the current elapsed time, set the elapsed time
2006 to it (we check for "greater than" so as not to be confused by
2007 time moving backwards). */
2008 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2009 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2010 cf->elapsed_time = fdata->rel_ts;
2013 /* Get the time elapsed between the previous displayed packet and
2015 nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2016 prev_ts = fdata->abs_ts;
2019 /* Free up all data attached to a "frame_data" structure. */
2021 clear_fdata(frame_data *fdata)
2024 g_slist_free(fdata->pfd);
2028 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2029 const struct wtap_pkthdr *whdr,
2030 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2034 gboolean create_proto_tree;
2035 epan_dissect_t *edt;
2038 /* Count this packet. */
2041 /* If we're going to print packet information, or we're going to
2042 run a read filter, or we're going to process taps, set up to
2043 do a dissection and do so. */
2044 if (do_dissection) {
2045 fill_in_fdata(&fdata, cf, whdr, offset);
2047 if (print_packet_info) {
2048 /* Grab any resolved addresses */
2050 if (g_resolv_flags) {
2051 host_name_lookup_process(NULL);
2056 if (cf->rfcode || verbose || num_tap_filters!=0)
2057 create_proto_tree = TRUE;
2059 create_proto_tree = FALSE;
2060 /* The protocol tree will be "visible", i.e., printed, only if we're
2061 printing packet details, which is true if we're printing stuff
2062 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2064 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2066 /* If we're running a read filter, prime the epan_dissect_t with that
2069 epan_dissect_prime_dfilter(edt, cf->rfcode);
2071 tap_queue_init(edt);
2073 /* We only need the columns if we're printing packet info but we're
2074 *not* verbose; in verbose mode, we print the protocol tree, not
2075 the protocol summary. */
2076 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2077 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2079 tap_push_tapped_queue(edt);
2081 /* Run the read filter if we have one. */
2083 passed = dfilter_apply_edt(cf->rfcode, edt);
2087 /* We're not running a display filter and we're not printing any
2088 packet information, so we don't need to do a dissection, and all
2089 packets are processed. */
2095 /* Count this packet. */
2100 /* Process this packet. */
2102 /* We're writing to a capture file; write this packet. */
2103 if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2106 if (print_packet_counts) {
2107 /* We're printing packet counts. */
2108 if (ld.packet_count != 0) {
2109 fprintf(stderr, "\r%u ", ld.packet_count);
2110 /* stderr could be line buffered */
2116 if (print_packet_info) {
2117 /* We're printing packet information; print the information for
2119 print_packet(cf, edt);
2121 /* The ANSI C standard does not appear to *require* that a line-buffered
2122 stream be flushed to the host environment whenever a newline is
2123 written, it just says that, on such a stream, characters "are
2124 intended to be transmitted to or from the host environment as a
2125 block when a new-line character is encountered".
2127 The Visual C++ 6.0 C implementation doesn't do what is intended;
2128 even if you set a stream to be line-buffered, it still doesn't
2129 flush the buffer at the end of every line.
2131 So, if the "-l" flag was specified, we flush the standard output
2132 at the end of a packet. This will do the right thing if we're
2133 printing packet summary lines, and, as we print the entire protocol
2134 tree for a single packet without waiting for anything to happen,
2135 it should be as good as line-buffered mode if we're printing
2136 protocol trees. (The whole reason for the "-l" flag in either
2137 tcpdump or Tethereal is to allow the output of a live capture to
2138 be piped to a program or script and to have that script see the
2139 information for the packet as soon as it's printed, rather than
2140 having to wait until a standard I/O buffer fills up. */
2144 if (ferror(stdout)) {
2145 show_print_file_io_error(errno);
2151 if (do_dissection) {
2152 epan_dissect_free(edt);
2153 clear_fdata(&fdata);
2159 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2167 cmdarg_err("Not all the packets could be written to \"%s\" because there is "
2168 "no space left on the file system.",
2174 cmdarg_err("Not all the packets could be written to \"%s\" because you are "
2175 "too close to, or over your disk quota.",
2180 case WTAP_ERR_CANT_CLOSE:
2181 cmdarg_err("\"%s\" couldn't be closed for some unknown reason.",
2185 case WTAP_ERR_SHORT_WRITE:
2186 cmdarg_err("Not all the packets could be written to \"%s\".",
2192 cmdarg_err("\"%s\" could not be closed: %s.",
2193 fname, wtap_strerror(err));
2195 cmdarg_err("An error occurred while writing to \"%s\": %s.",
2196 fname, wtap_strerror(err));
2203 write_preamble(capture_file *cf)
2205 switch (output_action) {
2208 return print_preamble(print_stream, cf->filename);
2213 write_pdml_preamble(stdout);
2215 write_psml_preamble(stdout);
2216 return !ferror(stdout);
2219 g_assert_not_reached();
2225 get_line_buf(size_t len)
2227 static char *line_bufp = NULL;
2228 static size_t line_buf_len = 256;
2229 size_t new_line_buf_len;
2231 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2232 new_line_buf_len *= 2)
2234 if (line_bufp == NULL) {
2235 line_buf_len = new_line_buf_len;
2236 line_bufp = g_malloc(line_buf_len + 1);
2238 if (new_line_buf_len > line_buf_len) {
2239 line_buf_len = new_line_buf_len;
2240 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2247 print_columns(capture_file *cf)
2254 line_bufp = get_line_buf(256);
2257 for (i = 0; i < cf->cinfo.num_cols; i++) {
2258 switch (cf->cinfo.col_fmt[i]) {
2262 * Don't print this if we're doing a live capture from a network
2263 * interface - if we're doing a live capture, you won't be
2264 * able to look at the capture in the future (it's not being
2265 * saved anywhere), so the frame numbers are unlikely to be
2268 * (XXX - it might be nice to be able to save and print at
2269 * the same time, sort of like an "Update list of packets
2270 * in real time" capture in Ethereal.)
2272 if (capture_opts.iface != NULL)
2275 column_len = strlen(cf->cinfo.col_data[i]);
2278 line_bufp = get_line_buf(buf_offset + column_len);
2279 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2285 case COL_ABS_DATE_TIME: /* XXX - wider */
2286 column_len = strlen(cf->cinfo.col_data[i]);
2287 if (column_len < 10)
2289 line_bufp = get_line_buf(buf_offset + column_len);
2290 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2296 case COL_DEF_DL_SRC:
2297 case COL_RES_DL_SRC:
2298 case COL_UNRES_DL_SRC:
2299 case COL_DEF_NET_SRC:
2300 case COL_RES_NET_SRC:
2301 case COL_UNRES_NET_SRC:
2302 column_len = strlen(cf->cinfo.col_data[i]);
2303 if (column_len < 12)
2305 line_bufp = get_line_buf(buf_offset + column_len);
2306 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2312 case COL_DEF_DL_DST:
2313 case COL_RES_DL_DST:
2314 case COL_UNRES_DL_DST:
2315 case COL_DEF_NET_DST:
2316 case COL_RES_NET_DST:
2317 case COL_UNRES_NET_DST:
2318 column_len = strlen(cf->cinfo.col_data[i]);
2319 if (column_len < 12)
2321 line_bufp = get_line_buf(buf_offset + column_len);
2322 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2326 column_len = strlen(cf->cinfo.col_data[i]);
2327 line_bufp = get_line_buf(buf_offset + column_len);
2328 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2331 buf_offset += column_len;
2332 if (i != cf->cinfo.num_cols - 1) {
2334 * This isn't the last column, so we need to print a
2335 * separator between this column and the next.
2337 * If we printed a network source and are printing a
2338 * network destination of the same type next, separate
2339 * them with "->"; if we printed a network destination
2340 * and are printing a network source of the same type
2341 * next, separate them with "<-"; otherwise separate them
2344 * We add enough space to the buffer for " <- " or " -> ",
2345 * even if we're only adding " ".
2347 line_bufp = get_line_buf(buf_offset + 4);
2348 switch (cf->cinfo.col_fmt[i]) {
2353 switch (cf->cinfo.col_fmt[i + 1]) {
2358 strcat(line_bufp + buf_offset, " -> ");
2363 strcat(line_bufp + buf_offset, " ");
2369 case COL_DEF_DL_SRC:
2370 case COL_RES_DL_SRC:
2371 case COL_UNRES_DL_SRC:
2372 switch (cf->cinfo.col_fmt[i + 1]) {
2374 case COL_DEF_DL_DST:
2375 case COL_RES_DL_DST:
2376 case COL_UNRES_DL_DST:
2377 strcat(line_bufp + buf_offset, " -> ");
2382 strcat(line_bufp + buf_offset, " ");
2388 case COL_DEF_NET_SRC:
2389 case COL_RES_NET_SRC:
2390 case COL_UNRES_NET_SRC:
2391 switch (cf->cinfo.col_fmt[i + 1]) {
2393 case COL_DEF_NET_DST:
2394 case COL_RES_NET_DST:
2395 case COL_UNRES_NET_DST:
2396 strcat(line_bufp + buf_offset, " -> ");
2401 strcat(line_bufp + buf_offset, " ");
2410 switch (cf->cinfo.col_fmt[i + 1]) {
2415 strcat(line_bufp + buf_offset, " <- ");
2420 strcat(line_bufp + buf_offset, " ");
2426 case COL_DEF_DL_DST:
2427 case COL_RES_DL_DST:
2428 case COL_UNRES_DL_DST:
2429 switch (cf->cinfo.col_fmt[i + 1]) {
2431 case COL_DEF_DL_SRC:
2432 case COL_RES_DL_SRC:
2433 case COL_UNRES_DL_SRC:
2434 strcat(line_bufp + buf_offset, " <- ");
2439 strcat(line_bufp + buf_offset, " ");
2445 case COL_DEF_NET_DST:
2446 case COL_RES_NET_DST:
2447 case COL_UNRES_NET_DST:
2448 switch (cf->cinfo.col_fmt[i + 1]) {
2450 case COL_DEF_NET_SRC:
2451 case COL_RES_NET_SRC:
2452 case COL_UNRES_NET_SRC:
2453 strcat(line_bufp + buf_offset, " <- ");
2458 strcat(line_bufp + buf_offset, " ");
2465 strcat(line_bufp + buf_offset, " ");
2471 return print_line(print_stream, 0, line_bufp);
2475 print_packet(capture_file *cf, epan_dissect_t *edt)
2477 print_args_t print_args;
2480 /* Print the information in the protocol tree. */
2481 switch (output_action) {
2484 print_args.to_file = TRUE;
2485 print_args.format = print_format;
2486 print_args.print_summary = !verbose;
2487 print_args.print_hex = verbose && print_hex;
2488 print_args.print_formfeed = FALSE;
2489 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2491 /* init the packet range */
2492 packet_range_init(&print_args.range);
2494 if (!proto_tree_print(&print_args, edt, print_stream))
2497 /* "print_hex_data()" will put out a leading blank line, as well
2498 as a trailing one; print one here, to separate the packets,
2499 only if "print_hex_data()" won't be called. */
2500 if (!print_line(print_stream, 0, ""))
2506 proto_tree_write_pdml(edt, stdout);
2508 return !ferror(stdout);
2511 /* Just fill in the columns. */
2512 epan_dissect_fill_in_columns(edt);
2514 /* Now print them. */
2515 switch (output_action) {
2518 if (!print_columns(cf))
2523 proto_tree_write_psml(edt, stdout);
2524 return !ferror(stdout);
2528 if (!print_hex_data(print_stream, edt))
2530 if (!print_line(print_stream, 0, ""))
2539 switch (output_action) {
2542 return print_finale(print_stream);
2547 write_pdml_finale(stdout);
2549 write_psml_finale(stdout);
2550 return !ferror(stdout);
2553 g_assert_not_reached();
2559 show_print_file_io_error(int err)
2564 cmdarg_err("Not all the packets could be printed because there is "
2565 "no space left on the file system.");
2570 cmdarg_err("Not all the packets could be printed because you are "
2571 "too close to, or over your disk quota.");
2576 cmdarg_err("An error occurred while printing packets: %s.",
2583 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2587 static char errmsg_errno[1024+1];
2590 /* Wiretap error. */
2593 case WTAP_ERR_NOT_REGULAR_FILE:
2594 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2597 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2598 /* Seen only when opening a capture file for reading. */
2599 errmsg = "The file \"%s\" isn't a capture file in a format Tethereal understands.";
2602 case WTAP_ERR_UNSUPPORTED:
2603 /* Seen only when opening a capture file for reading. */
2604 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2605 "The file \"%%s\" isn't a capture file in a format Tethereal understands.\n"
2608 errmsg = errmsg_errno;
2611 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2612 /* Seen only when opening a capture file for writing. */
2613 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2614 "The file \"%%s\" is a pipe, and %s capture files can't be "
2615 "written to a pipe.", wtap_file_type_string(file_type));
2616 errmsg = errmsg_errno;
2619 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2620 /* Seen only when opening a capture file for writing. */
2621 errmsg = "Tethereal doesn't support writing capture files in that format.";
2624 case WTAP_ERR_UNSUPPORTED_ENCAP:
2626 errmsg = "Tethereal can't save this capture in that format.";
2628 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2629 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2632 errmsg = errmsg_errno;
2636 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2638 errmsg = "Tethereal can't save this capture in that format.";
2640 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2643 case WTAP_ERR_BAD_RECORD:
2644 /* Seen only when opening a capture file for reading. */
2645 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2646 "The file \"%%s\" appears to be damaged or corrupt.\n"
2649 errmsg = errmsg_errno;
2652 case WTAP_ERR_CANT_OPEN:
2654 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2656 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2659 case WTAP_ERR_SHORT_READ:
2660 errmsg = "The file \"%s\" appears to have been cut short"
2661 " in the middle of a packet or other data.";
2664 case WTAP_ERR_SHORT_WRITE:
2665 errmsg = "A full header couldn't be written to the file \"%s\".";
2669 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2670 "The file \"%%s\" could not be %s: %s.",
2671 for_writing ? "created" : "opened",
2672 wtap_strerror(err));
2673 errmsg = errmsg_errno;
2677 errmsg = file_open_error_message(err, for_writing);
2682 * Open/create errors are reported with an console message in Tethereal.
2685 open_failure_message(const char *filename, int err, gboolean for_writing)
2687 fprintf(stderr, "tethereal: ");
2688 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2689 fprintf(stderr, "\n");
2693 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2697 char err_msg[2048+1];
2699 wth = wtap_open_offline(fname, err, &err_info, FALSE);
2703 /* The open succeeded. Fill in the information for this file. */
2705 /* Initialize all data structures used for dissection. */
2709 cf->f_datalen = 0; /* not used, but set it anyway */
2711 /* Set the file name because we need it to set the follow stream filter.
2712 XXX - is that still true? We need it for other reasons, though,
2714 cf->filename = g_strdup(fname);
2716 /* Indicate whether it's a permanent or temporary file. */
2717 cf->is_tempfile = is_tempfile;
2719 /* If it's a temporary capture buffer file, mark it as not saved. */
2720 cf->user_saved = !is_tempfile;
2722 cf->cd_t = wtap_file_type(cf->wth);
2724 cf->drops_known = FALSE;
2726 cf->snap = wtap_snapshot_length(cf->wth);
2727 if (cf->snap == 0) {
2728 /* Snapshot length not known. */
2729 cf->has_snap = FALSE;
2730 cf->snap = WTAP_MAX_PACKET_SIZE;
2732 cf->has_snap = TRUE;
2733 nstime_set_zero(&cf->elapsed_time);
2734 nstime_set_zero(&first_ts);
2735 nstime_set_zero(&prev_ts);
2740 g_snprintf(err_msg, sizeof err_msg,
2741 cf_open_error_message(*err, err_info, FALSE, 0), fname);
2742 cmdarg_err("%s", err_msg);
2748 * General errors are reported with an console message in Tethereal.
2751 failure_message(const char *msg_format, va_list ap)
2753 fprintf(stderr, "tethereal: ");
2754 vfprintf(stderr, msg_format, ap);
2755 fprintf(stderr, "\n");
2759 * Read errors are reported with an console message in Tethereal.
2762 read_failure_message(const char *filename, int err)
2764 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
2765 filename, strerror(err));
2769 * Report an error in command-line arguments.
2772 cmdarg_err(const char *fmt, ...)
2777 fprintf(stderr, "tethereal: ");
2778 vfprintf(stderr, fmt, ap);
2779 fprintf(stderr, "\n");
2784 * Report additional information for an error in command-line arguments.
2787 cmdarg_err_cont(const char *fmt, ...)
2792 vfprintf(stderr, fmt, ap);
2793 fprintf(stderr, "\n");
2798 /****************************************************************************************************************/
2799 /* sync pipe "dummies", needed for capture_loop.c */
2803 /** the child has opened a new capture file, notify the parent */
2805 sync_pipe_filename_to_parent(const char *filename)
2807 /* shouldn't happen */
2811 /** the child captured some new packets, notify the parent */
2813 sync_pipe_packet_count_to_parent(int packet_count)
2815 /* shouldn't happen */
2819 /** the child stopped capturing, notify the parent */
2821 sync_pipe_drops_to_parent(int drops)
2823 /* shouldn't happen */
2827 /** the child encountered an error, notify the parent */
2829 sync_pipe_errmsg_to_parent(const char *errmsg)
2834 #endif /* HAVE_LIBPCAP */
2837 /****************************************************************************************************************/
2838 /* simple_dialog "dummies", needed for capture_loop.c */
2843 char *simple_dialog_primary_start(void)
2848 char *simple_dialog_primary_end(void)
2854 /* XXX - do we need to convert the string for the console? */
2856 simple_dialog_format_message(const char *msg)
2862 #if GTK_MAJOR_VERSION < 2
2863 str = g_strdup(msg);
2865 str = xml_escape(msg);
2873 #endif /* HAVE_LIBPCAP */