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>
98 #include "capture-wpcap.h"
99 #include "capture_errs.h"
102 #include "capture_loop.h"
103 #endif /* HAVE_LIBPCAP */
104 #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\n"
205 svnversion, get_copyright_info(), comp_info_str->str,
206 runtime_info_str->str);
211 fprintf(output, "\nt%s [ -vh ] [ -DlLnpqSVx ] [ -a <capture autostop condition> ] ...\n",
213 fprintf(output, "\t[ -b <capture ring buffer option> ] ...\n");
215 fprintf(output, "\t[ -B <capture buffer size> ]\n");
217 fprintf(output, "\t[ -c <capture packet count> ]\n");
218 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
219 fprintf(output, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
220 fprintf(output, "\t[ -i <capture interface> ] [ -N <name resolving flags> ]\n");
221 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
222 fprintf(output, "\t[ -R <read (display) filter> ] [ -s <capture snaplen> ]\n");
223 fprintf(output, "\t[ -t <time stamp format> ] [ -T pdml|ps|psml|text ]\n");
224 fprintf(output, "\t[ -w <savefile> ] [ -y <capture link type> ] [ -z <statistics> ]\n");
226 fprintf(output, "\nt%s [ -vh ] [ -lnVx ]\n", PACKAGE);
227 fprintf(output, "\t[ -d %s ] ...\n", decode_as_arg_template);
228 fprintf(output, "\t[ -F <output file type> ] [ -N <name resolving flags> ]\n");
229 fprintf(output, "\t[ -o <preference setting> ] ... [ -r <infile> ]\n");
230 fprintf(output, "\t[ -R <read (display) filter> ] \t[ -t <time stamp format> ]\n");
231 fprintf(output, "\t[ -T pdml|ps|psml|text ] [ -w <savefile> ] [ -z <statistics ]\n");
233 fprintf(output, "Valid file type arguments to the \"-F\" flag:\n");
234 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
235 if (wtap_dump_can_open(i))
236 fprintf(output, "\t%s - %s\n",
237 wtap_file_type_short_string(i), wtap_file_type_string(i));
239 fprintf(output, "\tdefault is libpcap\n");
243 * For a dissector table, print on the stream described by output,
244 * its short name (which is what's used in the "-d" option) and its
248 display_dissector_table_names(char *table_name, const char *ui_name,
251 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
255 * For a dissector handle, print on the stream described by output,
256 * the filter name (which is what's used in the "-d" option) and the full
257 * name for the protocol that corresponds to this handle.
260 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
263 const gchar* proto_filter_name;
264 const gchar* proto_ui_name;
266 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
268 if (proto_id != -1) {
269 proto_filter_name = proto_get_protocol_filter_name(proto_id);
270 proto_ui_name = proto_get_protocol_name(proto_id);
271 g_assert(proto_filter_name != NULL);
272 g_assert(proto_ui_name != NULL);
274 fprintf((FILE *)output, "\t%s (%s)\n",
281 * The protocol_name_search structure is used by find_protocol_name_func()
282 * to pass parameters and store results
284 struct protocol_name_search{
285 gchar *searched_name; /* Protocol filter name we are looking for */
286 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
287 guint nb_match; /* How many dissectors matched searched_name */
289 typedef struct protocol_name_search *protocol_name_search_t;
292 * This function parses all dissectors associated with a table to find the
293 * one whose protocol has the specified filter name. It is called
294 * as a reference function in a call to dissector_table_foreach_handle.
295 * The name we are looking for, as well as the results, are stored in the
296 * protocol_name_search struct pointed to by user_data.
297 * If called using dissector_table_foreach_handle, we actually parse the
298 * whole list of dissectors.
301 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
305 const gchar *protocol_filter_name;
306 protocol_name_search_t search_info;
310 search_info = (protocol_name_search_t)user_data;
312 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
313 if (proto_id != -1) {
314 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
315 g_assert(protocol_filter_name != NULL);
316 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
318 if (search_info->nb_match == 0) {
319 /* Record this handle only if this is the first match */
320 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
322 search_info->nb_match++;
328 * Print all layer type names supported.
329 * We send the output to the stream described by the handle output.
333 fprint_all_layer_types(FILE *output)
336 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
340 * Print all protocol names supported for a specific layer type.
341 * table_name contains the layer type name in which the search is performed.
342 * We send the output to the stream described by the handle output.
346 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
349 dissector_table_foreach_handle(table_name,
350 display_dissector_names,
355 * The function below parses the command-line parameters for the decode as
356 * feature (a string pointer by cl_param).
357 * It checks the format of the command-line, searches for a matching table
358 * and dissector. If a table/dissector match is not found, we display a
359 * summary of the available tables/dissectors (on stderr) and return FALSE.
360 * If everything is fine, we get the "Decode as" preference activated,
361 * then we return TRUE.
364 add_decode_as(const gchar *cl_param)
368 gchar *decoded_param;
369 gchar *remaining_param;
371 gchar *dissector_str;
372 dissector_handle_t dissector_matching;
373 dissector_table_t table_matching;
374 ftenum_t dissector_table_selector_type;
375 struct protocol_name_search user_protocol_name;
377 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
380 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
381 g_assert(decoded_param);
382 strcpy(decoded_param, cl_param);
385 /* The lines below will parse this string (modifying it) to extract all
386 necessary information. Note that decoded_param is still needed since
387 strings are not copied - we just save pointers. */
389 /* This section extracts a layer type (table_name) from decoded_param */
390 table_name = decoded_param; /* Layer type string starts from beginning */
392 remaining_param = strchr(table_name, '=');
393 if (remaining_param == NULL) {
394 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
395 /* If the argument does not follow the template, carry on anyway to check
396 if the table name is at least correct. If remaining_param is NULL,
397 we'll exit anyway further down */
400 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
403 /* Remove leading and trailing spaces from the table name */
404 while ( table_name[0] == ' ' )
406 while ( table_name[strlen(table_name) - 1] == ' ' )
407 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
409 /* The following part searches a table matching with the layer type specified */
410 table_matching = NULL;
412 /* Look for the requested table */
413 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
414 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
417 table_matching = find_dissector_table(table_name);
418 if (!table_matching) {
419 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
423 if (!table_matching) {
424 /* Display a list of supported layer types to help the user, if the
425 specified layer type was not found */
426 cmdarg_err("Valid layer types are:");
427 fprint_all_layer_types(stderr);
429 if (remaining_param == NULL || !table_matching) {
430 /* Exit if the layer type was not found, or if no '=' separator was found
432 g_free(decoded_param);
436 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
437 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
440 remaining_param++; /* Move to the second '=' */
441 *remaining_param = '\0'; /* Remove the second '=' */
443 remaining_param++; /* Position after the layer type string */
445 /* This section extracts a selector value (selector_str) from decoded_param */
447 selector_str = remaining_param; /* Next part starts with the selector number */
449 remaining_param = strchr(selector_str, ',');
450 if (remaining_param == NULL) {
451 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
452 /* If the argument does not follow the template, carry on anyway to check
453 if the selector value is at least correct. If remaining_param is NULL,
454 we'll exit anyway further down */
457 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
460 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
462 switch (dissector_table_selector_type) {
468 /* The selector for this table is an unsigned number. Parse it as such.
469 There's no need to remove leading and trailing spaces from the
470 selector number string, because sscanf will do that for us. */
471 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
472 cmdarg_err("Invalid selector number \"%s\"", selector_str);
473 g_free(decoded_param);
480 /* The selector for this table is a string. */
484 /* There are currently no dissector tables with any types other
485 than the ones listed above. */
486 g_assert_not_reached();
489 if (remaining_param == NULL) {
490 /* Exit if no ',' separator was found (see above) */
491 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
492 fprint_all_protocols_for_layer_types(stderr, table_name);
493 g_free(decoded_param);
497 remaining_param++; /* Position after the selector number string */
499 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
501 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
503 /* Remove leading and trailing spaces from the dissector name */
504 while ( dissector_str[0] == ' ' )
506 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
507 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
509 dissector_matching = NULL;
511 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
512 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 */
513 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
516 user_protocol_name.nb_match = 0;
517 user_protocol_name.searched_name = dissector_str;
518 user_protocol_name.matched_handle = NULL;
520 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 */
522 if (user_protocol_name.nb_match != 0) {
523 dissector_matching = user_protocol_name.matched_handle;
524 if (user_protocol_name.nb_match > 1) {
525 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
529 /* OK, check whether the problem is that there isn't any such
530 protocol, or that there is but it's not specified as a protocol
531 that's valid for that dissector table.
532 Note, we don't exit here, but dissector_matching will remain NULL,
534 if (proto_get_id_by_filter_name(dissector_str) == -1) {
535 /* No such protocol */
536 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
538 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
539 dissector_str, table_name);
544 if (!dissector_matching) {
545 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
546 fprint_all_protocols_for_layer_types(stderr, table_name);
547 g_free(decoded_param);
551 /* This is the end of the code that parses the command-line options.
552 All information is now stored in the variables:
556 The above variables that are strings are still pointing to areas within
557 decoded_parm. decoded_parm thus still needs to be kept allocated in
558 until we stop needing these variables
559 decoded_param will be deallocated at each exit point of this function */
562 /* We now have a pointer to the handle for the requested dissector
563 (requested protocol) inside the variable dissector_matching */
564 switch (dissector_table_selector_type) {
570 /* The selector for this table is an unsigned number. */
571 dissector_change(table_name, selector, dissector_matching);
576 /* The selector for this table is a string. */
577 dissector_change_string(table_name, selector_str, dissector_matching);
581 /* There are currently no dissector tables with any types other
582 than the ones listed above. */
583 g_assert_not_reached();
585 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
590 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
591 const gchar *message _U_, gpointer user_data _U_)
596 output_file_description(const char *fname)
598 char *save_file_string;
600 /* Get a string that describes what we're writing to */
601 if (*fname == '\0') {
602 /* We're writing to the standard output */
603 save_file_string = g_strdup("standard output");
605 /* We're writing to a file with the name in save_file */
606 save_file_string = g_strdup_printf("file \"%s\"", fname);
608 return save_file_string;
612 main(int argc, char *argv[])
616 gboolean arg_error = FALSE;
622 char *gpf_path, *pf_path;
623 char *gdp_path, *dp_path;
624 int gpf_open_errno, gpf_read_errno;
625 int pf_open_errno, pf_read_errno;
626 int gdp_open_errno, gdp_read_errno;
627 int dp_open_errno, dp_read_errno;
630 gboolean capture_filter_specified = FALSE;
631 gboolean list_link_layer_types = FALSE;
632 gboolean start_capture = FALSE;
634 gboolean capture_option_specified = FALSE;
636 gboolean quiet = FALSE;
637 gchar *save_file = NULL;
638 int out_file_type = WTAP_FILE_PCAP;
639 gchar *cf_name = NULL, *rfilter = NULL;
640 #ifdef HAVE_PCAP_OPEN_DEAD
641 struct bpf_program fcode;
643 dfilter_t *rfcode = NULL;
646 GLogLevelFlags log_flags;
648 #define OPTSTRING_INIT "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vVw:xy:z:"
651 #define OPTSTRING_WIN32 "B:"
653 #define OPTSTRING_WIN32 ""
656 #define OPTSTRING_WIN32 ""
657 #endif /* HAVE_LIBPCAP */
659 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
661 /* nothing more than the standard GLib handler, but without a warning */
664 G_LOG_LEVEL_CRITICAL|
669 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
671 g_log_set_handler(NULL,
673 log_func_ignore, NULL /* user_data */);
674 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
676 log_func_ignore, NULL /* user_data */);
678 /* initialize memory allocation subsystem */
683 capture_opts_init(&capture_opts, NULL /* cfile */);
686 timestamp_set_type(TS_RELATIVE);
687 timestamp_set_precision(TS_PREC_AUTO);
689 /* Register all dissectors; we must do this before checking for the
690 "-G" flag, as the "-G" flag dumps information registered by the
691 dissectors, and we must do it before we read the preferences, in
692 case any dissectors register preferences. */
693 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
694 failure_message,open_failure_message,read_failure_message);
696 /* Register all tap listeners; we do this before we parse the arguments,
697 as the "-z" argument can specify a registered tap. */
699 /* we register the plugin taps before the other taps because
700 stats_tree taps plugins will be registered as tap listeners
701 by stats_tree_stat.c and need to registered before that */
703 register_all_plugin_tap_listeners();
705 register_all_tap_listeners();
707 /* Now register the preferences for any non-dissector modules.
708 We must do that before we read the preferences as well. */
709 prefs_register_modules();
711 /* If invoked with the "-G" flag, we dump out information based on
712 the argument to the "-G" flag; if no argument is specified,
713 for backwards compatibility we dump out a glossary of display
716 XXX - we do this here, for now, to support "-G" with no arguments.
717 If none of our build or other processes uses "-G" with no arguments,
718 we can just process it with the other arguments. */
719 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
721 proto_registrar_dump_fields(1);
723 if (strcmp(argv[2], "fields") == 0)
724 proto_registrar_dump_fields(1);
725 else if (strcmp(argv[2], "fields2") == 0)
726 proto_registrar_dump_fields(2);
727 else if (strcmp(argv[2], "fields3") == 0)
728 proto_registrar_dump_fields(3);
729 else if (strcmp(argv[2], "protocols") == 0)
730 proto_registrar_dump_protocols();
731 else if (strcmp(argv[2], "values") == 0)
732 proto_registrar_dump_values();
733 else if (strcmp(argv[2], "decodes") == 0)
734 dissector_dump_decodes();
735 else if (strcmp(argv[2], "defaultprefs") == 0)
737 else if (strcmp(argv[2], "currentprefs") == 0) {
738 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
739 &pf_open_errno, &pf_read_errno, &pf_path);
742 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
749 /* Set the C-language locale to the native environment. */
750 setlocale(LC_ALL, "");
752 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
753 &pf_open_errno, &pf_read_errno, &pf_path);
754 if (gpf_path != NULL) {
755 if (gpf_open_errno != 0) {
756 cmdarg_err("Can't open global preferences file \"%s\": %s.",
757 pf_path, strerror(gpf_open_errno));
759 if (gpf_read_errno != 0) {
760 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
761 pf_path, strerror(gpf_read_errno));
764 if (pf_path != NULL) {
765 if (pf_open_errno != 0) {
766 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
767 strerror(pf_open_errno));
769 if (pf_read_errno != 0) {
770 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
771 pf_path, strerror(pf_read_errno));
777 /* Set the name resolution code's flags from the preferences. */
778 g_resolv_flags = prefs->name_resolve;
780 /* Read the disabled protocols file. */
781 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
782 &dp_path, &dp_open_errno, &dp_read_errno);
783 if (gdp_path != NULL) {
784 if (gdp_open_errno != 0) {
786 "Could not open global disabled protocols file\n\"%s\": %s.",
787 gdp_path, strerror(gdp_open_errno));
789 if (gdp_read_errno != 0) {
791 "I/O error reading global disabled protocols file\n\"%s\": %s.",
792 gdp_path, strerror(gdp_read_errno));
796 if (dp_path != NULL) {
797 if (dp_open_errno != 0) {
799 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
800 strerror(dp_open_errno));
802 if (dp_read_errno != 0) {
804 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
805 strerror(dp_read_errno));
811 /* Load Wpcap, if possible */
815 init_cap_file(&cfile);
817 /* Assemble the compile-time version information string */
818 comp_info_str = g_string_new("Compiled ");
819 get_compiled_version_info(comp_info_str);
821 /* Assemble the run-time version information string */
822 runtime_info_str = g_string_new("Running ");
823 get_runtime_version_info(runtime_info_str);
825 /* Print format defaults to this. */
826 print_format = PR_FMT_TEXT;
828 /* Now get our args */
829 while ((opt = getopt(argc, argv, optstring)) != -1) {
831 case 'a': /* autostop criteria */
832 case 'b': /* Ringbuffer option */
833 case 'c': /* Capture xxx packets */
834 case 'f': /* capture filter */
835 case 'i': /* Use interface xxx */
836 case 'p': /* Don't capture in promiscuous mode */
837 case 's': /* Set the snapshot (capture) length */
838 case 'y': /* Set the pcap data link type */
840 case 'B': /* Buffer size */
843 capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
845 capture_option_specified = TRUE;
849 case 'd': /* Decode as rule */
850 if (!add_decode_as(optarg))
853 case 'D': /* Print a list of capture devices and exit */
855 capture_opts_list_interfaces();
858 capture_option_specified = TRUE;
863 out_file_type = wtap_short_string_to_file_type(optarg);
864 if (out_file_type < 0) {
865 cmdarg_err("\"%s\" isn't a valid capture file type",
870 case 'h': /* Print help and exit */
874 case 'l': /* "Line-buffer" standard output */
875 /* This isn't line-buffering, strictly speaking, it's just
876 flushing the standard output after the information for
877 each packet is printed; however, that should be good
878 enough for all the purposes to which "-l" is put (and
879 is probably actually better for "-V", as it does fewer
882 See the comment in "process_packet()" for an explanation of
883 why we do that, and why we don't just use "setvbuf()" to
884 make the standard output line-buffered (short version: in
885 Windows, "line-buffered" is the same as "fully-buffered",
886 and the output buffer is only flushed when it fills up). */
887 line_buffered = TRUE;
889 case 'L': /* Print list of link-layer types and exit */
891 list_link_layer_types = TRUE;
894 capture_option_specified = TRUE;
898 case 'n': /* No name resolution */
899 g_resolv_flags = RESOLV_NONE;
901 case 'N': /* Select what types of addresses/port #s to resolve */
902 if (g_resolv_flags == RESOLV_ALL)
903 g_resolv_flags = RESOLV_NONE;
904 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
905 if (badopt != '\0') {
906 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
911 case 'o': /* Override preference from command line */
912 switch (prefs_set_pref(optarg)) {
914 case PREFS_SET_SYNTAX_ERR:
915 cmdarg_err("Invalid -o flag \"%s\"", optarg);
919 case PREFS_SET_NO_SUCH_PREF:
920 case PREFS_SET_OBSOLETE:
921 cmdarg_err("-o flag \"%s\" specifies unknown preference",
927 case 'q': /* Quiet */
930 case 'r': /* Read capture file xxx */
931 cf_name = g_strdup(optarg);
933 case 'R': /* Read file filter */
936 case 'S': /* show packets in real time */
937 print_packet_info = TRUE;
939 case 't': /* Time stamp type */
940 if (strcmp(optarg, "r") == 0)
941 timestamp_set_type(TS_RELATIVE);
942 else if (strcmp(optarg, "a") == 0)
943 timestamp_set_type(TS_ABSOLUTE);
944 else if (strcmp(optarg, "ad") == 0)
945 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
946 else if (strcmp(optarg, "d") == 0)
947 timestamp_set_type(TS_DELTA);
949 cmdarg_err("Invalid time stamp type \"%s\"",
951 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
952 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
956 case 'T': /* printing Type */
957 if (strcmp(optarg, "text") == 0) {
958 output_action = WRITE_TEXT;
959 print_format = PR_FMT_TEXT;
960 } else if (strcmp(optarg, "ps") == 0) {
961 output_action = WRITE_TEXT;
962 print_format = PR_FMT_PS;
963 } else if (strcmp(optarg, "pdml") == 0) {
964 output_action = WRITE_XML;
966 } else if (strcmp(optarg, "psml") == 0) {
967 output_action = WRITE_XML;
970 cmdarg_err("Invalid -T parameter.");
971 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", or \"psml\".");
975 case 'v': /* Show version and exit */
976 printf("t" PACKAGE " " VERSION "%s\n"
983 svnversion, get_copyright_info(), comp_info_str->str,
984 runtime_info_str->str);
987 case 'w': /* Write to capture file xxx */
988 save_file = g_strdup(optarg);
990 case 'V': /* Verbose */
993 case 'x': /* Print packet data in hex (and ASCII) */
997 /* We won't call the init function for the stat this soon
998 as it would disallow MATE's fields (which are registered
999 by the preferences set callback) from being used as
1000 part of a tap filter. Instead, we just add the argument
1001 to a list of stat arguments. */
1002 if (!process_stat_cmd_arg(optarg)) {
1003 cmdarg_err("invalid -z argument.");
1004 cmdarg_err_cont(" -z argument must be one of :");
1005 list_stat_cmd_args();
1010 case '?': /* Bad flag - print usage message */
1016 /* If no capture filter or read filter has been specified, and there are
1017 still command-line arguments, treat them as the tokens of a capture
1018 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1019 flag was specified. */
1020 if (optind < argc) {
1021 if (cf_name != NULL) {
1022 if (rfilter != NULL) {
1023 cmdarg_err("Read filters were specified both with \"-R\" "
1024 "and with additional command-line arguments");
1027 rfilter = get_args_as_string(argc, argv, optind);
1030 if (capture_filter_specified) {
1031 cmdarg_err("Capture filters were specified both with \"-f\""
1032 " and with additional command-line arguments");
1035 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1037 capture_option_specified = TRUE;
1042 /* See if we're writing a capture file and the file is a pipe */
1044 ld.output_to_pipe = FALSE;
1046 if (save_file != NULL) {
1047 /* We're writing to a capture file. */
1048 if (strcmp(save_file, "-") == 0) {
1049 /* Write to the standard output.
1050 If we'll also be writing dissected packets to the standard
1051 output, reject the request. At best, we could redirect that
1052 to the standard error; we *can't* write both to the standard
1053 output and have either of them be useful. */
1054 if (print_packet_info) {
1055 cmdarg_err("You can't write both raw packet data and dissected packets"
1056 " to the standard error.");
1060 save_file = g_strdup("");
1062 /* XXX - should we check whether it's a pipe? It's arguably
1063 silly to do "-w - >output_file" rather than "-w output_file",
1064 but by not checking we might be violating the Principle Of
1065 Least Astonishment. */
1066 ld.output_to_pipe = TRUE;
1071 err = test_for_fifo(save_file);
1074 case ENOENT: /* it doesn't exist, so we'll be creating it,
1075 and it won't be a FIFO */
1076 case 0: /* found it, but it's not a FIFO */
1079 case ESPIPE: /* it is a FIFO */
1080 ld.output_to_pipe = TRUE;
1083 default: /* couldn't stat it */
1084 cmdarg_err("Error testing whether capture file is a pipe: %s",
1091 /* We're not writing to a file, so we should print packet information
1092 unless "-q" was specified. */
1094 print_packet_info = TRUE;
1097 #ifndef HAVE_LIBPCAP
1098 if (capture_option_specified)
1099 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1106 /* We don't support capture filters when reading from a capture file
1107 (the BPF compiler doesn't support all link-layer types that we
1108 support in capture files we read). */
1110 if (cf_name != NULL) {
1111 if (capture_filter_specified) {
1112 cmdarg_err("Only read filters, not capture filters, "
1113 "can be specified when reading a capture file.");
1120 if (output_action != WRITE_TEXT) {
1121 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1127 if (list_link_layer_types) {
1128 /* We're supposed to list the link-layer types for an interface;
1129 did the user also specify a capture file to be read? */
1131 /* Yes - that's bogus. */
1132 cmdarg_err("You can't specify -L and a capture file to be read.");
1135 /* No - did they specify a ring buffer option? */
1136 if (capture_opts.multi_files_on) {
1137 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1141 /* If they didn't specify a "-w" flag, but specified a maximum capture
1142 file size, tell them that this doesn't work, and exit. */
1143 if (capture_opts.has_autostop_filesize && save_file == NULL) {
1144 cmdarg_err("Maximum capture file size specified, but "
1145 "capture isn't being saved to a file.");
1149 if (capture_opts.multi_files_on) {
1150 /* Multiple-file mode works only under certain conditions:
1151 a) it doesn't work if you're not saving the capture to a file;
1152 b) it doesn't work if you're writing to the standard output;
1153 c) it doesn't work if you're writing to a pipe;
1154 d) it only works if you're saving in libpcap format;
1155 e) it makes no sense if the maximum file size is set to "infinite"
1156 (XXX - shouldn't that be "if there is no stop criterion",
1157 as you might want to switch files based on a packet count
1159 if (save_file == NULL) {
1160 cmdarg_err("Multiple capture files requested, but "
1161 "the capture isn't being saved to a file.");
1164 if (strcmp(save_file, "") == 0) {
1165 cmdarg_err("Multiple capture files requested, but "
1166 "the capture is being written to the standard output.");
1169 if (ld.output_to_pipe) {
1170 cmdarg_err("Multiple capture files requested, but "
1171 "the capture file is a pipe.");
1174 if (out_file_type != WTAP_FILE_PCAP) {
1175 cmdarg_err("Multiple capture files requested, but "
1176 "the capture isn't being saved in libpcap format.");
1179 if (!capture_opts.has_autostop_filesize) {
1180 cmdarg_err("Multiple capture files requested, but "
1181 "no maximum capture file size was specified.");
1189 /* Start windows sockets */
1190 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1193 /* Notify all registered modules that have had any of their preferences
1194 changed either from one of the preferences file or from the command
1195 line that their preferences have changed. */
1198 /* At this point MATE will have registered its field array so we can
1199 have a tap filter with one of MATE's late-registered fields as part
1200 of the filter. We can now process all the "-z" arguments. */
1201 start_requested_stats();
1203 /* disabled protocols as per configuration file */
1204 if (gdp_path == NULL && dp_path == NULL) {
1205 set_disabled_protos_list();
1208 /* Build the column format array */
1209 col_setup(&cfile.cinfo, prefs->num_cols);
1210 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1211 cfile.cinfo.col_fmt[i] = get_column_format(i);
1212 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1213 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1215 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1216 cfile.cinfo.col_data[i] = NULL;
1217 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1218 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1220 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1221 cfile.cinfo.col_fence[i] = 0;
1222 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1223 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1226 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1229 for (j = 0; j < NUM_COL_FMTS; j++) {
1230 if (!cfile.cinfo.fmt_matx[i][j])
1233 if (cfile.cinfo.col_first[j] == -1)
1234 cfile.cinfo.col_first[j] = i;
1235 cfile.cinfo.col_last[j] = i;
1240 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1241 capture_opts_trim_ring_num_files(&capture_opts);
1244 if (rfilter != NULL) {
1245 if (!dfilter_compile(rfilter, &rfcode)) {
1246 cmdarg_err("%s", dfilter_error_msg);
1248 #ifdef HAVE_PCAP_OPEN_DEAD
1252 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1254 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1256 " Note: That display filter code looks like a valid capture filter;");
1258 " maybe you mixed them up?");
1267 cfile.rfcode = rfcode;
1269 if (print_packet_info) {
1270 /* If we're printing as text or PostScript, we have
1271 to create a print stream. */
1272 if (output_action == WRITE_TEXT) {
1273 switch (print_format) {
1276 print_stream = print_stream_text_stdio_new(stdout);
1280 print_stream = print_stream_ps_stdio_new(stdout);
1284 g_assert_not_reached();
1289 /* We have to dissect each packet if:
1291 we're printing information about each packet;
1293 we're using a read filter on the packets;
1295 we're using any taps. */
1296 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1300 * We're reading a capture file.
1305 * Immediately relinquish any set-UID or set-GID privileges we have;
1306 * we must not be allowed to read any capture files the user running
1307 * Tethereal can't open.
1313 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1318 /* Set timestamp precision; there should arguably be a command-line
1319 option to let the user set this. */
1320 switch(wtap_file_tsprecision(cfile.wth)) {
1321 case(WTAP_FILE_TSPREC_SEC):
1322 timestamp_set_precision(TS_PREC_AUTO_SEC);
1324 case(WTAP_FILE_TSPREC_DSEC):
1325 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1327 case(WTAP_FILE_TSPREC_CSEC):
1328 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1330 case(WTAP_FILE_TSPREC_MSEC):
1331 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1333 case(WTAP_FILE_TSPREC_USEC):
1334 timestamp_set_precision(TS_PREC_AUTO_USEC);
1336 case(WTAP_FILE_TSPREC_NSEC):
1337 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1340 g_assert_not_reached();
1343 /* Process the packets in the file */
1344 err = load_cap_file(&cfile, save_file, out_file_type);
1351 /* No capture file specified, so we're supposed to do a live capture
1352 (or get a list of link-layer types for a live capture device);
1353 do we have support for live captures? */
1360 cmdarg_err("WinPcap couldn't be found.");
1361 detailed_err = cant_load_winpcap_err("Tethereal");
1362 cmdarg_err_cont("%s", detailed_err);
1363 g_free(detailed_err);
1368 /* trim the interface name and exit if that failed */
1369 if (!capture_opts_trim_iface(&capture_opts,
1370 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1374 /* if requested, list the link layer types and exit */
1375 if (list_link_layer_types) {
1376 capture_opts_list_link_layer_types(&capture_opts);
1382 * The user didn't ask us not to print a count of packets as
1383 * they arrive, so do so.
1385 print_packet_counts = TRUE;
1388 /* For now, assume libpcap gives microsecond precision. */
1389 timestamp_set_precision(TS_PREC_AUTO_USEC);
1391 capture(save_file, out_file_type);
1393 if (capture_opts.multi_files_on) {
1397 /* No - complain. */
1398 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1403 draw_tap_listeners(TRUE);
1410 /* Do the low-level work of a capture.
1411 Returns TRUE if it succeeds, FALSE otherwise. */
1413 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1416 capture(char *save_file, int out_file_type)
1419 int volatile volatile_err = 0;
1420 int volatile inpkts = 0;
1422 char errmsg[1024+1];
1423 condition *volatile cnd_autostop_size = NULL;
1424 condition *volatile cnd_autostop_duration = NULL;
1427 void (*oldhandler)(int);
1428 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1430 struct pcap_stat stats;
1435 /* Initialize all data structures used for dissection. */
1438 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1440 ld.packet_cb = capture_pcap_cb;
1443 /* open the "input file" from network interface or capture pipe */
1444 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg)))
1451 * We've opened the capture device, so, if we're set-UID or set-GID,
1452 * relinquish those privileges.
1454 * XXX - if we have saved set-user-ID support, we should give up those
1455 * privileges immediately, and then reclaim them long enough to get
1456 * a list of network interfaces and to open one, and then give them
1457 * up again, so that stuff we do while processing the argument list,
1458 * reading the user's preferences, etc. is done as the real user and
1459 * group, not the effective user and group.
1465 capture_opts.save_file = save_file;
1467 /* open the output file (temporary/specified name/ringbuffer) */
1468 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1472 /* init the input filter from the network interface (capture pipe will do nothing) */
1473 if(!capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe,
1474 capture_opts.iface, capture_opts.cfilter, errmsg, sizeof errmsg))
1479 /* open the wiretap part of the output file (the output file is already open) */
1480 if(!capture_loop_init_wiretap_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg))
1485 /* Save the capture file name. */
1486 ld.save_file = capture_opts.save_file;
1489 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1490 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1492 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1494 XXX - deal with signal semantics on various UNIX platforms. Or just
1495 use "sigaction()" and be done with it? */
1496 signal(SIGTERM, capture_cleanup);
1497 signal(SIGINT, capture_cleanup);
1498 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1499 signal(SIGHUP, oldhandler);
1502 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1503 quiet mode, report the number of packets we've captured. */
1504 signal(SIGINFO, report_counts_siginfo);
1505 #endif /* SIGINFO */
1508 /* Let the user know what interface was chosen. */
1509 descr = get_interface_descriptive_name(capture_opts.iface);
1510 fprintf(stderr, "Capturing on %s\n", descr);
1513 /* initialize capture stop conditions */
1514 init_capture_stop_conditions();
1515 /* create stop conditions */
1516 if (capture_opts.has_autostop_filesize)
1517 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1518 (long)capture_opts.autostop_filesize * 1024);
1519 if (capture_opts.has_autostop_duration)
1520 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1521 (gint32)capture_opts.autostop_duration);
1523 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1524 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT,
1525 capture_opts.file_duration);
1527 if (!setjmp(ld.stopenv)) {
1529 ld.packet_count = 0;
1534 /* We need to be careful with automatic variables defined in the
1535 outer scope which are changed inside the loop. Most compilers
1536 don't try to roll them back to their original values after the
1537 longjmp which causes the loop to finish, but all that the
1538 standards say is that their values are indeterminate. If we
1539 don't want them to be rolled back, we should define them with the
1540 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1541 Programming in the UNIX Environment, p. 178).
1543 The "err" variable causes a particular problem. If we give it
1544 the volatile attribute, then when we pass a reference to it (as
1545 in "&err") to a function, GCC warns: "passing arg <n> of
1546 <function> discards qualifiers from pointer target type".
1547 Therefore within the loop and just beyond we don't use "err".
1548 Within the loop we define "loop_err", and assign its value to
1549 "volatile_err", which is in the outer scope and is checked when
1552 We also define "packet_count_prev" here to keep things tidy,
1553 since it's used only inside the loop. If it were defined in the
1554 outer scope, GCC would give a warning (unnecessary in this case)
1555 that it might be clobbered, and we'd need to give it the volatile
1556 attribute to suppress the warning. */
1559 int packet_count_prev = 0;
1561 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1562 /* We're not stopping at a particular capture file size, and we're
1563 not stopping after some particular amount of time has expired,
1564 so either we have no stop condition or the only stop condition
1565 is a maximum packet count.
1567 If there's no maximum packet count, pass it -1, meaning "until
1568 you run out of packets in the bufferful you read". Otherwise,
1569 pass it the number of packets we have left to capture.
1571 We don't call "pcap_loop()" as, if we're saving to a file that's
1572 a FIFO, we want to flush the FIFO after we're done processing
1573 this libpcap bufferful of packets, so that the program
1574 reading the FIFO sees the packets immediately and doesn't get
1575 any partial packet, forcing it to block in the middle of reading
1577 if (capture_opts.autostop_packets == 0)
1580 if (ld.packet_count >= capture_opts.autostop_packets) {
1581 /* XXX do we need this test here? */
1582 /* It appears there's nothing more to capture. */
1585 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1588 /* We need to check the capture file size or the timeout after
1593 if (ld.from_cap_pipe) {
1594 inpkts = cap_pipe_dispatch(ld.cap_pipe_fd, &ld, &ld.cap_pipe_hdr, &ld.cap_pipe_rechdr, pcap_data,
1595 errmsg, sizeof errmsg);
1598 inpkts = pcap_dispatch(ld.pcap_h, pcap_cnt, capture_pcap_cb, (u_char *) &ld);
1600 /* Error from "pcap_dispatch()", or error or "no more packets" from
1601 "cap_pipe_dispatch(). */
1603 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1604 /* The specified capture time has elapsed; stop the capture. */
1606 } else if (inpkts > 0) {
1607 if (capture_opts.autostop_packets != 0 &&
1608 ld.packet_count >= capture_opts.autostop_packets) {
1609 /* The specified number of packets have been captured and have
1610 passed both any capture filter in effect and any read filter
1613 } else if (cnd_autostop_size != NULL &&
1614 cnd_eval(cnd_autostop_size,
1615 (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))) {
1616 /* We're saving the capture to a file, and the capture file reached
1617 its maximum size. */
1618 if (capture_opts.multi_files_on) {
1619 /* Switch to the next ringbuffer file */
1620 if (ringbuf_switch_file(&ld.wtap_pdh, &save_file, &save_file_fd, &loop_err)) {
1621 /* File switch succeeded: reset the condition */
1622 cnd_reset(cnd_autostop_size);
1623 if (cnd_file_duration) {
1624 cnd_reset(cnd_file_duration);
1627 /* File switch failed: stop here */
1628 volatile_err = loop_err;
1632 /* No ringbuffer - just stop. */
1636 if (ld.output_to_pipe) {
1637 if (ld.packet_count > packet_count_prev) {
1638 wtap_dump_flush(ld.wtap_pdh);
1639 packet_count_prev = ld.packet_count;
1643 } /* while (ld.go) */
1645 /* delete stop conditions */
1646 if (cnd_autostop_size != NULL)
1647 cnd_delete(cnd_autostop_size);
1648 if (cnd_autostop_duration != NULL)
1649 cnd_delete(cnd_autostop_duration);
1650 if (cnd_file_duration != NULL)
1651 cnd_delete(cnd_file_duration);
1653 if (print_packet_counts) {
1654 /* We're printing packet counts to stderr.
1655 Send a newline so that we move to the line after the packet count. */
1656 fprintf(stderr, "\n");
1659 /* If we got an error while capturing, report it. */
1662 if (ld.from_cap_pipe) {
1663 if (ld.cap_pipe_err == PIPERR) {
1664 cmdarg_err("Error while capturing packets: %s",
1670 cmdarg_err("Error while capturing packets: %s",
1671 pcap_geterr(ld.pcap_h));
1675 if (volatile_err == 0)
1678 show_capture_file_io_error(save_file, volatile_err, FALSE);
1682 if (save_file != NULL) {
1683 /* We're saving to a file or files; close all files. */
1684 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1686 /* If we've displayed a message about a write error, there's no point
1687 in displaying another message about an error on close. */
1688 if (!close_ok && write_ok)
1689 show_capture_file_io_error(save_file, err, TRUE);
1693 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1694 eth_close(ld.cap_pipe_fd);
1698 /* Get the capture statistics, and, if any packets were dropped, report
1700 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1701 if (stats.ps_drop != 0) {
1702 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1705 cmdarg_err("Can't get packet-drop statistics: %s",
1706 pcap_geterr(ld.pcap_h));
1708 pcap_close(ld.pcap_h);
1711 /* Report the number of captured packets if not reported during capture
1712 and we are saving to a file. */
1718 if (capture_opts.multi_files_on) {
1719 ringbuf_error_cleanup();
1723 cmdarg_err("%s", errmsg);
1725 if (ld.from_cap_pipe) {
1726 if (ld.cap_pipe_fd >= 0)
1727 eth_close(ld.cap_pipe_fd);
1731 if (ld.pcap_h != NULL)
1732 pcap_close(ld.pcap_h);
1739 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1742 struct wtap_pkthdr whdr;
1743 union wtap_pseudo_header pseudo_header;
1744 loop_data *ld = (loop_data *) user;
1749 /* Convert from libpcap to Wiretap format.
1750 If that fails, ignore the packet (wtap_process_pcap_packet has
1751 written an error message). */
1752 pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1759 * Prevent a SIGINFO handler from writing to stdout while we're
1760 * doing so; instead, have it just set a flag telling us to print
1761 * that information when we're done.
1764 #endif /* SIGINFO */
1766 /* The current packet may have arrived after a very long silence,
1767 * way past the time to switch files. In order not to have
1768 * the first packet of a new series of events as the last
1769 * [or only] packet in the file, switch before writing!
1771 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1772 /* time elapsed for this ring file, switch to the next */
1773 if (ringbuf_switch_file(&ld->wtap_pdh, &ld->save_file, &save_file_fd, &loop_err)) {
1774 /* File switch succeeded: reset the condition */
1775 cnd_reset(cnd_file_duration);
1777 /* File switch failed: stop here */
1778 /* XXX - we should do something with "loop_err" */
1783 if (!process_packet(&cfile, ld->wtap_pdh, 0, &whdr, &pseudo_header, pd, &err)) {
1784 /* Error writing to a capture file */
1785 if (print_packet_counts) {
1786 /* We're printing counts of packets captured; move to the line after
1788 fprintf(stderr, "\n");
1790 show_capture_file_io_error(ld->save_file, err, FALSE);
1791 pcap_close(ld->pcap_h);
1792 wtap_dump_close(ld->wtap_pdh, &err);
1798 * Allow SIGINFO handlers to write.
1803 * If a SIGINFO handler asked us to write out capture counts, do so.
1807 #endif /* SIGINFO */
1812 capture_cleanup(DWORD ctrltype _U_)
1814 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1815 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1816 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1817 like SIGTERM at least when the machine's shutting down.
1819 For now, we handle them all as indications that we should clean up
1820 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1823 However, as handlers run in a new thread, we can't just longjmp
1824 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1825 no other handler - such as one that would terminate the process -
1828 XXX - for some reason, typing ^C to Tethereal, if you run this in
1829 a Cygwin console window in at least some versions of Cygwin,
1830 causes Tethereal to terminate immediately; this routine gets
1831 called, but the main loop doesn't get a chance to run and
1832 exit cleanly, at least if this is compiled with Microsoft Visual
1833 C++ (i.e., it's a property of the Cygwin console window or Bash;
1834 it happens if Tethereal is not built with Cygwin - for all I know,
1835 building it with Cygwin may make the problem go away). */
1841 capture_cleanup(int signum _U_)
1843 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1844 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1845 "ld.go" to FALSE and return, we won't break out of it and quit
1847 longjmp(ld.stopenv, 1);
1855 /* XXX - if we use sigaction, this doesn't have to be done.
1856 (Yes, this isn't necessary on BSD, but just in case a system
1857 where "signal()" has AT&T semantics adopts SIGINFO....) */
1858 signal(SIGINFO, report_counts_siginfo);
1859 #endif /* SIGINFO */
1861 if (!print_packet_counts) {
1862 /* Report the count only if we aren't printing a packet count
1863 as packets arrive. */
1864 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1867 infoprint = FALSE; /* we just reported it */
1868 #endif /* SIGINFO */
1873 report_counts_siginfo(int signum _U_)
1875 int sav_errno = errno;
1876 /* If we've been told to delay printing, just set a flag asking
1877 that we print counts (if we're supposed to), otherwise print
1878 the count of packets captured (if we're supposed to). */
1885 #endif /* SIGINFO */
1886 #endif /* HAVE_LIBPCAP */
1889 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
1892 int snapshot_length;
1897 char *save_file_string = NULL;
1899 linktype = wtap_file_encap(cf->wth);
1900 if (save_file != NULL) {
1901 /* Get a string that describes what we're writing to */
1902 save_file_string = output_file_description(save_file);
1904 /* Set up to write to the capture file. */
1905 snapshot_length = wtap_snapshot_length(cf->wth);
1906 if (snapshot_length == 0) {
1907 /* Snapshot length of input file not known. */
1908 snapshot_length = WTAP_MAX_PACKET_SIZE;
1910 pdh = wtap_dump_open(save_file, out_file_type,
1911 linktype, snapshot_length, FALSE /* compressed */, &err);
1914 /* We couldn't set up to write to the capture file. */
1917 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1918 cmdarg_err("Capture files can't be written in that format.");
1921 case WTAP_ERR_UNSUPPORTED_ENCAP:
1922 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1923 cmdarg_err("The capture file being read can't be written in "
1927 case WTAP_ERR_CANT_OPEN:
1928 cmdarg_err("The %s couldn't be created for some "
1929 "unknown reason.", save_file_string);
1932 case WTAP_ERR_SHORT_WRITE:
1933 cmdarg_err("A full header couldn't be written to the %s.",
1938 cmdarg_err("The %s could not be created: %s.", save_file_string,
1939 wtap_strerror(err));
1945 if (print_packet_info) {
1946 if (!write_preamble(cf)) {
1948 show_print_file_io_error(err);
1954 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
1955 if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
1956 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
1958 /* Error writing to a capture file */
1959 show_capture_file_io_error(save_file, err, FALSE);
1960 wtap_dump_close(pdh, &err);
1965 /* Print a message noting that the read failed somewhere along the line. */
1968 case WTAP_ERR_UNSUPPORTED_ENCAP:
1969 cmdarg_err("\"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)",
1970 cf->filename, err_info);
1973 case WTAP_ERR_CANT_READ:
1974 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
1978 case WTAP_ERR_SHORT_READ:
1979 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
1983 case WTAP_ERR_BAD_RECORD:
1984 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
1985 cf->filename, err_info);
1989 cmdarg_err("An error occurred while reading \"%s\": %s.",
1990 cf->filename, wtap_strerror(err));
1993 if (save_file != NULL) {
1994 /* Now close the capture file. */
1995 if (!wtap_dump_close(pdh, &err))
1996 show_capture_file_io_error(save_file, err, TRUE);
1999 if (save_file != NULL) {
2000 /* Now close the capture file. */
2001 if (!wtap_dump_close(pdh, &err))
2002 show_capture_file_io_error(save_file, err, TRUE);
2004 if (print_packet_info) {
2005 if (!write_finale()) {
2007 show_print_file_io_error(err);
2014 wtap_close(cf->wth);
2017 if (save_file_string != NULL)
2018 g_free(save_file_string);
2024 fill_in_fdata(frame_data *fdata, capture_file *cf,
2025 const struct wtap_pkthdr *phdr, long offset)
2030 fdata->num = cf->count;
2031 fdata->pkt_len = phdr->len;
2032 cum_bytes += phdr->len;
2033 fdata->cum_bytes = cum_bytes;
2034 fdata->cap_len = phdr->caplen;
2035 fdata->file_off = offset;
2036 fdata->lnk_t = phdr->pkt_encap;
2037 fdata->abs_ts = *((nstime_t *) &phdr->ts);
2038 fdata->flags.passed_dfilter = 0;
2039 fdata->flags.encoding = CHAR_ASCII;
2040 fdata->flags.visited = 0;
2041 fdata->flags.marked = 0;
2042 fdata->flags.ref_time = 0;
2044 /* If we don't have the time stamp of the first packet in the
2045 capture, it's because this is the first packet. Save the time
2046 stamp of this packet as the time stamp of the first packet. */
2047 if (nstime_is_zero(&first_ts)) {
2048 first_ts = fdata->abs_ts;
2051 /* If we don't have the time stamp of the previous displayed packet,
2052 it's because this is the first displayed packet. Save the time
2053 stamp of this packet as the time stamp of the previous displayed
2055 if (nstime_is_zero(&prev_ts)) {
2056 prev_ts = fdata->abs_ts;
2059 /* Get the time elapsed between the first packet and this packet. */
2060 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2062 /* If it's greater than the current elapsed time, set the elapsed time
2063 to it (we check for "greater than" so as not to be confused by
2064 time moving backwards). */
2065 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2066 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2067 cf->elapsed_time = fdata->rel_ts;
2070 /* Get the time elapsed between the previous displayed packet and
2072 nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2073 prev_ts = fdata->abs_ts;
2076 /* Free up all data attached to a "frame_data" structure. */
2078 clear_fdata(frame_data *fdata)
2081 g_slist_free(fdata->pfd);
2085 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2086 const struct wtap_pkthdr *whdr,
2087 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2091 gboolean create_proto_tree;
2092 epan_dissect_t *edt;
2095 /* Count this packet. */
2098 /* If we're going to print packet information, or we're going to
2099 run a read filter, or we're going to process taps, set up to
2100 do a dissection and do so. */
2101 if (do_dissection) {
2102 fill_in_fdata(&fdata, cf, whdr, offset);
2104 if (print_packet_info) {
2105 /* Grab any resolved addresses */
2107 if (g_resolv_flags) {
2108 host_name_lookup_process(NULL);
2113 if (cf->rfcode || verbose || num_tap_filters!=0)
2114 create_proto_tree = TRUE;
2116 create_proto_tree = FALSE;
2117 /* The protocol tree will be "visible", i.e., printed, only if we're
2118 printing packet details, which is true if we're printing stuff
2119 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2121 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2123 /* If we're running a read filter, prime the epan_dissect_t with that
2126 epan_dissect_prime_dfilter(edt, cf->rfcode);
2128 tap_queue_init(edt);
2130 /* We only need the columns if we're printing packet info but we're
2131 *not* verbose; in verbose mode, we print the protocol tree, not
2132 the protocol summary. */
2133 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2134 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2136 tap_push_tapped_queue(edt);
2138 /* Run the read filter if we have one. */
2140 passed = dfilter_apply_edt(cf->rfcode, edt);
2144 /* We're not running a display filter and we're not printing any
2145 packet information, so we don't need to do a dissection, and all
2146 packets are processed. */
2152 /* Count this packet. */
2157 /* Process this packet. */
2159 /* We're writing to a capture file; write this packet. */
2160 if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2163 if (print_packet_counts) {
2164 /* We're printing packet counts. */
2165 if (ld.packet_count != 0) {
2166 fprintf(stderr, "\r%u ", ld.packet_count);
2167 /* stderr could be line buffered */
2173 if (print_packet_info) {
2174 /* We're printing packet information; print the information for
2176 print_packet(cf, edt);
2178 /* The ANSI C standard does not appear to *require* that a line-buffered
2179 stream be flushed to the host environment whenever a newline is
2180 written, it just says that, on such a stream, characters "are
2181 intended to be transmitted to or from the host environment as a
2182 block when a new-line character is encountered".
2184 The Visual C++ 6.0 C implementation doesn't do what is intended;
2185 even if you set a stream to be line-buffered, it still doesn't
2186 flush the buffer at the end of every line.
2188 So, if the "-l" flag was specified, we flush the standard output
2189 at the end of a packet. This will do the right thing if we're
2190 printing packet summary lines, and, as we print the entire protocol
2191 tree for a single packet without waiting for anything to happen,
2192 it should be as good as line-buffered mode if we're printing
2193 protocol trees. (The whole reason for the "-l" flag in either
2194 tcpdump or Tethereal is to allow the output of a live capture to
2195 be piped to a program or script and to have that script see the
2196 information for the packet as soon as it's printed, rather than
2197 having to wait until a standard I/O buffer fills up. */
2201 if (ferror(stdout)) {
2202 show_print_file_io_error(errno);
2208 if (do_dissection) {
2209 epan_dissect_free(edt);
2210 clear_fdata(&fdata);
2216 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2218 char *save_file_string;
2220 save_file_string = output_file_description(fname);
2225 cmdarg_err("Not all the packets could be written to the %s because there is "
2226 "no space left on the file system.",
2232 cmdarg_err("Not all the packets could be written to the %s because you are "
2233 "too close to, or over your disk quota.",
2238 case WTAP_ERR_CANT_CLOSE:
2239 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2243 case WTAP_ERR_SHORT_WRITE:
2244 cmdarg_err("Not all the packets could be written to the %s.",
2250 cmdarg_err("The %s could not be closed: %s.",
2251 save_file_string, wtap_strerror(err));
2253 cmdarg_err("An error occurred while writing to the %s: %s.",
2254 save_file_string, wtap_strerror(err));
2258 g_free(save_file_string);
2262 write_preamble(capture_file *cf)
2264 switch (output_action) {
2267 return print_preamble(print_stream, cf->filename);
2272 write_pdml_preamble(stdout);
2274 write_psml_preamble(stdout);
2275 return !ferror(stdout);
2278 g_assert_not_reached();
2284 get_line_buf(size_t len)
2286 static char *line_bufp = NULL;
2287 static size_t line_buf_len = 256;
2288 size_t new_line_buf_len;
2290 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2291 new_line_buf_len *= 2)
2293 if (line_bufp == NULL) {
2294 line_buf_len = new_line_buf_len;
2295 line_bufp = g_malloc(line_buf_len + 1);
2297 if (new_line_buf_len > line_buf_len) {
2298 line_buf_len = new_line_buf_len;
2299 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2306 print_columns(capture_file *cf)
2313 line_bufp = get_line_buf(256);
2316 for (i = 0; i < cf->cinfo.num_cols; i++) {
2317 switch (cf->cinfo.col_fmt[i]) {
2321 * Don't print this if we're doing a live capture from a network
2322 * interface - if we're doing a live capture, you won't be
2323 * able to look at the capture in the future (it's not being
2324 * saved anywhere), so the frame numbers are unlikely to be
2327 * (XXX - it might be nice to be able to save and print at
2328 * the same time, sort of like an "Update list of packets
2329 * in real time" capture in Ethereal.)
2331 if (capture_opts.iface != NULL)
2334 column_len = strlen(cf->cinfo.col_data[i]);
2337 line_bufp = get_line_buf(buf_offset + column_len);
2338 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2344 case COL_ABS_DATE_TIME: /* XXX - wider */
2345 column_len = strlen(cf->cinfo.col_data[i]);
2346 if (column_len < 10)
2348 line_bufp = get_line_buf(buf_offset + column_len);
2349 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2355 case COL_DEF_DL_SRC:
2356 case COL_RES_DL_SRC:
2357 case COL_UNRES_DL_SRC:
2358 case COL_DEF_NET_SRC:
2359 case COL_RES_NET_SRC:
2360 case COL_UNRES_NET_SRC:
2361 column_len = strlen(cf->cinfo.col_data[i]);
2362 if (column_len < 12)
2364 line_bufp = get_line_buf(buf_offset + column_len);
2365 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2371 case COL_DEF_DL_DST:
2372 case COL_RES_DL_DST:
2373 case COL_UNRES_DL_DST:
2374 case COL_DEF_NET_DST:
2375 case COL_RES_NET_DST:
2376 case COL_UNRES_NET_DST:
2377 column_len = strlen(cf->cinfo.col_data[i]);
2378 if (column_len < 12)
2380 line_bufp = get_line_buf(buf_offset + column_len);
2381 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2385 column_len = strlen(cf->cinfo.col_data[i]);
2386 line_bufp = get_line_buf(buf_offset + column_len);
2387 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2390 buf_offset += column_len;
2391 if (i != cf->cinfo.num_cols - 1) {
2393 * This isn't the last column, so we need to print a
2394 * separator between this column and the next.
2396 * If we printed a network source and are printing a
2397 * network destination of the same type next, separate
2398 * them with "->"; if we printed a network destination
2399 * and are printing a network source of the same type
2400 * next, separate them with "<-"; otherwise separate them
2403 * We add enough space to the buffer for " <- " or " -> ",
2404 * even if we're only adding " ".
2406 line_bufp = get_line_buf(buf_offset + 4);
2407 switch (cf->cinfo.col_fmt[i]) {
2412 switch (cf->cinfo.col_fmt[i + 1]) {
2417 strcat(line_bufp + buf_offset, " -> ");
2422 strcat(line_bufp + buf_offset, " ");
2428 case COL_DEF_DL_SRC:
2429 case COL_RES_DL_SRC:
2430 case COL_UNRES_DL_SRC:
2431 switch (cf->cinfo.col_fmt[i + 1]) {
2433 case COL_DEF_DL_DST:
2434 case COL_RES_DL_DST:
2435 case COL_UNRES_DL_DST:
2436 strcat(line_bufp + buf_offset, " -> ");
2441 strcat(line_bufp + buf_offset, " ");
2447 case COL_DEF_NET_SRC:
2448 case COL_RES_NET_SRC:
2449 case COL_UNRES_NET_SRC:
2450 switch (cf->cinfo.col_fmt[i + 1]) {
2452 case COL_DEF_NET_DST:
2453 case COL_RES_NET_DST:
2454 case COL_UNRES_NET_DST:
2455 strcat(line_bufp + buf_offset, " -> ");
2460 strcat(line_bufp + buf_offset, " ");
2469 switch (cf->cinfo.col_fmt[i + 1]) {
2474 strcat(line_bufp + buf_offset, " <- ");
2479 strcat(line_bufp + buf_offset, " ");
2485 case COL_DEF_DL_DST:
2486 case COL_RES_DL_DST:
2487 case COL_UNRES_DL_DST:
2488 switch (cf->cinfo.col_fmt[i + 1]) {
2490 case COL_DEF_DL_SRC:
2491 case COL_RES_DL_SRC:
2492 case COL_UNRES_DL_SRC:
2493 strcat(line_bufp + buf_offset, " <- ");
2498 strcat(line_bufp + buf_offset, " ");
2504 case COL_DEF_NET_DST:
2505 case COL_RES_NET_DST:
2506 case COL_UNRES_NET_DST:
2507 switch (cf->cinfo.col_fmt[i + 1]) {
2509 case COL_DEF_NET_SRC:
2510 case COL_RES_NET_SRC:
2511 case COL_UNRES_NET_SRC:
2512 strcat(line_bufp + buf_offset, " <- ");
2517 strcat(line_bufp + buf_offset, " ");
2524 strcat(line_bufp + buf_offset, " ");
2530 return print_line(print_stream, 0, line_bufp);
2534 print_packet(capture_file *cf, epan_dissect_t *edt)
2536 print_args_t print_args;
2539 /* Print the information in the protocol tree. */
2540 switch (output_action) {
2543 print_args.to_file = TRUE;
2544 print_args.format = print_format;
2545 print_args.print_summary = !verbose;
2546 print_args.print_hex = verbose && print_hex;
2547 print_args.print_formfeed = FALSE;
2548 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2550 /* init the packet range */
2551 packet_range_init(&print_args.range);
2553 if (!proto_tree_print(&print_args, edt, print_stream))
2556 /* "print_hex_data()" will put out a leading blank line, as well
2557 as a trailing one; print one here, to separate the packets,
2558 only if "print_hex_data()" won't be called. */
2559 if (!print_line(print_stream, 0, ""))
2565 proto_tree_write_pdml(edt, stdout);
2567 return !ferror(stdout);
2570 /* Just fill in the columns. */
2571 epan_dissect_fill_in_columns(edt);
2573 /* Now print them. */
2574 switch (output_action) {
2577 if (!print_columns(cf))
2582 proto_tree_write_psml(edt, stdout);
2583 return !ferror(stdout);
2587 if (!print_hex_data(print_stream, edt))
2589 if (!print_line(print_stream, 0, ""))
2598 switch (output_action) {
2601 return print_finale(print_stream);
2606 write_pdml_finale(stdout);
2608 write_psml_finale(stdout);
2609 return !ferror(stdout);
2612 g_assert_not_reached();
2618 show_print_file_io_error(int err)
2623 cmdarg_err("Not all the packets could be printed because there is "
2624 "no space left on the file system.");
2629 cmdarg_err("Not all the packets could be printed because you are "
2630 "too close to, or over your disk quota.");
2635 cmdarg_err("An error occurred while printing packets: %s.",
2642 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2646 static char errmsg_errno[1024+1];
2649 /* Wiretap error. */
2652 case WTAP_ERR_NOT_REGULAR_FILE:
2653 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2656 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2657 /* Seen only when opening a capture file for reading. */
2658 errmsg = "The file \"%s\" isn't a capture file in a format Tethereal understands.";
2661 case WTAP_ERR_UNSUPPORTED:
2662 /* Seen only when opening a capture file for reading. */
2663 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2664 "The file \"%%s\" isn't a capture file in a format Tethereal understands.\n"
2667 errmsg = errmsg_errno;
2670 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2671 /* Seen only when opening a capture file for writing. */
2672 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2673 "The file \"%%s\" is a pipe, and %s capture files can't be "
2674 "written to a pipe.", wtap_file_type_string(file_type));
2675 errmsg = errmsg_errno;
2678 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2679 /* Seen only when opening a capture file for writing. */
2680 errmsg = "Tethereal doesn't support writing capture files in that format.";
2683 case WTAP_ERR_UNSUPPORTED_ENCAP:
2685 errmsg = "Tethereal can't save this capture in that format.";
2687 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2688 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2691 errmsg = errmsg_errno;
2695 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2697 errmsg = "Tethereal can't save this capture in that format.";
2699 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2702 case WTAP_ERR_BAD_RECORD:
2703 /* Seen only when opening a capture file for reading. */
2704 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2705 "The file \"%%s\" appears to be damaged or corrupt.\n"
2708 errmsg = errmsg_errno;
2711 case WTAP_ERR_CANT_OPEN:
2713 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2715 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2718 case WTAP_ERR_SHORT_READ:
2719 errmsg = "The file \"%s\" appears to have been cut short"
2720 " in the middle of a packet or other data.";
2723 case WTAP_ERR_SHORT_WRITE:
2724 errmsg = "A full header couldn't be written to the file \"%s\".";
2728 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2729 "The file \"%%s\" could not be %s: %s.",
2730 for_writing ? "created" : "opened",
2731 wtap_strerror(err));
2732 errmsg = errmsg_errno;
2736 errmsg = file_open_error_message(err, for_writing);
2741 * Open/create errors are reported with an console message in Tethereal.
2744 open_failure_message(const char *filename, int err, gboolean for_writing)
2746 fprintf(stderr, "tethereal: ");
2747 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2748 fprintf(stderr, "\n");
2752 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2756 char err_msg[2048+1];
2758 wth = wtap_open_offline(fname, err, &err_info, FALSE);
2762 /* The open succeeded. Fill in the information for this file. */
2764 /* Initialize all data structures used for dissection. */
2768 cf->f_datalen = 0; /* not used, but set it anyway */
2770 /* Set the file name because we need it to set the follow stream filter.
2771 XXX - is that still true? We need it for other reasons, though,
2773 cf->filename = g_strdup(fname);
2775 /* Indicate whether it's a permanent or temporary file. */
2776 cf->is_tempfile = is_tempfile;
2778 /* If it's a temporary capture buffer file, mark it as not saved. */
2779 cf->user_saved = !is_tempfile;
2781 cf->cd_t = wtap_file_type(cf->wth);
2783 cf->drops_known = FALSE;
2785 cf->snap = wtap_snapshot_length(cf->wth);
2786 if (cf->snap == 0) {
2787 /* Snapshot length not known. */
2788 cf->has_snap = FALSE;
2789 cf->snap = WTAP_MAX_PACKET_SIZE;
2791 cf->has_snap = TRUE;
2792 nstime_set_zero(&cf->elapsed_time);
2793 nstime_set_zero(&first_ts);
2794 nstime_set_zero(&prev_ts);
2799 g_snprintf(err_msg, sizeof err_msg,
2800 cf_open_error_message(*err, err_info, FALSE, 0), fname);
2801 cmdarg_err("%s", err_msg);
2807 * General errors are reported with an console message in Tethereal.
2810 failure_message(const char *msg_format, va_list ap)
2812 fprintf(stderr, "tethereal: ");
2813 vfprintf(stderr, msg_format, ap);
2814 fprintf(stderr, "\n");
2818 * Read errors are reported with an console message in Tethereal.
2821 read_failure_message(const char *filename, int err)
2823 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
2824 filename, strerror(err));
2828 * Report an error in command-line arguments.
2831 cmdarg_err(const char *fmt, ...)
2836 fprintf(stderr, "tethereal: ");
2837 vfprintf(stderr, fmt, ap);
2838 fprintf(stderr, "\n");
2843 * Report additional information for an error in command-line arguments.
2846 cmdarg_err_cont(const char *fmt, ...)
2851 vfprintf(stderr, fmt, ap);
2852 fprintf(stderr, "\n");
2857 /****************************************************************************************************************/
2858 /* sync pipe "dummies", needed for capture_loop.c */
2862 /** the child has opened a new capture file, notify the parent */
2864 sync_pipe_filename_to_parent(const char *filename)
2866 /* shouldn't happen */
2870 /** the child captured some new packets, notify the parent */
2872 sync_pipe_packet_count_to_parent(int packet_count)
2874 /* shouldn't happen */
2878 /** the child stopped capturing, notify the parent */
2880 sync_pipe_drops_to_parent(int drops)
2882 /* shouldn't happen */
2886 /** the child encountered an error, notify the parent */
2888 sync_pipe_errmsg_to_parent(const char *errmsg)
2893 #endif /* HAVE_LIBPCAP */
2896 /****************************************************************************************************************/
2897 /* simple_dialog "dummies", needed for capture_loop.c */
2902 char *simple_dialog_primary_start(void)
2907 char *simple_dialog_primary_end(void)
2913 /* XXX - do we need to convert the string for the console? */
2915 simple_dialog_format_message(const char *msg)
2921 #if GTK_MAJOR_VERSION < 2
2922 str = g_strdup(msg);
2924 str = xml_escape(msg);
2932 #endif /* HAVE_LIBPCAP */