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 <epan/privileges.h>
66 #include <wiretap/file_util.h>
69 #include <epan/timestamp.h>
70 #include <epan/packet.h>
72 #include "disabled_protos.h"
73 #include <epan/prefs.h>
74 #include <epan/column.h>
76 #include <epan/addr_resolv.h>
78 #include "clopts_common.h"
79 #include "cmdarg_err.h"
80 #include "version_info.h"
81 #include <epan/conversation.h>
82 #include <epan/plugins.h>
84 #include "conditions.h"
85 #include "capture_stop_conditions.h"
86 #include "ringbuffer.h"
87 #include "capture_ui_utils.h"
88 #include <epan/epan_dissect.h>
90 #include <epan/stat_cmd_args.h>
91 #include <epan/timestamp.h>
92 #include <epan/ex-opt.h>
97 #include "capture-pcap-util.h"
98 #include <wiretap/wtap-capture.h>
100 #include "capture-wpcap.h"
101 #include "capture_errs.h"
104 #include "capture_loop.h"
105 #endif /* HAVE_LIBPCAP */
106 #include "epan/emem.h"
110 * This is the template for the decode as option; it is shared between the
111 * various functions that output the usage for this parameter.
113 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
115 static nstime_t first_ts;
116 static nstime_t prev_ts;
117 static GString *comp_info_str, *runtime_info_str;
119 static gboolean print_packet_info; /* TRUE if we're to print packet information */
121 * The way the packet decode is to be written.
124 WRITE_TEXT, /* summary or detail text */
125 WRITE_XML /* PDML or PSML */
126 /* Add CSV and the like here */
128 static output_action_e output_action;
129 static gboolean do_dissection; /* TRUE if we have to dissect each packet */
130 static gboolean verbose;
131 static gboolean print_hex;
132 static gboolean line_buffered;
133 static guint32 cum_bytes = 0;
134 static print_format_e print_format = PR_FMT_TEXT;
135 static print_stream_t *print_stream;
139 * TRUE if we're to print packet counts to keep track of captured packets.
141 static gboolean print_packet_counts;
147 static capture_options capture_opts;
151 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
152 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
154 #endif /* HAVE_LIBPCAP */
157 static int capture(int);
158 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
160 static void report_counts(void);
162 static BOOL WINAPI capture_cleanup(DWORD);
164 static void capture_cleanup(int);
166 static void report_counts_siginfo(int);
169 #endif /* HAVE_LIBPCAP */
171 static int load_cap_file(capture_file *, char *, int);
172 static gboolean process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
173 const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
174 const guchar *pd, int *err);
175 static void show_capture_file_io_error(const char *, int, gboolean);
176 static void show_print_file_io_error(int err);
177 static gboolean write_preamble(capture_file *cf);
178 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
179 static gboolean write_finale(void);
180 static const char *cf_open_error_message(int err, gchar *err_info,
181 gboolean for_writing, int file_type);
183 static void open_failure_message(const char *filename, int err,
184 gboolean for_writing);
185 static void failure_message(const char *msg_format, va_list ap);
186 static void read_failure_message(const char *filename, int err);
191 static void list_capture_types(void) {
194 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
195 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
196 if (wtap_dump_can_open(i))
197 fprintf(stderr, " %s - %s\n",
198 wtap_file_type_short_string(i), wtap_file_type_string(i));
203 print_usage(gboolean print_ver)
210 "Tethereal " VERSION "%s\n"
211 "Dump and analyze network traffic.\n"
212 "See http://www.ethereal.com for more information.\n"
215 svnversion, get_copyright_info());
219 fprintf(output, "\n");
220 fprintf(output, "Usage: tethereal [options] ...\n");
221 fprintf(output, "\n");
224 fprintf(output, "Capture interface:\n");
225 fprintf(output, " -i <interface> name or idx of interface (def: first none loopback)\n");
226 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
227 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
228 fprintf(output, " -p don't capture in promiscuous mode\n");
230 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
232 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
233 fprintf(output, " -D print list of interfaces and exit\n");
234 fprintf(output, " -L print list of link-layer types of iface and exit\n");
235 fprintf(output, "\n");
236 fprintf(output, "Capture stop conditions:\n");
237 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
238 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
239 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
240 fprintf(output, " files:NUM - stop after NUM files\n");
241 /*fprintf(output, "\n");*/
242 fprintf(output, "Capture output:\n");
243 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
244 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
245 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
246 #endif /* HAVE_LIBPCAP */
248 /*fprintf(output, "\n");*/
249 fprintf(output, "Input file:\n");
250 fprintf(output, " -r <infile> set the filename to read from (no pipes or stdin!)\n");
252 fprintf(output, "\n");
253 fprintf(output, "Processing:\n");
254 fprintf(output, " -R <read filter> packet filter in Ethereal display filter syntax\n");
255 fprintf(output, " -n disable all name resolutions (def: all enabled)\n");
256 fprintf(output, " -N <name resolve flags> enable specific name resolution(s): \"mntC\"\n");
257 fprintf(output, " -d %s ...\n", decode_as_arg_template);
258 fprintf(output, " \"Decode As\", see the man page for details\n");
259 fprintf(output, " Example: tcp.port==8888,http\n");
261 /*fprintf(output, "\n");*/
262 fprintf(output, "Output:\n");
263 fprintf(stderr, " -w <outfile|-> set the output filename (or '-' for stdout)\n");
264 fprintf(stderr, " -F <output file type> set the output file type, default is libpcap\n");
265 fprintf(stderr, " an empty \"-F\" option will list the file types\n");
266 fprintf(output, " -V add output of packet tree (Packet Details)\n");
267 fprintf(output, " -x add output of hex and ASCII dump (Packet Bytes)\n");
268 fprintf(output, " -T pdml|ps|psml|text output format of text output (def: text)\n");
269 fprintf(output, " -t ad|a|r|d output format of time stamps (def: r: rel. to first)\n");
270 fprintf(output, " -l flush output after each packet\n");
271 fprintf(output, " -q be more quiet on stdout (e.g. when using statistics)\n");
272 fprintf(output, " -X <key>:<value> eXtension options, see the man page for details\n");
273 fprintf(output, " -z <statistics> various statistics, see the man page for details\n");
275 fprintf(output, "\n");
276 fprintf(stderr, "Miscellaneous:\n");
277 fprintf(stderr, " -h display this help and exit\n");
278 fprintf(stderr, " -v display version info and exit\n");
279 fprintf(output, " -o <name>:<value> ... override preference setting\n");
283 * For a dissector table, print on the stream described by output,
284 * its short name (which is what's used in the "-d" option) and its
288 display_dissector_table_names(char *table_name, const char *ui_name,
291 fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
295 * For a dissector handle, print on the stream described by output,
296 * the filter name (which is what's used in the "-d" option) and the full
297 * name for the protocol that corresponds to this handle.
300 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
303 const gchar* proto_filter_name;
304 const gchar* proto_ui_name;
306 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
308 if (proto_id != -1) {
309 proto_filter_name = proto_get_protocol_filter_name(proto_id);
310 proto_ui_name = proto_get_protocol_name(proto_id);
311 g_assert(proto_filter_name != NULL);
312 g_assert(proto_ui_name != NULL);
314 fprintf((FILE *)output, "\t%s (%s)\n",
321 * The protocol_name_search structure is used by find_protocol_name_func()
322 * to pass parameters and store results
324 struct protocol_name_search{
325 gchar *searched_name; /* Protocol filter name we are looking for */
326 dissector_handle_t matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
327 guint nb_match; /* How many dissectors matched searched_name */
329 typedef struct protocol_name_search *protocol_name_search_t;
332 * This function parses all dissectors associated with a table to find the
333 * one whose protocol has the specified filter name. It is called
334 * as a reference function in a call to dissector_table_foreach_handle.
335 * The name we are looking for, as well as the results, are stored in the
336 * protocol_name_search struct pointed to by user_data.
337 * If called using dissector_table_foreach_handle, we actually parse the
338 * whole list of dissectors.
341 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
345 const gchar *protocol_filter_name;
346 protocol_name_search_t search_info;
350 search_info = (protocol_name_search_t)user_data;
352 proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
353 if (proto_id != -1) {
354 protocol_filter_name = proto_get_protocol_filter_name(proto_id);
355 g_assert(protocol_filter_name != NULL);
356 if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
358 if (search_info->nb_match == 0) {
359 /* Record this handle only if this is the first match */
360 search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
362 search_info->nb_match++;
368 * Print all layer type names supported.
369 * We send the output to the stream described by the handle output.
373 fprint_all_layer_types(FILE *output)
376 dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
380 * Print all protocol names supported for a specific layer type.
381 * table_name contains the layer type name in which the search is performed.
382 * We send the output to the stream described by the handle output.
386 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
389 dissector_table_foreach_handle(table_name,
390 display_dissector_names,
395 * The function below parses the command-line parameters for the decode as
396 * feature (a string pointer by cl_param).
397 * It checks the format of the command-line, searches for a matching table
398 * and dissector. If a table/dissector match is not found, we display a
399 * summary of the available tables/dissectors (on stderr) and return FALSE.
400 * If everything is fine, we get the "Decode as" preference activated,
401 * then we return TRUE.
404 add_decode_as(const gchar *cl_param)
408 gchar *decoded_param;
409 gchar *remaining_param;
411 gchar *dissector_str;
412 dissector_handle_t dissector_matching;
413 dissector_table_t table_matching;
414 ftenum_t dissector_table_selector_type;
415 struct protocol_name_search user_protocol_name;
417 /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
420 decoded_param = g_malloc( sizeof(gchar) * (strlen(cl_param) + 1) ); /* Allocate enough space to have a working copy of the command-line parameter */
421 g_assert(decoded_param);
422 strcpy(decoded_param, cl_param);
425 /* The lines below will parse this string (modifying it) to extract all
426 necessary information. Note that decoded_param is still needed since
427 strings are not copied - we just save pointers. */
429 /* This section extracts a layer type (table_name) from decoded_param */
430 table_name = decoded_param; /* Layer type string starts from beginning */
432 remaining_param = strchr(table_name, '=');
433 if (remaining_param == NULL) {
434 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
435 /* If the argument does not follow the template, carry on anyway to check
436 if the table name is at least correct. If remaining_param is NULL,
437 we'll exit anyway further down */
440 *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
443 /* Remove leading and trailing spaces from the table name */
444 while ( table_name[0] == ' ' )
446 while ( table_name[strlen(table_name) - 1] == ' ' )
447 table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
449 /* The following part searches a table matching with the layer type specified */
450 table_matching = NULL;
452 /* Look for the requested table */
453 if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
454 cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
457 table_matching = find_dissector_table(table_name);
458 if (!table_matching) {
459 cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
463 if (!table_matching) {
464 /* Display a list of supported layer types to help the user, if the
465 specified layer type was not found */
466 cmdarg_err("Valid layer types are:");
467 fprint_all_layer_types(stderr);
469 if (remaining_param == NULL || !table_matching) {
470 /* Exit if the layer type was not found, or if no '=' separator was found
472 g_free(decoded_param);
476 if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
477 cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
480 remaining_param++; /* Move to the second '=' */
481 *remaining_param = '\0'; /* Remove the second '=' */
483 remaining_param++; /* Position after the layer type string */
485 /* This section extracts a selector value (selector_str) from decoded_param */
487 selector_str = remaining_param; /* Next part starts with the selector number */
489 remaining_param = strchr(selector_str, ',');
490 if (remaining_param == NULL) {
491 cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
492 /* If the argument does not follow the template, carry on anyway to check
493 if the selector value is at least correct. If remaining_param is NULL,
494 we'll exit anyway further down */
497 *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
500 dissector_table_selector_type = get_dissector_table_selector_type(table_name);
502 switch (dissector_table_selector_type) {
508 /* The selector for this table is an unsigned number. Parse it as such.
509 There's no need to remove leading and trailing spaces from the
510 selector number string, because sscanf will do that for us. */
511 if ( sscanf(selector_str, "%u", &selector) != 1 ) {
512 cmdarg_err("Invalid selector number \"%s\"", selector_str);
513 g_free(decoded_param);
520 /* The selector for this table is a string. */
524 /* There are currently no dissector tables with any types other
525 than the ones listed above. */
526 g_assert_not_reached();
529 if (remaining_param == NULL) {
530 /* Exit if no ',' separator was found (see above) */
531 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
532 fprint_all_protocols_for_layer_types(stderr, table_name);
533 g_free(decoded_param);
537 remaining_param++; /* Position after the selector number string */
539 /* This section extracts a protocol filter name (dissector_str) from decoded_param */
541 dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
543 /* Remove leading and trailing spaces from the dissector name */
544 while ( dissector_str[0] == ' ' )
546 while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
547 dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
549 dissector_matching = NULL;
551 /* We now have a pointer to the handle for the requested table inside the variable table_matching */
552 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 */
553 cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
556 user_protocol_name.nb_match = 0;
557 user_protocol_name.searched_name = dissector_str;
558 user_protocol_name.matched_handle = NULL;
560 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 */
562 if (user_protocol_name.nb_match != 0) {
563 dissector_matching = user_protocol_name.matched_handle;
564 if (user_protocol_name.nb_match > 1) {
565 cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
569 /* OK, check whether the problem is that there isn't any such
570 protocol, or that there is but it's not specified as a protocol
571 that's valid for that dissector table.
572 Note, we don't exit here, but dissector_matching will remain NULL,
574 if (proto_get_id_by_filter_name(dissector_str) == -1) {
575 /* No such protocol */
576 cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
578 cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
579 dissector_str, table_name);
584 if (!dissector_matching) {
585 cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
586 fprint_all_protocols_for_layer_types(stderr, table_name);
587 g_free(decoded_param);
591 /* This is the end of the code that parses the command-line options.
592 All information is now stored in the variables:
596 The above variables that are strings are still pointing to areas within
597 decoded_parm. decoded_parm thus still needs to be kept allocated in
598 until we stop needing these variables
599 decoded_param will be deallocated at each exit point of this function */
602 /* We now have a pointer to the handle for the requested dissector
603 (requested protocol) inside the variable dissector_matching */
604 switch (dissector_table_selector_type) {
610 /* The selector for this table is an unsigned number. */
611 dissector_change(table_name, selector, dissector_matching);
616 /* The selector for this table is a string. */
617 dissector_change_string(table_name, selector_str, dissector_matching);
621 /* There are currently no dissector tables with any types other
622 than the ones listed above. */
623 g_assert_not_reached();
625 g_free(decoded_param); /* "Decode As" rule has been succesfully added */
630 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
631 const gchar *message _U_, gpointer user_data _U_)
636 output_file_description(const char *fname)
638 char *save_file_string;
640 /* Get a string that describes what we're writing to */
641 if (strcmp(fname, "-") == 0) {
642 /* We're writing to the standard output */
643 save_file_string = g_strdup("standard output");
645 /* We're writing to a file with the name in save_file */
646 save_file_string = g_strdup_printf("file \"%s\"", fname);
648 return save_file_string;
652 main(int argc, char *argv[])
656 gboolean arg_error = FALSE;
662 char *gpf_path, *pf_path;
663 char *gdp_path, *dp_path;
664 int gpf_open_errno, gpf_read_errno;
665 int pf_open_errno, pf_read_errno;
666 int gdp_open_errno, gdp_read_errno;
667 int dp_open_errno, dp_read_errno;
670 gboolean capture_filter_specified = FALSE;
671 gboolean list_link_layer_types = FALSE;
672 gboolean start_capture = FALSE;
674 gboolean capture_option_specified = FALSE;
676 gboolean quiet = FALSE;
677 int out_file_type = WTAP_FILE_PCAP;
678 gchar *cf_name = NULL, *rfilter = NULL;
679 #ifdef HAVE_PCAP_OPEN_DEAD
680 struct bpf_program fcode;
682 dfilter_t *rfcode = NULL;
685 GLogLevelFlags log_flags;
688 #define OPTSTRING_INIT "a:b:c:d:Df:F:hi:lLnN:o:pqr:R:s:St:T:vVw:xX:y:z:"
691 #define OPTSTRING_WIN32 "B:"
693 #define OPTSTRING_WIN32 ""
696 #define OPTSTRING_WIN32 ""
697 #endif /* HAVE_LIBPCAP */
699 static const char optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
702 * Get credential information for later use.
704 get_credential_info();
706 /* nothing more than the standard GLib handler, but without a warning */
709 G_LOG_LEVEL_CRITICAL|
714 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
716 g_log_set_handler(NULL,
718 log_func_ignore, NULL /* user_data */);
719 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
721 log_func_ignore, NULL /* user_data */);
723 /* initialize memory allocation subsystem */
728 capture_opts_init(&capture_opts, NULL /* cfile */);
731 timestamp_set_type(TS_RELATIVE);
732 timestamp_set_precision(TS_PREC_AUTO);
734 /* Register all dissectors; we must do this before checking for the
735 "-G" flag, as the "-G" flag dumps information registered by the
736 dissectors, and we must do it before we read the preferences, in
737 case any dissectors register preferences. */
738 epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs,
739 failure_message,open_failure_message,read_failure_message);
741 /* Register all tap listeners; we do this before we parse the arguments,
742 as the "-z" argument can specify a registered tap. */
744 /* we register the plugin taps before the other taps because
745 stats_tree taps plugins will be registered as tap listeners
746 by stats_tree_stat.c and need to registered before that */
748 register_all_plugin_tap_listeners();
750 register_all_tap_listeners();
752 /* Now register the preferences for any non-dissector modules.
753 We must do that before we read the preferences as well. */
754 prefs_register_modules();
756 /* If invoked with the "-G" flag, we dump out information based on
757 the argument to the "-G" flag; if no argument is specified,
758 for backwards compatibility we dump out a glossary of display
761 XXX - we do this here, for now, to support "-G" with no arguments.
762 If none of our build or other processes uses "-G" with no arguments,
763 we can just process it with the other arguments. */
764 if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
766 proto_registrar_dump_fields(1);
768 if (strcmp(argv[2], "fields") == 0)
769 proto_registrar_dump_fields(1);
770 else if (strcmp(argv[2], "fields2") == 0)
771 proto_registrar_dump_fields(2);
772 else if (strcmp(argv[2], "fields3") == 0)
773 proto_registrar_dump_fields(3);
774 else if (strcmp(argv[2], "protocols") == 0)
775 proto_registrar_dump_protocols();
776 else if (strcmp(argv[2], "values") == 0)
777 proto_registrar_dump_values();
778 else if (strcmp(argv[2], "decodes") == 0)
779 dissector_dump_decodes();
780 else if (strcmp(argv[2], "defaultprefs") == 0)
782 else if (strcmp(argv[2], "currentprefs") == 0) {
783 read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
784 &pf_open_errno, &pf_read_errno, &pf_path);
787 cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
794 /* Set the C-language locale to the native environment. */
795 setlocale(LC_ALL, "");
797 prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
798 &pf_open_errno, &pf_read_errno, &pf_path);
799 if (gpf_path != NULL) {
800 if (gpf_open_errno != 0) {
801 cmdarg_err("Can't open global preferences file \"%s\": %s.",
802 pf_path, strerror(gpf_open_errno));
804 if (gpf_read_errno != 0) {
805 cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
806 pf_path, strerror(gpf_read_errno));
809 if (pf_path != NULL) {
810 if (pf_open_errno != 0) {
811 cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
812 strerror(pf_open_errno));
814 if (pf_read_errno != 0) {
815 cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
816 pf_path, strerror(pf_read_errno));
822 /* Set the name resolution code's flags from the preferences. */
823 g_resolv_flags = prefs->name_resolve;
825 /* Read the disabled protocols file. */
826 read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
827 &dp_path, &dp_open_errno, &dp_read_errno);
828 if (gdp_path != NULL) {
829 if (gdp_open_errno != 0) {
831 "Could not open global disabled protocols file\n\"%s\": %s.",
832 gdp_path, strerror(gdp_open_errno));
834 if (gdp_read_errno != 0) {
836 "I/O error reading global disabled protocols file\n\"%s\": %s.",
837 gdp_path, strerror(gdp_read_errno));
841 if (dp_path != NULL) {
842 if (dp_open_errno != 0) {
844 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
845 strerror(dp_open_errno));
847 if (dp_read_errno != 0) {
849 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
850 strerror(dp_read_errno));
856 /* Load Wpcap, if possible */
860 init_cap_file(&cfile);
862 /* Assemble the compile-time version information string */
863 comp_info_str = g_string_new("Compiled ");
864 get_compiled_version_info(comp_info_str);
866 /* Assemble the run-time version information string */
867 runtime_info_str = g_string_new("Running ");
868 get_runtime_version_info(runtime_info_str);
870 /* Print format defaults to this. */
871 print_format = PR_FMT_TEXT;
873 /* Now get our args */
874 while ((opt = getopt(argc, argv, optstring)) != -1) {
876 case 'a': /* autostop criteria */
877 case 'b': /* Ringbuffer option */
878 case 'c': /* Capture xxx packets */
879 case 'f': /* capture filter */
880 case 'i': /* Use interface xxx */
881 case 'p': /* Don't capture in promiscuous mode */
882 case 's': /* Set the snapshot (capture) length */
883 case 'w': /* Write to capture file xxx */
884 case 'y': /* Set the pcap data link type */
886 case 'B': /* Buffer size */
889 status = capture_opts_add_opt(&capture_opts, opt, optarg, &start_capture);
894 capture_option_specified = TRUE;
898 case 'd': /* Decode as rule */
899 if (!add_decode_as(optarg))
902 case 'D': /* Print a list of capture devices and exit */
904 status = capture_opts_list_interfaces();
907 capture_option_specified = TRUE;
912 out_file_type = wtap_short_string_to_file_type(optarg);
913 if (out_file_type < 0) {
914 cmdarg_err("\"%s\" isn't a valid capture file type",
916 list_capture_types();
920 case 'h': /* Print help and exit */
924 case 'l': /* "Line-buffer" standard output */
925 /* This isn't line-buffering, strictly speaking, it's just
926 flushing the standard output after the information for
927 each packet is printed; however, that should be good
928 enough for all the purposes to which "-l" is put (and
929 is probably actually better for "-V", as it does fewer
932 See the comment in "process_packet()" for an explanation of
933 why we do that, and why we don't just use "setvbuf()" to
934 make the standard output line-buffered (short version: in
935 Windows, "line-buffered" is the same as "fully-buffered",
936 and the output buffer is only flushed when it fills up). */
937 line_buffered = TRUE;
939 case 'L': /* Print list of link-layer types and exit */
941 list_link_layer_types = TRUE;
944 capture_option_specified = TRUE;
948 case 'n': /* No name resolution */
949 g_resolv_flags = RESOLV_NONE;
951 case 'N': /* Select what types of addresses/port #s to resolve */
952 if (g_resolv_flags == RESOLV_ALL)
953 g_resolv_flags = RESOLV_NONE;
954 badopt = string_to_name_resolve(optarg, &g_resolv_flags);
955 if (badopt != '\0') {
956 cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
961 case 'o': /* Override preference from command line */
962 switch (prefs_set_pref(optarg)) {
964 case PREFS_SET_SYNTAX_ERR:
965 cmdarg_err("Invalid -o flag \"%s\"", optarg);
969 case PREFS_SET_NO_SUCH_PREF:
970 case PREFS_SET_OBSOLETE:
971 cmdarg_err("-o flag \"%s\" specifies unknown preference",
977 case 'q': /* Quiet */
980 case 'r': /* Read capture file xxx */
981 cf_name = g_strdup(optarg);
983 case 'R': /* Read file filter */
986 case 'S': /* show packets in real time */
987 print_packet_info = TRUE;
989 case 't': /* Time stamp type */
990 if (strcmp(optarg, "r") == 0)
991 timestamp_set_type(TS_RELATIVE);
992 else if (strcmp(optarg, "a") == 0)
993 timestamp_set_type(TS_ABSOLUTE);
994 else if (strcmp(optarg, "ad") == 0)
995 timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
996 else if (strcmp(optarg, "d") == 0)
997 timestamp_set_type(TS_DELTA);
999 cmdarg_err("Invalid time stamp type \"%s\"",
1001 cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1002 cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1006 case 'T': /* printing Type */
1007 if (strcmp(optarg, "text") == 0) {
1008 output_action = WRITE_TEXT;
1009 print_format = PR_FMT_TEXT;
1010 } else if (strcmp(optarg, "ps") == 0) {
1011 output_action = WRITE_TEXT;
1012 print_format = PR_FMT_PS;
1013 } else if (strcmp(optarg, "pdml") == 0) {
1014 output_action = WRITE_XML;
1016 } else if (strcmp(optarg, "psml") == 0) {
1017 output_action = WRITE_XML;
1020 cmdarg_err("Invalid -T parameter.");
1021 cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", or \"psml\".");
1025 case 'v': /* Show version and exit */
1026 printf("Tethereal " VERSION "%s\n"
1033 svnversion, get_copyright_info(), comp_info_str->str,
1034 runtime_info_str->str);
1037 case 'V': /* Verbose */
1040 case 'x': /* Print packet data in hex (and ASCII) */
1047 /* We won't call the init function for the stat this soon
1048 as it would disallow MATE's fields (which are registered
1049 by the preferences set callback) from being used as
1050 part of a tap filter. Instead, we just add the argument
1051 to a list of stat arguments. */
1052 if (!process_stat_cmd_arg(optarg)) {
1053 cmdarg_err("invalid -z argument.");
1054 cmdarg_err_cont(" -z argument must be one of :");
1055 list_stat_cmd_args();
1060 case '?': /* Bad flag - print usage message */
1063 list_capture_types();
1073 /* If no capture filter or read filter has been specified, and there are
1074 still command-line arguments, treat them as the tokens of a capture
1075 filter (if no "-r" flag was specified) or a read filter (if a "-r"
1076 flag was specified. */
1077 if (optind < argc) {
1078 if (cf_name != NULL) {
1079 if (rfilter != NULL) {
1080 cmdarg_err("Read filters were specified both with \"-R\" "
1081 "and with additional command-line arguments");
1084 rfilter = get_args_as_string(argc, argv, optind);
1087 if (capture_filter_specified) {
1088 cmdarg_err("Capture filters were specified both with \"-f\""
1089 " and with additional command-line arguments");
1092 capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1094 capture_option_specified = TRUE;
1099 /* If we're not writing to a file and "-q" wasn't specified
1100 we should print packet information */
1101 if (capture_opts.save_file == NULL && !quiet)
1102 print_packet_info = TRUE;
1104 if (capture_opts.save_file != NULL &&
1105 strcmp(capture_opts.save_file, "-") == 0
1106 && print_packet_info) {
1107 /* If we're writing to the standard output.
1108 and we'll also be writing dissected packets to the standard
1109 output, reject the request. At best, we could redirect that
1110 to the standard error; we *can't* write both to the standard
1111 output and have either of them be useful. */
1112 cmdarg_err("You can't write both raw packet data and dissected packets"
1113 " to the standard output.");
1117 #ifndef HAVE_LIBPCAP
1118 if (capture_option_specified)
1119 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1126 /* We don't support capture filters when reading from a capture file
1127 (the BPF compiler doesn't support all link-layer types that we
1128 support in capture files we read). */
1130 if (cf_name != NULL) {
1131 if (capture_filter_specified) {
1132 cmdarg_err("Only read filters, not capture filters, "
1133 "can be specified when reading a capture file.");
1140 if (output_action != WRITE_TEXT) {
1141 cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1147 if (list_link_layer_types) {
1148 /* We're supposed to list the link-layer types for an interface;
1149 did the user also specify a capture file to be read? */
1151 /* Yes - that's bogus. */
1152 cmdarg_err("You can't specify -L and a capture file to be read.");
1155 /* No - did they specify a ring buffer option? */
1156 if (capture_opts.multi_files_on) {
1157 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1161 /* If they didn't specify a "-w" flag, but specified a maximum capture
1162 file size, tell them that this doesn't work, and exit. */
1163 if (capture_opts.has_autostop_filesize && capture_opts.save_file == NULL) {
1164 cmdarg_err("Maximum capture file size specified, but "
1165 "capture isn't being saved to a file.");
1169 if (capture_opts.multi_files_on) {
1170 /* Multiple-file mode works only under certain conditions:
1171 a) it doesn't work if you're not saving the capture to a file;
1172 b) it doesn't work if you're writing to the standard output;
1173 c) it doesn't work if you're writing to a pipe;
1174 d) it only works if you're saving in libpcap format;
1175 e) it makes no sense if the maximum file size is set to "infinite"
1176 (XXX - shouldn't that be "if there is no stop criterion",
1177 as you might want to switch files based on a packet count
1179 if (capture_opts.save_file == NULL) {
1180 cmdarg_err("Multiple capture files requested, but "
1181 "the capture isn't being saved to a file.");
1184 if (strcmp(capture_opts.save_file, "-") == 0) {
1185 cmdarg_err("Multiple capture files requested, but "
1186 "the capture is being written to the standard output.");
1189 if (capture_opts.output_to_pipe) {
1190 cmdarg_err("Multiple capture files requested, but "
1191 "the capture file is a pipe.");
1194 if (out_file_type != WTAP_FILE_PCAP) {
1195 cmdarg_err("Multiple capture files requested, but "
1196 "the capture isn't being saved in libpcap format.");
1199 if (!capture_opts.has_autostop_filesize) {
1200 cmdarg_err("Multiple capture files requested, but "
1201 "no maximum capture file size was specified.");
1209 /* Start windows sockets */
1210 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1213 /* Notify all registered modules that have had any of their preferences
1214 changed either from one of the preferences file or from the command
1215 line that their preferences have changed. */
1218 /* At this point MATE will have registered its field array so we can
1219 have a tap filter with one of MATE's late-registered fields as part
1220 of the filter. We can now process all the "-z" arguments. */
1221 start_requested_stats();
1223 /* disabled protocols as per configuration file */
1224 if (gdp_path == NULL && dp_path == NULL) {
1225 set_disabled_protos_list();
1228 /* Build the column format array */
1229 col_setup(&cfile.cinfo, prefs->num_cols);
1230 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1231 cfile.cinfo.col_fmt[i] = get_column_format(i);
1232 cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
1233 cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
1235 get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
1236 cfile.cinfo.col_data[i] = NULL;
1237 if (cfile.cinfo.col_fmt[i] == COL_INFO)
1238 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
1240 cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1241 cfile.cinfo.col_fence[i] = 0;
1242 cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1243 cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
1246 for (i = 0; i < cfile.cinfo.num_cols; i++) {
1249 for (j = 0; j < NUM_COL_FMTS; j++) {
1250 if (!cfile.cinfo.fmt_matx[i][j])
1253 if (cfile.cinfo.col_first[j] == -1)
1254 cfile.cinfo.col_first[j] = i;
1255 cfile.cinfo.col_last[j] = i;
1260 capture_opts_trim_snaplen(&capture_opts, MIN_PACKET_SIZE);
1261 capture_opts_trim_ring_num_files(&capture_opts);
1264 if (rfilter != NULL) {
1265 if (!dfilter_compile(rfilter, &rfcode)) {
1266 cmdarg_err("%s", dfilter_error_msg);
1268 #ifdef HAVE_PCAP_OPEN_DEAD
1272 pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1274 if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1276 " Note: That display filter code looks like a valid capture filter;");
1278 " maybe you mixed them up?");
1287 cfile.rfcode = rfcode;
1289 if (print_packet_info) {
1290 /* If we're printing as text or PostScript, we have
1291 to create a print stream. */
1292 if (output_action == WRITE_TEXT) {
1293 switch (print_format) {
1296 print_stream = print_stream_text_stdio_new(stdout);
1300 print_stream = print_stream_ps_stdio_new(stdout);
1304 g_assert_not_reached();
1309 /* We have to dissect each packet if:
1311 we're printing information about each packet;
1313 we're using a read filter on the packets;
1315 we're using any taps. */
1316 do_dissection = print_packet_info || rfcode || have_tap_listeners();
1320 * We're reading a capture file.
1324 * Immediately relinquish any special privileges we have; we must not
1325 * be allowed to read any capture files the user running Tethereal
1328 relinquish_special_privs_perm();
1330 if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1335 /* Set timestamp precision; there should arguably be a command-line
1336 option to let the user set this. */
1337 switch(wtap_file_tsprecision(cfile.wth)) {
1338 case(WTAP_FILE_TSPREC_SEC):
1339 timestamp_set_precision(TS_PREC_AUTO_SEC);
1341 case(WTAP_FILE_TSPREC_DSEC):
1342 timestamp_set_precision(TS_PREC_AUTO_DSEC);
1344 case(WTAP_FILE_TSPREC_CSEC):
1345 timestamp_set_precision(TS_PREC_AUTO_CSEC);
1347 case(WTAP_FILE_TSPREC_MSEC):
1348 timestamp_set_precision(TS_PREC_AUTO_MSEC);
1350 case(WTAP_FILE_TSPREC_USEC):
1351 timestamp_set_precision(TS_PREC_AUTO_USEC);
1353 case(WTAP_FILE_TSPREC_NSEC):
1354 timestamp_set_precision(TS_PREC_AUTO_NSEC);
1357 g_assert_not_reached();
1360 /* Process the packets in the file */
1361 err = load_cap_file(&cfile, capture_opts.save_file, out_file_type);
1368 /* No capture file specified, so we're supposed to do a live capture
1369 (or get a list of link-layer types for a live capture device);
1370 do we have support for live captures? */
1377 cmdarg_err("WinPcap couldn't be found.");
1378 detailed_err = cant_load_winpcap_err("Tethereal");
1379 cmdarg_err_cont("%s", detailed_err);
1380 g_free(detailed_err);
1385 /* trim the interface name and exit if that failed */
1386 if (!capture_opts_trim_iface(&capture_opts,
1387 (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1391 /* if requested, list the link layer types and exit */
1392 if (list_link_layer_types) {
1393 status = capture_opts_list_link_layer_types(&capture_opts);
1399 * The user didn't ask us not to print a count of packets as
1400 * they arrive, so do so.
1402 print_packet_counts = TRUE;
1405 /* For now, assume libpcap gives microsecond precision. */
1406 timestamp_set_precision(TS_PREC_AUTO_USEC);
1408 capture(out_file_type);
1410 if (capture_opts.multi_files_on) {
1414 /* No - complain. */
1415 cmdarg_err("This version of Tethereal was not built with support for capturing packets.");
1420 draw_tap_listeners(TRUE);
1427 /* Do the low-level work of a capture.
1428 Returns TRUE if it succeeds, FALSE otherwise. */
1430 static condition *volatile cnd_file_duration = NULL; /* this must be visible in process_packet */
1433 capture(int out_file_type)
1436 int volatile volatile_err = 0;
1437 int volatile inpkts = 0;
1439 char errmsg[1024+1];
1440 condition *volatile cnd_autostop_size = NULL;
1441 condition *volatile cnd_autostop_duration = NULL;
1444 void (*oldhandler)(int);
1445 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1447 struct pcap_stat stats;
1452 /* Initialize all data structures used for dissection. */
1455 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1457 ld.packet_cb = capture_pcap_cb;
1460 /* open the "input file" from network interface or capture pipe */
1461 if (!capture_loop_open_input(&capture_opts, &ld, errmsg, sizeof(errmsg)))
1467 * We've opened the capture device, so we shouldn't need any special
1468 * privileges any more; relinquish those privileges.
1470 * XXX - if we have saved set-user-ID support, we should give up those
1471 * privileges immediately, and then reclaim them long enough to get
1472 * a list of network interfaces and to open one, and then give them
1473 * up again, so that stuff we do while processing the argument list,
1474 * reading the user's preferences, loading and starting plugins
1475 * (especially *user* plugins), etc. is done with the user's privileges,
1476 * not special privileges.
1478 relinquish_special_privs_perm();
1480 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1481 if (!capture_loop_open_output(&capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1485 /* init the input filter from the network interface (capture pipe will do nothing) */
1486 if(!capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe,
1487 capture_opts.iface, capture_opts.cfilter, errmsg, sizeof errmsg))
1492 /* open the wiretap part of the output file (the output file is already open) */
1493 if(!capture_loop_init_wiretap_output(&capture_opts, save_file_fd, &ld, errmsg, sizeof errmsg))
1498 /* Save the capture file name. */
1499 ld.save_file = capture_opts.save_file;
1502 /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1503 SetConsoleCtrlHandler(capture_cleanup, TRUE);
1505 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1507 XXX - deal with signal semantics on various UNIX platforms. Or just
1508 use "sigaction()" and be done with it? */
1509 signal(SIGTERM, capture_cleanup);
1510 signal(SIGINT, capture_cleanup);
1511 if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1512 signal(SIGHUP, oldhandler);
1515 /* Catch SIGINFO and, if we get it and we're capturing to a file in
1516 quiet mode, report the number of packets we've captured. */
1517 signal(SIGINFO, report_counts_siginfo);
1518 #endif /* SIGINFO */
1521 /* Let the user know what interface was chosen. */
1522 descr = get_interface_descriptive_name(capture_opts.iface);
1523 fprintf(stderr, "Capturing on %s\n", descr);
1526 /* initialize capture stop conditions */
1527 init_capture_stop_conditions();
1528 /* create stop conditions */
1529 if (capture_opts.has_autostop_filesize)
1530 cnd_autostop_size = cnd_new((const char*)CND_CLASS_CAPTURESIZE,
1531 (long)capture_opts.autostop_filesize * 1024);
1532 if (capture_opts.has_autostop_duration)
1533 cnd_autostop_duration = cnd_new((const char*)CND_CLASS_TIMEOUT,
1534 (gint32)capture_opts.autostop_duration);
1536 if (capture_opts.multi_files_on && capture_opts.has_file_duration)
1537 cnd_file_duration = cnd_new(CND_CLASS_TIMEOUT,
1538 capture_opts.file_duration);
1540 if (!setjmp(ld.stopenv)) {
1542 ld.packet_count = 0;
1547 /* We need to be careful with automatic variables defined in the
1548 outer scope which are changed inside the loop. Most compilers
1549 don't try to roll them back to their original values after the
1550 longjmp which causes the loop to finish, but all that the
1551 standards say is that their values are indeterminate. If we
1552 don't want them to be rolled back, we should define them with the
1553 volatile attribute (paraphrasing W. Richard Stevens, Advanced
1554 Programming in the UNIX Environment, p. 178).
1556 The "err" variable causes a particular problem. If we give it
1557 the volatile attribute, then when we pass a reference to it (as
1558 in "&err") to a function, GCC warns: "passing arg <n> of
1559 <function> discards qualifiers from pointer target type".
1560 Therefore within the loop and just beyond we don't use "err".
1561 Within the loop we define "loop_err", and assign its value to
1562 "volatile_err", which is in the outer scope and is checked when
1565 We also define "packet_count_prev" here to keep things tidy,
1566 since it's used only inside the loop. If it were defined in the
1567 outer scope, GCC would give a warning (unnecessary in this case)
1568 that it might be clobbered, and we'd need to give it the volatile
1569 attribute to suppress the warning. */
1572 int packet_count_prev = 0;
1574 if (cnd_autostop_size == NULL && cnd_autostop_duration == NULL) {
1575 /* We're not stopping at a particular capture file size, and we're
1576 not stopping after some particular amount of time has expired,
1577 so either we have no stop condition or the only stop condition
1578 is a maximum packet count.
1580 If there's no maximum packet count, pass it -1, meaning "until
1581 you run out of packets in the bufferful you read". Otherwise,
1582 pass it the number of packets we have left to capture.
1584 We don't call "pcap_loop()" as, if we're saving to a file that's
1585 a FIFO, we want to flush the FIFO after we're done processing
1586 this libpcap bufferful of packets, so that the program
1587 reading the FIFO sees the packets immediately and doesn't get
1588 any partial packet, forcing it to block in the middle of reading
1590 if (capture_opts.autostop_packets == 0)
1593 if (ld.packet_count >= capture_opts.autostop_packets) {
1594 /* XXX do we need this test here? */
1595 /* It appears there's nothing more to capture. */
1598 pcap_cnt = capture_opts.autostop_packets - ld.packet_count;
1601 /* We need to check the capture file size or the timeout after
1606 if (ld.from_cap_pipe) {
1607 inpkts = cap_pipe_dispatch(ld.cap_pipe_fd, &ld, &ld.cap_pipe_hdr, &ld.cap_pipe_rechdr, pcap_data,
1608 errmsg, sizeof errmsg);
1611 inpkts = pcap_dispatch(ld.pcap_h, pcap_cnt, capture_pcap_cb, (u_char *) &ld);
1613 /* Error from "pcap_dispatch()", or error or "no more packets" from
1614 "cap_pipe_dispatch(). */
1616 } else if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1617 /* The specified capture time has elapsed; stop the capture. */
1619 } else if (inpkts > 0) {
1620 if (capture_opts.autostop_packets != 0 &&
1621 ld.packet_count >= capture_opts.autostop_packets) {
1622 /* The specified number of packets have been captured and have
1623 passed both any capture filter in effect and any read filter
1626 } else if (cnd_autostop_size != NULL &&
1627 cnd_eval(cnd_autostop_size,
1628 (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))) {
1629 /* We're saving the capture to a file, and the capture file reached
1630 its maximum size. */
1631 if (capture_opts.multi_files_on) {
1632 /* Switch to the next ringbuffer file */
1633 if (ringbuf_switch_file(&ld.wtap_pdh, &capture_opts.save_file, &save_file_fd, &loop_err)) {
1634 /* File switch succeeded: reset the condition */
1635 cnd_reset(cnd_autostop_size);
1636 if (cnd_file_duration) {
1637 cnd_reset(cnd_file_duration);
1640 /* File switch failed: stop here */
1641 volatile_err = loop_err;
1645 /* No ringbuffer - just stop. */
1649 if (capture_opts.output_to_pipe) {
1650 if (ld.packet_count > packet_count_prev) {
1651 wtap_dump_flush(ld.wtap_pdh);
1652 packet_count_prev = ld.packet_count;
1656 } /* while (ld.go) */
1658 /* delete stop conditions */
1659 if (cnd_autostop_size != NULL)
1660 cnd_delete(cnd_autostop_size);
1661 if (cnd_autostop_duration != NULL)
1662 cnd_delete(cnd_autostop_duration);
1663 if (cnd_file_duration != NULL)
1664 cnd_delete(cnd_file_duration);
1666 if (print_packet_counts) {
1667 /* We're printing packet counts to stderr.
1668 Send a newline so that we move to the line after the packet count. */
1669 fprintf(stderr, "\n");
1672 /* If we got an error while capturing, report it. */
1675 if (ld.from_cap_pipe) {
1676 if (ld.cap_pipe_err == PIPERR) {
1677 cmdarg_err("Error while capturing packets: %s",
1683 cmdarg_err("Error while capturing packets: %s",
1684 pcap_geterr(ld.pcap_h));
1688 if (volatile_err == 0)
1691 show_capture_file_io_error(capture_opts.save_file, volatile_err, FALSE);
1695 if (capture_opts.save_file != NULL) {
1696 /* We're saving to a file or files; close all files. */
1697 close_ok = capture_loop_close_output(&capture_opts, &ld, &err);
1699 /* If we've displayed a message about a write error, there's no point
1700 in displaying another message about an error on close. */
1701 if (!close_ok && write_ok)
1702 show_capture_file_io_error(capture_opts.save_file, err, TRUE);
1706 if (ld.from_cap_pipe && ld.cap_pipe_fd >= 0)
1707 eth_close(ld.cap_pipe_fd);
1711 /* Get the capture statistics, and, if any packets were dropped, report
1713 if (pcap_stats(ld.pcap_h, &stats) >= 0) {
1714 if (stats.ps_drop != 0) {
1715 fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1718 cmdarg_err("Can't get packet-drop statistics: %s",
1719 pcap_geterr(ld.pcap_h));
1721 pcap_close(ld.pcap_h);
1724 /* Report the number of captured packets if not reported during capture
1725 and we are saving to a file. */
1731 if (capture_opts.multi_files_on) {
1732 ringbuf_error_cleanup();
1734 g_free(capture_opts.save_file);
1735 capture_opts.save_file = NULL;
1736 cmdarg_err("%s", errmsg);
1738 if (ld.from_cap_pipe) {
1739 if (ld.cap_pipe_fd >= 0)
1740 eth_close(ld.cap_pipe_fd);
1744 if (ld.pcap_h != NULL)
1745 pcap_close(ld.pcap_h);
1752 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1755 struct wtap_pkthdr whdr;
1756 union wtap_pseudo_header pseudo_header;
1757 loop_data *ld = (loop_data *) user;
1762 /* Convert from libpcap to Wiretap format.
1763 If that fails, ignore the packet (wtap_process_pcap_packet has
1764 written an error message). */
1765 pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1772 * Prevent a SIGINFO handler from writing to stdout while we're
1773 * doing so; instead, have it just set a flag telling us to print
1774 * that information when we're done.
1777 #endif /* SIGINFO */
1779 /* The current packet may have arrived after a very long silence,
1780 * way past the time to switch files. In order not to have
1781 * the first packet of a new series of events as the last
1782 * [or only] packet in the file, switch before writing!
1784 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1785 /* time elapsed for this ring file, switch to the next */
1786 if (ringbuf_switch_file(&ld->wtap_pdh, &ld->save_file, &save_file_fd, &loop_err)) {
1787 /* File switch succeeded: reset the condition */
1788 cnd_reset(cnd_file_duration);
1790 /* File switch failed: stop here */
1791 /* XXX - we should do something with "loop_err" */
1796 if (!process_packet(&cfile, ld->wtap_pdh, 0, &whdr, &pseudo_header, pd, &err)) {
1797 /* Error writing to a capture file */
1798 if (print_packet_counts) {
1799 /* We're printing counts of packets captured; move to the line after
1801 fprintf(stderr, "\n");
1803 show_capture_file_io_error(ld->save_file, err, FALSE);
1804 pcap_close(ld->pcap_h);
1805 wtap_dump_close(ld->wtap_pdh, &err);
1811 * Allow SIGINFO handlers to write.
1816 * If a SIGINFO handler asked us to write out capture counts, do so.
1820 #endif /* SIGINFO */
1825 capture_cleanup(DWORD ctrltype _U_)
1827 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1828 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1829 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1830 like SIGTERM at least when the machine's shutting down.
1832 For now, we handle them all as indications that we should clean up
1833 and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1836 However, as handlers run in a new thread, we can't just longjmp
1837 out; we have to set "ld.go" to FALSE, and must return TRUE so that
1838 no other handler - such as one that would terminate the process -
1841 XXX - for some reason, typing ^C to Tethereal, if you run this in
1842 a Cygwin console window in at least some versions of Cygwin,
1843 causes Tethereal to terminate immediately; this routine gets
1844 called, but the main loop doesn't get a chance to run and
1845 exit cleanly, at least if this is compiled with Microsoft Visual
1846 C++ (i.e., it's a property of the Cygwin console window or Bash;
1847 it happens if Tethereal is not built with Cygwin - for all I know,
1848 building it with Cygwin may make the problem go away). */
1854 capture_cleanup(int signum _U_)
1856 /* Longjmp back to the starting point; "pcap_dispatch()", on many
1857 UNIX platforms, just keeps looping if it gets EINTR, so if we set
1858 "ld.go" to FALSE and return, we won't break out of it and quit
1860 longjmp(ld.stopenv, 1);
1868 /* XXX - if we use sigaction, this doesn't have to be done.
1869 (Yes, this isn't necessary on BSD, but just in case a system
1870 where "signal()" has AT&T semantics adopts SIGINFO....) */
1871 signal(SIGINFO, report_counts_siginfo);
1872 #endif /* SIGINFO */
1874 if (!print_packet_counts) {
1875 /* Report the count only if we aren't printing a packet count
1876 as packets arrive. */
1877 fprintf(stderr, "%u packets captured\n", ld.packet_count);
1880 infoprint = FALSE; /* we just reported it */
1881 #endif /* SIGINFO */
1886 report_counts_siginfo(int signum _U_)
1888 int sav_errno = errno;
1889 /* If we've been told to delay printing, just set a flag asking
1890 that we print counts (if we're supposed to), otherwise print
1891 the count of packets captured (if we're supposed to). */
1898 #endif /* SIGINFO */
1899 #endif /* HAVE_LIBPCAP */
1902 load_cap_file(capture_file *cf, char *save_file, int out_file_type)
1905 int snapshot_length;
1910 char *save_file_string = NULL;
1912 linktype = wtap_file_encap(cf->wth);
1913 if (save_file != NULL) {
1914 /* Get a string that describes what we're writing to */
1915 save_file_string = output_file_description(save_file);
1917 /* Set up to write to the capture file. */
1918 snapshot_length = wtap_snapshot_length(cf->wth);
1919 if (snapshot_length == 0) {
1920 /* Snapshot length of input file not known. */
1921 snapshot_length = WTAP_MAX_PACKET_SIZE;
1923 pdh = wtap_dump_open(save_file, out_file_type,
1924 linktype, snapshot_length, FALSE /* compressed */, &err);
1927 /* We couldn't set up to write to the capture file. */
1930 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1931 cmdarg_err("Capture files can't be written in that format.");
1934 case WTAP_ERR_UNSUPPORTED_ENCAP:
1935 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1936 cmdarg_err("The capture file being read can't be written in "
1940 case WTAP_ERR_CANT_OPEN:
1941 cmdarg_err("The %s couldn't be created for some "
1942 "unknown reason.", save_file_string);
1945 case WTAP_ERR_SHORT_WRITE:
1946 cmdarg_err("A full header couldn't be written to the %s.",
1951 cmdarg_err("The %s could not be created: %s.", save_file_string,
1952 wtap_strerror(err));
1958 if (print_packet_info) {
1959 if (!write_preamble(cf)) {
1961 show_print_file_io_error(err);
1967 while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
1968 if (!process_packet(cf, pdh, data_offset, wtap_phdr(cf->wth),
1969 wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
1971 /* Error writing to a capture file */
1972 show_capture_file_io_error(save_file, err, FALSE);
1973 wtap_dump_close(pdh, &err);
1978 /* Print a message noting that the read failed somewhere along the line. */
1981 case WTAP_ERR_UNSUPPORTED_ENCAP:
1982 cmdarg_err("\"%s\" has a packet with a network type that Tethereal doesn't support.\n(%s)",
1983 cf->filename, err_info);
1986 case WTAP_ERR_CANT_READ:
1987 cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
1991 case WTAP_ERR_SHORT_READ:
1992 cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
1996 case WTAP_ERR_BAD_RECORD:
1997 cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
1998 cf->filename, err_info);
2002 cmdarg_err("An error occurred while reading \"%s\": %s.",
2003 cf->filename, wtap_strerror(err));
2006 if (save_file != NULL) {
2007 /* Now close the capture file. */
2008 if (!wtap_dump_close(pdh, &err))
2009 show_capture_file_io_error(save_file, err, TRUE);
2012 if (save_file != NULL) {
2013 /* Now close the capture file. */
2014 if (!wtap_dump_close(pdh, &err))
2015 show_capture_file_io_error(save_file, err, TRUE);
2017 if (print_packet_info) {
2018 if (!write_finale()) {
2020 show_print_file_io_error(err);
2027 wtap_close(cf->wth);
2030 if (save_file_string != NULL)
2031 g_free(save_file_string);
2037 fill_in_fdata(frame_data *fdata, capture_file *cf,
2038 const struct wtap_pkthdr *phdr, long offset)
2043 fdata->num = cf->count;
2044 fdata->pkt_len = phdr->len;
2045 cum_bytes += phdr->len;
2046 fdata->cum_bytes = cum_bytes;
2047 fdata->cap_len = phdr->caplen;
2048 fdata->file_off = offset;
2049 fdata->lnk_t = phdr->pkt_encap;
2050 fdata->abs_ts = *((nstime_t *) &phdr->ts);
2051 fdata->flags.passed_dfilter = 0;
2052 fdata->flags.encoding = CHAR_ASCII;
2053 fdata->flags.visited = 0;
2054 fdata->flags.marked = 0;
2055 fdata->flags.ref_time = 0;
2056 fdata->color_filter = NULL;
2058 /* If we don't have the time stamp of the first packet in the
2059 capture, it's because this is the first packet. Save the time
2060 stamp of this packet as the time stamp of the first packet. */
2061 if (nstime_is_zero(&first_ts)) {
2062 first_ts = fdata->abs_ts;
2065 /* If we don't have the time stamp of the previous displayed packet,
2066 it's because this is the first displayed packet. Save the time
2067 stamp of this packet as the time stamp of the previous displayed
2069 if (nstime_is_zero(&prev_ts)) {
2070 prev_ts = fdata->abs_ts;
2073 /* Get the time elapsed between the first packet and this packet. */
2074 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2076 /* If it's greater than the current elapsed time, set the elapsed time
2077 to it (we check for "greater than" so as not to be confused by
2078 time moving backwards). */
2079 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2080 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2081 cf->elapsed_time = fdata->rel_ts;
2084 /* Get the time elapsed between the previous displayed packet and
2086 nstime_delta(&fdata->del_ts, &fdata->abs_ts, &prev_ts);
2087 prev_ts = fdata->abs_ts;
2090 /* Free up all data attached to a "frame_data" structure. */
2092 clear_fdata(frame_data *fdata)
2095 g_slist_free(fdata->pfd);
2099 process_packet(capture_file *cf, wtap_dumper *pdh, long offset,
2100 const struct wtap_pkthdr *whdr,
2101 union wtap_pseudo_header *pseudo_header, const guchar *pd,
2105 gboolean create_proto_tree;
2106 epan_dissect_t *edt;
2109 /* Count this packet. */
2112 /* If we're going to print packet information, or we're going to
2113 run a read filter, or we're going to process taps, set up to
2114 do a dissection and do so. */
2115 if (do_dissection) {
2116 fill_in_fdata(&fdata, cf, whdr, offset);
2118 if (print_packet_info) {
2119 /* Grab any resolved addresses */
2121 if (g_resolv_flags) {
2122 host_name_lookup_process(NULL);
2127 if (cf->rfcode || verbose || num_tap_filters!=0)
2128 create_proto_tree = TRUE;
2130 create_proto_tree = FALSE;
2131 /* The protocol tree will be "visible", i.e., printed, only if we're
2132 printing packet details, which is true if we're printing stuff
2133 ("print_packet_info" is true) and we're in verbose mode ("verbose"
2135 edt = epan_dissect_new(create_proto_tree, print_packet_info && verbose);
2137 /* If we're running a read filter, prime the epan_dissect_t with that
2140 epan_dissect_prime_dfilter(edt, cf->rfcode);
2142 tap_queue_init(edt);
2144 /* We only need the columns if we're printing packet info but we're
2145 *not* verbose; in verbose mode, we print the protocol tree, not
2146 the protocol summary. */
2147 epan_dissect_run(edt, pseudo_header, pd, &fdata,
2148 (print_packet_info && !verbose) ? &cf->cinfo : NULL);
2150 tap_push_tapped_queue(edt);
2152 /* Run the read filter if we have one. */
2154 passed = dfilter_apply_edt(cf->rfcode, edt);
2158 /* We're not running a display filter and we're not printing any
2159 packet information, so we don't need to do a dissection, and all
2160 packets are processed. */
2166 /* Count this packet. */
2171 /* Process this packet. */
2173 /* We're writing to a capture file; write this packet. */
2174 if (!wtap_dump(pdh, whdr, pseudo_header, pd, err))
2177 if (print_packet_counts) {
2178 /* We're printing packet counts. */
2179 if (ld.packet_count != 0) {
2180 fprintf(stderr, "\r%u ", ld.packet_count);
2181 /* stderr could be line buffered */
2187 if (print_packet_info) {
2188 /* We're printing packet information; print the information for
2190 print_packet(cf, edt);
2192 /* The ANSI C standard does not appear to *require* that a line-buffered
2193 stream be flushed to the host environment whenever a newline is
2194 written, it just says that, on such a stream, characters "are
2195 intended to be transmitted to or from the host environment as a
2196 block when a new-line character is encountered".
2198 The Visual C++ 6.0 C implementation doesn't do what is intended;
2199 even if you set a stream to be line-buffered, it still doesn't
2200 flush the buffer at the end of every line.
2202 So, if the "-l" flag was specified, we flush the standard output
2203 at the end of a packet. This will do the right thing if we're
2204 printing packet summary lines, and, as we print the entire protocol
2205 tree for a single packet without waiting for anything to happen,
2206 it should be as good as line-buffered mode if we're printing
2207 protocol trees. (The whole reason for the "-l" flag in either
2208 tcpdump or Tethereal is to allow the output of a live capture to
2209 be piped to a program or script and to have that script see the
2210 information for the packet as soon as it's printed, rather than
2211 having to wait until a standard I/O buffer fills up. */
2215 if (ferror(stdout)) {
2216 show_print_file_io_error(errno);
2222 if (do_dissection) {
2223 epan_dissect_free(edt);
2224 clear_fdata(&fdata);
2230 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2232 char *save_file_string;
2234 save_file_string = output_file_description(fname);
2239 cmdarg_err("Not all the packets could be written to the %s because there is "
2240 "no space left on the file system.",
2246 cmdarg_err("Not all the packets could be written to the %s because you are "
2247 "too close to, or over your disk quota.",
2252 case WTAP_ERR_CANT_CLOSE:
2253 cmdarg_err("The %s couldn't be closed for some unknown reason.",
2257 case WTAP_ERR_SHORT_WRITE:
2258 cmdarg_err("Not all the packets could be written to the %s.",
2264 cmdarg_err("The %s could not be closed: %s.",
2265 save_file_string, wtap_strerror(err));
2267 cmdarg_err("An error occurred while writing to the %s: %s.",
2268 save_file_string, wtap_strerror(err));
2272 g_free(save_file_string);
2276 write_preamble(capture_file *cf)
2278 switch (output_action) {
2281 return print_preamble(print_stream, cf->filename);
2286 write_pdml_preamble(stdout);
2288 write_psml_preamble(stdout);
2289 return !ferror(stdout);
2292 g_assert_not_reached();
2298 get_line_buf(size_t len)
2300 static char *line_bufp = NULL;
2301 static size_t line_buf_len = 256;
2302 size_t new_line_buf_len;
2304 for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2305 new_line_buf_len *= 2)
2307 if (line_bufp == NULL) {
2308 line_buf_len = new_line_buf_len;
2309 line_bufp = g_malloc(line_buf_len + 1);
2311 if (new_line_buf_len > line_buf_len) {
2312 line_buf_len = new_line_buf_len;
2313 line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2320 print_columns(capture_file *cf)
2327 line_bufp = get_line_buf(256);
2330 for (i = 0; i < cf->cinfo.num_cols; i++) {
2331 switch (cf->cinfo.col_fmt[i]) {
2335 * Don't print this if we're doing a live capture from a network
2336 * interface - if we're doing a live capture, you won't be
2337 * able to look at the capture in the future (it's not being
2338 * saved anywhere), so the frame numbers are unlikely to be
2341 * (XXX - it might be nice to be able to save and print at
2342 * the same time, sort of like an "Update list of packets
2343 * in real time" capture in Ethereal.)
2345 if (capture_opts.iface != NULL)
2348 column_len = strlen(cf->cinfo.col_data[i]);
2351 line_bufp = get_line_buf(buf_offset + column_len);
2352 sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2358 case COL_ABS_DATE_TIME: /* XXX - wider */
2359 column_len = strlen(cf->cinfo.col_data[i]);
2360 if (column_len < 10)
2362 line_bufp = get_line_buf(buf_offset + column_len);
2363 sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2369 case COL_DEF_DL_SRC:
2370 case COL_RES_DL_SRC:
2371 case COL_UNRES_DL_SRC:
2372 case COL_DEF_NET_SRC:
2373 case COL_RES_NET_SRC:
2374 case COL_UNRES_NET_SRC:
2375 column_len = strlen(cf->cinfo.col_data[i]);
2376 if (column_len < 12)
2378 line_bufp = get_line_buf(buf_offset + column_len);
2379 sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2385 case COL_DEF_DL_DST:
2386 case COL_RES_DL_DST:
2387 case COL_UNRES_DL_DST:
2388 case COL_DEF_NET_DST:
2389 case COL_RES_NET_DST:
2390 case COL_UNRES_NET_DST:
2391 column_len = strlen(cf->cinfo.col_data[i]);
2392 if (column_len < 12)
2394 line_bufp = get_line_buf(buf_offset + column_len);
2395 sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2399 column_len = strlen(cf->cinfo.col_data[i]);
2400 line_bufp = get_line_buf(buf_offset + column_len);
2401 strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2404 buf_offset += column_len;
2405 if (i != cf->cinfo.num_cols - 1) {
2407 * This isn't the last column, so we need to print a
2408 * separator between this column and the next.
2410 * If we printed a network source and are printing a
2411 * network destination of the same type next, separate
2412 * them with "->"; if we printed a network destination
2413 * and are printing a network source of the same type
2414 * next, separate them with "<-"; otherwise separate them
2417 * We add enough space to the buffer for " <- " or " -> ",
2418 * even if we're only adding " ".
2420 line_bufp = get_line_buf(buf_offset + 4);
2421 switch (cf->cinfo.col_fmt[i]) {
2426 switch (cf->cinfo.col_fmt[i + 1]) {
2431 strcat(line_bufp + buf_offset, " -> ");
2436 strcat(line_bufp + buf_offset, " ");
2442 case COL_DEF_DL_SRC:
2443 case COL_RES_DL_SRC:
2444 case COL_UNRES_DL_SRC:
2445 switch (cf->cinfo.col_fmt[i + 1]) {
2447 case COL_DEF_DL_DST:
2448 case COL_RES_DL_DST:
2449 case COL_UNRES_DL_DST:
2450 strcat(line_bufp + buf_offset, " -> ");
2455 strcat(line_bufp + buf_offset, " ");
2461 case COL_DEF_NET_SRC:
2462 case COL_RES_NET_SRC:
2463 case COL_UNRES_NET_SRC:
2464 switch (cf->cinfo.col_fmt[i + 1]) {
2466 case COL_DEF_NET_DST:
2467 case COL_RES_NET_DST:
2468 case COL_UNRES_NET_DST:
2469 strcat(line_bufp + buf_offset, " -> ");
2474 strcat(line_bufp + buf_offset, " ");
2483 switch (cf->cinfo.col_fmt[i + 1]) {
2488 strcat(line_bufp + buf_offset, " <- ");
2493 strcat(line_bufp + buf_offset, " ");
2499 case COL_DEF_DL_DST:
2500 case COL_RES_DL_DST:
2501 case COL_UNRES_DL_DST:
2502 switch (cf->cinfo.col_fmt[i + 1]) {
2504 case COL_DEF_DL_SRC:
2505 case COL_RES_DL_SRC:
2506 case COL_UNRES_DL_SRC:
2507 strcat(line_bufp + buf_offset, " <- ");
2512 strcat(line_bufp + buf_offset, " ");
2518 case COL_DEF_NET_DST:
2519 case COL_RES_NET_DST:
2520 case COL_UNRES_NET_DST:
2521 switch (cf->cinfo.col_fmt[i + 1]) {
2523 case COL_DEF_NET_SRC:
2524 case COL_RES_NET_SRC:
2525 case COL_UNRES_NET_SRC:
2526 strcat(line_bufp + buf_offset, " <- ");
2531 strcat(line_bufp + buf_offset, " ");
2538 strcat(line_bufp + buf_offset, " ");
2544 return print_line(print_stream, 0, line_bufp);
2548 print_packet(capture_file *cf, epan_dissect_t *edt)
2550 print_args_t print_args;
2553 /* Print the information in the protocol tree. */
2554 switch (output_action) {
2557 print_args.to_file = TRUE;
2558 print_args.format = print_format;
2559 print_args.print_summary = !verbose;
2560 print_args.print_hex = verbose && print_hex;
2561 print_args.print_formfeed = FALSE;
2562 print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2564 /* init the packet range */
2565 packet_range_init(&print_args.range);
2567 if (!proto_tree_print(&print_args, edt, print_stream))
2570 /* "print_hex_data()" will put out a leading blank line, as well
2571 as a trailing one; print one here, to separate the packets,
2572 only if "print_hex_data()" won't be called. */
2573 if (!print_line(print_stream, 0, ""))
2579 proto_tree_write_pdml(edt, stdout);
2581 return !ferror(stdout);
2584 /* Just fill in the columns. */
2585 epan_dissect_fill_in_columns(edt);
2587 /* Now print them. */
2588 switch (output_action) {
2591 if (!print_columns(cf))
2596 proto_tree_write_psml(edt, stdout);
2597 return !ferror(stdout);
2601 if (!print_hex_data(print_stream, edt))
2603 if (!print_line(print_stream, 0, ""))
2612 switch (output_action) {
2615 return print_finale(print_stream);
2620 write_pdml_finale(stdout);
2622 write_psml_finale(stdout);
2623 return !ferror(stdout);
2626 g_assert_not_reached();
2632 show_print_file_io_error(int err)
2637 cmdarg_err("Not all the packets could be printed because there is "
2638 "no space left on the file system.");
2643 cmdarg_err("Not all the packets could be printed because you are "
2644 "too close to, or over your disk quota.");
2649 cmdarg_err("An error occurred while printing packets: %s.",
2656 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2660 static char errmsg_errno[1024+1];
2663 /* Wiretap error. */
2666 case WTAP_ERR_NOT_REGULAR_FILE:
2667 errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
2670 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2671 /* Seen only when opening a capture file for reading. */
2672 errmsg = "The file \"%s\" isn't a capture file in a format Tethereal understands.";
2675 case WTAP_ERR_UNSUPPORTED:
2676 /* Seen only when opening a capture file for reading. */
2677 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2678 "The file \"%%s\" isn't a capture file in a format Tethereal understands.\n"
2681 errmsg = errmsg_errno;
2684 case WTAP_ERR_CANT_WRITE_TO_PIPE:
2685 /* Seen only when opening a capture file for writing. */
2686 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2687 "The file \"%%s\" is a pipe, and %s capture files can't be "
2688 "written to a pipe.", wtap_file_type_string(file_type));
2689 errmsg = errmsg_errno;
2692 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2693 /* Seen only when opening a capture file for writing. */
2694 errmsg = "Tethereal doesn't support writing capture files in that format.";
2697 case WTAP_ERR_UNSUPPORTED_ENCAP:
2699 errmsg = "Tethereal can't save this capture in that format.";
2701 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2702 "The file \"%%s\" is a capture for a network type that Tethereal doesn't support.\n"
2705 errmsg = errmsg_errno;
2709 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2711 errmsg = "Tethereal can't save this capture in that format.";
2713 errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
2716 case WTAP_ERR_BAD_RECORD:
2717 /* Seen only when opening a capture file for reading. */
2718 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2719 "The file \"%%s\" appears to be damaged or corrupt.\n"
2722 errmsg = errmsg_errno;
2725 case WTAP_ERR_CANT_OPEN:
2727 errmsg = "The file \"%s\" could not be created for some unknown reason.";
2729 errmsg = "The file \"%s\" could not be opened for some unknown reason.";
2732 case WTAP_ERR_SHORT_READ:
2733 errmsg = "The file \"%s\" appears to have been cut short"
2734 " in the middle of a packet or other data.";
2737 case WTAP_ERR_SHORT_WRITE:
2738 errmsg = "A full header couldn't be written to the file \"%s\".";
2742 g_snprintf(errmsg_errno, sizeof(errmsg_errno),
2743 "The file \"%%s\" could not be %s: %s.",
2744 for_writing ? "created" : "opened",
2745 wtap_strerror(err));
2746 errmsg = errmsg_errno;
2750 errmsg = file_open_error_message(err, for_writing);
2755 * Open/create errors are reported with an console message in Tethereal.
2758 open_failure_message(const char *filename, int err, gboolean for_writing)
2760 fprintf(stderr, "tethereal: ");
2761 fprintf(stderr, file_open_error_message(err, for_writing), filename);
2762 fprintf(stderr, "\n");
2766 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
2770 char err_msg[2048+1];
2772 wth = wtap_open_offline(fname, err, &err_info, FALSE);
2776 /* The open succeeded. Fill in the information for this file. */
2778 /* Initialize all data structures used for dissection. */
2782 cf->f_datalen = 0; /* not used, but set it anyway */
2784 /* Set the file name because we need it to set the follow stream filter.
2785 XXX - is that still true? We need it for other reasons, though,
2787 cf->filename = g_strdup(fname);
2789 /* Indicate whether it's a permanent or temporary file. */
2790 cf->is_tempfile = is_tempfile;
2792 /* If it's a temporary capture buffer file, mark it as not saved. */
2793 cf->user_saved = !is_tempfile;
2795 cf->cd_t = wtap_file_type(cf->wth);
2797 cf->drops_known = FALSE;
2799 cf->snap = wtap_snapshot_length(cf->wth);
2800 if (cf->snap == 0) {
2801 /* Snapshot length not known. */
2802 cf->has_snap = FALSE;
2803 cf->snap = WTAP_MAX_PACKET_SIZE;
2805 cf->has_snap = TRUE;
2806 nstime_set_zero(&cf->elapsed_time);
2807 nstime_set_zero(&first_ts);
2808 nstime_set_zero(&prev_ts);
2813 g_snprintf(err_msg, sizeof err_msg,
2814 cf_open_error_message(*err, err_info, FALSE, 0), fname);
2815 cmdarg_err("%s", err_msg);
2821 * General errors are reported with an console message in Tethereal.
2824 failure_message(const char *msg_format, va_list ap)
2826 fprintf(stderr, "tethereal: ");
2827 vfprintf(stderr, msg_format, ap);
2828 fprintf(stderr, "\n");
2832 * Read errors are reported with an console message in Tethereal.
2835 read_failure_message(const char *filename, int err)
2837 cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
2838 filename, strerror(err));
2842 * Report an error in command-line arguments.
2845 cmdarg_err(const char *fmt, ...)
2850 fprintf(stderr, "tethereal: ");
2851 vfprintf(stderr, fmt, ap);
2852 fprintf(stderr, "\n");
2857 * Report additional information for an error in command-line arguments.
2860 cmdarg_err_cont(const char *fmt, ...)
2865 vfprintf(stderr, fmt, ap);
2866 fprintf(stderr, "\n");
2871 /****************************************************************************************************************/
2872 /* sync pipe "dummies", needed for capture_loop.c */
2876 /** the child has opened a new capture file, notify the parent */
2878 sync_pipe_filename_to_parent(const char *filename)
2880 /* shouldn't happen */
2884 /** the child captured some new packets, notify the parent */
2886 sync_pipe_packet_count_to_parent(int packet_count)
2888 /* shouldn't happen */
2892 /** the child stopped capturing, notify the parent */
2894 sync_pipe_drops_to_parent(int drops)
2896 /* shouldn't happen */
2900 /** the child encountered an error, notify the parent */
2902 sync_pipe_errmsg_to_parent(const char *errmsg)
2907 #endif /* HAVE_LIBPCAP */
2910 /****************************************************************************************************************/
2911 /* signal pipe "dummies", needed for capture_loop.c */
2917 signal_pipe_check_running(void)
2919 /* currently, no check required */
2924 #endif /* HAVE_LIBPCAP */
2927 /****************************************************************************************************************/
2928 /* simple_dialog "dummies", needed for capture_loop.c */
2933 char *simple_dialog_primary_start(void)
2938 char *simple_dialog_primary_end(void)
2944 /* XXX - do we need to convert the string for the console? */
2946 simple_dialog_format_message(const char *msg)
2952 #if GTK_MAJOR_VERSION < 2
2953 str = g_strdup(msg);
2955 str = xml_escape(msg);
2963 #endif /* HAVE_LIBPCAP */