6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
8 * Copyright 1998 Gerald Combs
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
44 #include <epan/epan.h>
45 #include <epan/expert.h>
46 #include <epan/filesystem.h>
49 #include "color_filters.h"
51 #include <epan/column.h>
52 #include <epan/packet.h>
53 #include <epan/column-utils.h>
54 #include "packet-range.h"
61 #include <epan/prefs.h>
62 #include <epan/dfilter/dfilter.h>
63 #include <epan/epan_dissect.h>
65 #include <epan/dissectors/packet-data.h>
66 #include <epan/dissectors/packet-ber.h>
67 #include <epan/timestamp.h>
68 #include <epan/dfilter/dfilter-macro.h>
69 #include <wsutil/file_util.h>
70 #include <epan/strutil.h>
71 #include <epan/addr_resolv.h>
73 #include "ui/alert_box.h"
74 #include "ui/simple_dialog.h"
75 #include "ui/main_statusbar.h"
76 #include "ui/progress_dlg.h"
77 #include "ui/ui_util.h"
79 /* Needed for addrinfo */
80 #ifdef HAVE_SYS_TYPES_H
81 # include <sys/types.h>
84 #ifdef HAVE_SYS_SOCKET_H
85 #include <sys/socket.h>
88 #ifdef HAVE_NETINET_IN_H
89 # include <netinet/in.h>
96 #ifdef HAVE_WINSOCK2_H
97 # include <winsock2.h>
100 #if defined(_WIN32) && defined(INET6)
101 # include <ws2tcpip.h>
105 gboolean auto_scroll_live;
108 static guint32 cum_bytes;
109 static nstime_t first_ts;
110 static frame_data *prev_dis;
111 static frame_data *prev_cap;
113 static gulong computed_elapsed;
115 static void cf_reset_state(capture_file *cf);
117 static int read_packet(capture_file *cf, dfilter_t *dfcode,
118 gboolean create_proto_tree, column_info *cinfo, gint64 offset);
120 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);
127 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
129 static void match_subtree_text(proto_node *node, gpointer data);
130 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
132 static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
134 static match_result match_narrow(capture_file *cf, frame_data *fdata,
136 static match_result match_wide(capture_file *cf, frame_data *fdata,
138 static match_result match_binary(capture_file *cf, frame_data *fdata,
140 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
142 static match_result match_marked(capture_file *cf, frame_data *fdata,
144 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
146 static gboolean find_packet(capture_file *cf,
147 match_result (*match_function)(capture_file *, frame_data *, void *),
148 void *criterion, search_direction dir);
150 static void cf_open_failure_alert_box(const char *filename, int err,
151 gchar *err_info, gboolean for_writing,
153 static void cf_rename_failure_alert_box(const char *filename, int err);
154 static void cf_close_failure_alert_box(const char *filename, int err);
155 static void ref_time_packets(capture_file *cf);
156 /* Update the progress bar this many times when reading a file. */
157 #define N_PROGBAR_UPDATES 100
158 /* We read around 200k/100ms don't update the progress bar more often than that */
159 #define MIN_QUANTUM 200000
160 #define MIN_NUMBER_OF_PACKET 1500
163 * We could probably use g_signal_...() instead of the callbacks below but that
164 * would require linking our CLI programs to libgobject and creating an object
165 * instance for the signals.
168 cf_callback_t cb_fct;
170 } cf_callback_data_t;
172 static GList *cf_callbacks = NULL;
175 cf_callback_invoke(int event, gpointer data)
177 cf_callback_data_t *cb;
178 GList *cb_item = cf_callbacks;
180 /* there should be at least one interested */
181 g_assert(cb_item != NULL);
183 while (cb_item != NULL) {
184 cb = (cf_callback_data_t *)cb_item->data;
185 cb->cb_fct(event, data, cb->user_data);
186 cb_item = g_list_next(cb_item);
192 cf_callback_add(cf_callback_t func, gpointer user_data)
194 cf_callback_data_t *cb;
196 cb = g_new(cf_callback_data_t,1);
198 cb->user_data = user_data;
200 cf_callbacks = g_list_append(cf_callbacks, cb);
204 cf_callback_remove(cf_callback_t func)
206 cf_callback_data_t *cb;
207 GList *cb_item = cf_callbacks;
209 while (cb_item != NULL) {
210 cb = (cf_callback_data_t *)cb_item->data;
211 if (cb->cb_fct == func) {
212 cf_callbacks = g_list_remove(cf_callbacks, cb);
216 cb_item = g_list_next(cb_item);
219 g_assert_not_reached();
223 cf_timestamp_auto_precision(capture_file *cf)
226 int prec = timestamp_get_precision();
229 /* don't try to get the file's precision if none is opened */
230 if (cf->state == FILE_CLOSED) {
234 /* if we are in auto mode, set precision of current file */
235 if (prec == TS_PREC_AUTO ||
236 prec == TS_PREC_AUTO_SEC ||
237 prec == TS_PREC_AUTO_DSEC ||
238 prec == TS_PREC_AUTO_CSEC ||
239 prec == TS_PREC_AUTO_MSEC ||
240 prec == TS_PREC_AUTO_USEC ||
241 prec == TS_PREC_AUTO_NSEC)
243 switch(wtap_file_tsprecision(cf->wth)) {
244 case(WTAP_FILE_TSPREC_SEC):
245 timestamp_set_precision(TS_PREC_AUTO_SEC);
247 case(WTAP_FILE_TSPREC_DSEC):
248 timestamp_set_precision(TS_PREC_AUTO_DSEC);
250 case(WTAP_FILE_TSPREC_CSEC):
251 timestamp_set_precision(TS_PREC_AUTO_CSEC);
253 case(WTAP_FILE_TSPREC_MSEC):
254 timestamp_set_precision(TS_PREC_AUTO_MSEC);
256 case(WTAP_FILE_TSPREC_USEC):
257 timestamp_set_precision(TS_PREC_AUTO_USEC);
259 case(WTAP_FILE_TSPREC_NSEC):
260 timestamp_set_precision(TS_PREC_AUTO_NSEC);
263 g_assert_not_reached();
266 /* Set the column widths of those columns that show the time in
267 "command-line-specified" format. */
268 for (i = 0; i < cf->cinfo.num_cols; i++) {
269 if (col_has_time_fmt(&cf->cinfo, i)) {
270 packet_list_resize_column(i);
276 cf_get_computed_elapsed(void)
278 return computed_elapsed;
281 static void reset_elapsed(void)
283 computed_elapsed = 0;
287 * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
290 static void compute_elapsed(GTimeVal *start_time)
295 g_get_current_time(&time_now);
297 delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
298 time_now.tv_usec - start_time->tv_usec;
300 computed_elapsed = (gulong) (delta_time / 1000); /* ms */
304 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
309 wth = wtap_open_offline(fname, err, &err_info, TRUE);
313 /* The open succeeded. Close whatever capture file we had open,
314 and fill in the information for this file. */
317 /* XXX - we really want to initialize this after we've read all
318 the packets, so we know how much we'll ultimately need. */
319 buffer_init(&cf->buf, 1500);
321 /* Cleanup all data structures used for dissection. */
322 cleanup_dissection();
323 /* Initialize all data structures used for dissection. */
326 /* We're about to start reading the file. */
327 cf->state = FILE_READ_IN_PROGRESS;
332 /* Set the file name because we need it to set the follow stream filter.
333 XXX - is that still true? We need it for other reasons, though,
335 cf->filename = g_strdup(fname);
337 /* Indicate whether it's a permanent or temporary file. */
338 cf->is_tempfile = is_tempfile;
340 /* No user changes yet. */
341 cf->unsaved_changes = FALSE;
345 cf->cd_t = wtap_file_type(cf->wth);
346 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
348 cf->packet_comment_count = 0;
349 cf->displayed_count = 0;
350 cf->marked_count = 0;
351 cf->ignored_count = 0;
352 cf->ref_time_count = 0;
353 cf->drops_known = FALSE;
355 cf->snap = wtap_snapshot_length(cf->wth);
357 /* Snapshot length not known. */
358 cf->has_snap = FALSE;
359 cf->snap = WTAP_MAX_PACKET_SIZE;
363 /* Allocate a frame_data_sequence for the frames in this file */
364 cf->frames = new_frame_data_sequence();
366 nstime_set_zero(&cf->elapsed_time);
367 nstime_set_unset(&first_ts);
372 /* Adjust timestamp precision if auto is selected, col width will be adjusted */
373 cf_timestamp_auto_precision(cf);
375 packet_list_queue_draw();
376 cf_callback_invoke(cf_cb_file_opened, cf);
378 if (cf->cd_t == WTAP_FILE_BER) {
379 /* tell the BER dissector the file name */
380 ber_set_filename(cf->filename);
383 wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
384 wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
389 cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
394 * Add an encapsulation type to cf->linktypes.
397 cf_add_encapsulation_type(capture_file *cf, int encap)
401 for (i = 0; i < cf->linktypes->len; i++) {
402 if (g_array_index(cf->linktypes, gint, i) == encap)
403 return; /* it's already there */
405 /* It's not already there - add it. */
406 g_array_append_val(cf->linktypes, encap);
410 * Reset the state for the currently closed file, but don't do the
411 * UI callbacks; this is for use in "cf_open()", where we don't
412 * want the UI to go from "file open" to "file closed" back to
413 * "file open", we want it to go from "old file open" to "new file
414 * open and being read".
416 * XXX - currently, cf_open() calls cf_close(), rather than
420 cf_reset_state(capture_file *cf)
422 /* Die if we're in the middle of reading a file. */
423 g_assert(cf->state != FILE_READ_IN_PROGRESS);
429 /* We have no file open... */
430 if (cf->filename != NULL) {
431 /* If it's a temporary file, remove it. */
433 ws_unlink(cf->filename);
434 g_free(cf->filename);
437 /* ...which means we have no changes to that file to save. */
438 cf->unsaved_changes = FALSE;
440 /* Free up the packet buffer. */
441 buffer_free(&cf->buf);
443 dfilter_free(cf->rfcode);
445 if (cf->frames != NULL) {
446 free_frame_data_sequence(cf->frames);
449 #ifdef WANT_PACKET_EDITOR
450 if (cf->edited_frames) {
451 g_tree_destroy(cf->edited_frames);
452 cf->edited_frames = NULL;
455 cf_unselect_packet(cf); /* nothing to select */
456 cf->first_displayed = 0;
457 cf->last_displayed = 0;
459 /* No frames, no frame selected, no field in that frame selected. */
461 cf->current_frame = 0;
463 cf->finfo_selected = NULL;
465 /* No frame link-layer types, either. */
466 g_array_free(cf->linktypes, TRUE);
467 cf->linktypes = NULL;
469 /* Clear the packet list. */
470 packet_list_freeze();
475 nstime_set_zero(&cf->elapsed_time);
477 reset_tap_listeners();
479 /* We have no file open. */
480 cf->state = FILE_CLOSED;
483 /* Reset everything to a pristine state */
485 cf_close(capture_file *cf)
487 if (cf->state != FILE_CLOSED) {
488 cf_callback_invoke(cf_cb_file_closing, cf);
490 /* close things, if not already closed before */
491 color_filters_cleanup();
493 cleanup_dissection();
495 cf_callback_invoke(cf_cb_file_closed, cf);
500 calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
504 progbar_val = (gfloat) file_pos / (gfloat) size;
505 if (progbar_val > 1.0) {
507 /* The file probably grew while we were reading it.
508 * Update file size, and try again.
510 size = wtap_file_size(cf->wth, NULL);
513 progbar_val = (gfloat) file_pos / (gfloat) size;
515 /* If it's still > 1, either "wtap_file_size()" failed (in which
516 * case there's not much we can do about it), or the file
517 * *shrank* (in which case there's not much we can do about
518 * it); just clip the progress value at 1.0.
520 if (progbar_val > 1.0f)
524 g_snprintf(status_str, status_size,
525 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
526 file_pos / 1024, size / 1024);
532 cf_read(capture_file *cf, gboolean reloading)
537 progdlg_t *progbar = NULL;
541 volatile gboolean create_proto_tree;
545 /* Compile the current display filter.
546 * We assume this will not fail since cf->dfilter is only set in
547 * cf_filter IFF the filter was valid.
549 compiled = dfilter_compile(cf->dfilter, &dfcode);
550 g_assert(!cf->dfilter || (compiled && dfcode));
552 /* Get the union of the flags for all tap listeners. */
553 tap_flags = union_of_tap_listener_flags();
555 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
557 reset_tap_listeners();
559 name_ptr = g_filename_display_basename(cf->filename);
562 cf_callback_invoke(cf_cb_file_reload_started, cf);
564 cf_callback_invoke(cf_cb_file_read_started, cf);
566 /* Record whether the file is compressed.
567 XXX - do we know this at open time? */
568 cf->iscompressed = wtap_iscompressed(cf->wth);
570 /* The packet list window will be empty until the file is completly loaded */
571 packet_list_freeze();
574 g_get_current_time(&start_time);
578 int displayed_once = 0;
586 gint64 progbar_quantum;
587 gint64 progbar_nextstep;
589 gchar status_str[100];
593 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
595 /* Find the size of the file. */
596 size = wtap_file_size(cf->wth, NULL);
598 /* Update the progress bar when it gets to this value. */
599 progbar_nextstep = 0;
600 /* When we reach the value that triggers a progress bar update,
601 bump that value by this amount. */
603 progbar_quantum = size/N_PROGBAR_UPDATES;
604 if (progbar_quantum < MIN_QUANTUM)
605 progbar_quantum = MIN_QUANTUM;
608 /* Progress so far. */
611 while ((wtap_read(cf->wth, &err, &err_info, &data_offset))) {
614 file_pos = wtap_read_so_far(cf->wth);
616 /* Create the progress bar if necessary.
617 * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
619 if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
620 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
622 progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
623 TRUE, &stop_flag, &start_time, progbar_val);
625 progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
626 TRUE, &stop_flag, &start_time, progbar_val);
629 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
630 when we update it, we have to run the GTK+ main loop to get it
631 to repaint what's pending, and doing so may involve an "ioctl()"
632 to see if there's any pending input from an X server, and doing
633 that for every packet can be costly, especially on a big file. */
634 if (file_pos >= progbar_nextstep) {
635 if (progbar != NULL) {
636 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
637 /* update the packet bar content on the first run or frequently on very large files */
639 if (progbar_quantum > 500000 || displayed_once == 0) {
640 if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
642 packets_bar_update();
645 #endif /* HAVE_LIBPCAP */
646 update_progress_dlg(progbar, progbar_val, status_str);
648 progbar_nextstep += progbar_quantum;
653 /* Well, the user decided to abort the read. He/She will be warned and
654 it might be enough for him/her to work with the already loaded
656 This is especially true for very large capture files, where you don't
657 want to wait loading the whole file (which may last minutes or even
658 hours even on fast machines) just to see that it was the wrong file. */
661 read_packet(cf, dfcode, create_proto_tree, cinfo, data_offset);
664 CATCH(OutOfMemoryError) {
665 simple_message_box(ESD_TYPE_ERROR, NULL,
666 "Some infos / workarounds can be found at:\n"
667 "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
668 "Sorry, but Wireshark has run out of memory and has to terminate now!");
670 /* Could we close the current capture and free up memory from that? */
672 /* we have to terminate, as we cannot recover from the memory error */
678 /* Free the display name */
681 /* Cleanup and release all dfilter resources */
682 if (dfcode != NULL) {
683 dfilter_free(dfcode);
686 /* We're done reading the file; destroy the progress bar if it was created. */
688 destroy_progress_dlg(progbar);
690 /* We're done reading sequentially through the file. */
691 cf->state = FILE_READ_DONE;
693 /* Close the sequential I/O side, to free up memory it requires. */
694 wtap_sequential_close(cf->wth);
696 /* Allow the protocol dissectors to free up memory that they
697 * don't need after the sequential run-through of the packets. */
698 postseq_cleanup_all_protocols();
700 /* compute the time it took to load the file */
701 compute_elapsed(&start_time);
703 /* Set the file encapsulation type now; we don't know what it is until
704 we've looked at all the packets, as we don't know until then whether
705 there's more than one type (and thus whether it's
706 WTAP_ENCAP_PER_PACKET). */
707 cf->lnk_t = wtap_file_encap(cf->wth);
709 cf->current_frame = frame_data_sequence_find(cf->frames, cf->first_displayed);
714 cf_callback_invoke(cf_cb_file_reload_finished, cf);
716 cf_callback_invoke(cf_cb_file_read_finished, cf);
718 /* If we have any displayed packets to select, select the first of those
719 packets by making the first row the selected row. */
720 if (cf->first_displayed != 0) {
721 packet_list_select_first_row();
725 simple_message_box(ESD_TYPE_WARN, NULL,
726 "The remaining packets in the file were discarded.\n"
728 "As a lot of packets from the original file will be missing,\n"
729 "remember to be careful when saving the current content to a file.\n",
730 "File loading was cancelled!");
731 return CF_READ_ERROR;
735 /* Put up a message box noting that the read failed somewhere along
736 the line. Don't throw out the stuff we managed to read, though,
740 case WTAP_ERR_UNSUPPORTED:
741 simple_error_message_box(
742 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
747 case WTAP_ERR_UNSUPPORTED_ENCAP:
748 simple_error_message_box(
749 "The capture file has a packet with a network type that Wireshark doesn't support.\n(%s)",
754 case WTAP_ERR_CANT_READ:
755 simple_error_message_box(
756 "An attempt to read from the capture file failed for"
757 " some unknown reason.");
760 case WTAP_ERR_SHORT_READ:
761 simple_error_message_box(
762 "The capture file appears to have been cut short"
763 " in the middle of a packet.");
766 case WTAP_ERR_BAD_FILE:
767 simple_error_message_box(
768 "The capture file appears to be damaged or corrupt.\n(%s)",
773 case WTAP_ERR_DECOMPRESS:
774 simple_error_message_box(
775 "The compressed capture file appears to be damaged or corrupt.\n"
781 simple_error_message_box(
782 "An error occurred while reading the"
783 " capture file: %s.", wtap_strerror(err));
786 return CF_READ_ERROR;
793 cf_start_tail(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
795 cf_status_t cf_status;
797 cf_status = cf_open(cf, fname, is_tempfile, err);
802 cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
805 int newly_displayed_packets = 0;
807 volatile gboolean create_proto_tree;
811 /* Compile the current display filter.
812 * We assume this will not fail since cf->dfilter is only set in
813 * cf_filter IFF the filter was valid.
815 compiled = dfilter_compile(cf->dfilter, &dfcode);
816 g_assert(!cf->dfilter || (compiled && dfcode));
818 /* Get the union of the flags for all tap listeners. */
819 tap_flags = union_of_tap_listener_flags();
821 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
825 packet_list_check_end();
826 /* Don't freeze/thaw the list when doing live capture */
827 /*packet_list_freeze();*/
829 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
832 gint64 data_offset = 0;
835 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
837 while (to_read != 0) {
838 wtap_cleareof(cf->wth);
839 if (!wtap_read(cf->wth, err, &err_info, &data_offset)) {
842 if (cf->state == FILE_READ_ABORTED) {
843 /* Well, the user decided to exit Wireshark. Break out of the
844 loop, and let the code below (which is called even if there
845 aren't any packets left to read) exit. */
848 if (read_packet(cf, dfcode, create_proto_tree, (column_info *) cinfo, data_offset) != -1) {
849 newly_displayed_packets++;
854 CATCH(OutOfMemoryError) {
855 simple_message_box(ESD_TYPE_ERROR, NULL,
856 "Some infos / workarounds can be found at:\n"
857 "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
858 "Sorry, but Wireshark has run out of memory and has to terminate now!");
860 /* Could we close the current capture and free up memory from that? */
861 return CF_READ_ABORTED;
863 /* we have to terminate, as we cannot recover from the memory error */
869 /* Update the file encapsulation; it might have changed based on the
870 packets we've read. */
871 cf->lnk_t = wtap_file_encap(cf->wth);
873 /* Cleanup and release all dfilter resources */
874 if (dfcode != NULL) {
875 dfilter_free(dfcode);
878 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
879 cf->count, cf->state, *err);*/
881 /* Don't freeze/thaw the list when doing live capture */
882 /*packet_list_thaw();*/
883 /* With the new packet list the first packet
884 * isn't automatically selected.
886 if (!cf->current_frame)
887 packet_list_select_first_row();
889 /* moving to the end of the packet list - if the user requested so and
890 we have some new packets. */
891 if (newly_displayed_packets && auto_scroll_live && cf->count != 0)
892 packet_list_moveto_end();
894 if (cf->state == FILE_READ_ABORTED) {
895 /* Well, the user decided to exit Wireshark. Return CF_READ_ABORTED
896 so that our caller can kill off the capture child process;
897 this will cause an EOF on the pipe from the child, so
898 "cf_finish_tail()" will be called, and it will clean up
900 return CF_READ_ABORTED;
901 } else if (*err != 0) {
902 /* We got an error reading the capture file.
903 XXX - pop up a dialog box instead? */
904 g_warning("Error \"%s\" while reading: \"%s\" (\"%s\")",
905 wtap_strerror(*err), err_info, cf->filename);
908 return CF_READ_ERROR;
914 cf_fake_continue_tail(capture_file *cf) {
915 cf->state = FILE_READ_DONE;
919 cf_finish_tail(capture_file *cf, int *err)
925 gboolean create_proto_tree;
929 /* Compile the current display filter.
930 * We assume this will not fail since cf->dfilter is only set in
931 * cf_filter IFF the filter was valid.
933 compiled = dfilter_compile(cf->dfilter, &dfcode);
934 g_assert(!cf->dfilter || (compiled && dfcode));
936 /* Get the union of the flags for all tap listeners. */
937 tap_flags = union_of_tap_listener_flags();
938 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
940 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
942 if (cf->wth == NULL) {
944 return CF_READ_ERROR;
947 packet_list_check_end();
948 /* Don't freeze/thaw the list when doing live capture */
949 /*packet_list_freeze();*/
951 while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
952 if (cf->state == FILE_READ_ABORTED) {
953 /* Well, the user decided to abort the read. Break out of the
954 loop, and let the code below (which is called even if there
955 aren't any packets left to read) exit. */
958 read_packet(cf, dfcode, create_proto_tree, cinfo, data_offset);
961 /* Cleanup and release all dfilter resources */
962 if (dfcode != NULL) {
963 dfilter_free(dfcode);
966 /* Don't freeze/thaw the list when doing live capture */
967 /*packet_list_thaw();*/
969 if (cf->state == FILE_READ_ABORTED) {
970 /* Well, the user decided to abort the read. We're only called
971 when the child capture process closes the pipe to us (meaning
972 it's probably exited), so we can just close the capture
973 file; we return CF_READ_ABORTED so our caller can do whatever
974 is appropriate when that happens. */
976 return CF_READ_ABORTED;
979 if (auto_scroll_live && cf->count != 0)
980 packet_list_moveto_end();
982 /* We're done reading sequentially through the file. */
983 cf->state = FILE_READ_DONE;
985 /* We're done reading sequentially through the file; close the
986 sequential I/O side, to free up memory it requires. */
987 wtap_sequential_close(cf->wth);
989 /* Allow the protocol dissectors to free up memory that they
990 * don't need after the sequential run-through of the packets. */
991 postseq_cleanup_all_protocols();
993 /* Update the file encapsulation; it might have changed based on the
994 packets we've read. */
995 cf->lnk_t = wtap_file_encap(cf->wth);
997 /* Update the details in the file-set dialog, as the capture file
998 * has likely grown since we first stat-ed it */
999 fileset_update_file(cf->filename);
1002 /* We got an error reading the capture file.
1003 XXX - pop up a dialog box? */
1005 g_warning("Error \"%s\" while reading: \"%s\" (\"%s\")",
1006 wtap_strerror(*err), err_info, cf->filename);
1008 return CF_READ_ERROR;
1013 #endif /* HAVE_LIBPCAP */
1016 cf_get_display_name(capture_file *cf)
1020 /* Return a name to use in displays */
1021 if (!cf->is_tempfile) {
1022 /* Get the last component of the file name, and use that. */
1024 displayname = g_filename_display_basename(cf->filename);
1026 displayname=g_strdup("(No file)");
1029 /* The file we read is a temporary file from a live capture or
1030 a merge operation; we don't mention its name, but, if it's
1031 from a capture, give the source of the capture. */
1033 displayname = g_strdup(cf->source);
1035 displayname = g_strdup("(Untitled)");
1041 void cf_set_tempfile_source(capture_file *cf, gchar *source) {
1047 cf->source = g_strdup(source);
1049 cf->source = g_strdup("");
1053 const gchar *cf_get_tempfile_source(capture_file *cf) {
1061 /* XXX - use a macro instead? */
1063 cf_get_packet_count(capture_file *cf)
1068 /* XXX - use a macro instead? */
1070 cf_set_packet_count(capture_file *cf, int packet_count)
1072 cf->count = packet_count;
1075 /* XXX - use a macro instead? */
1077 cf_is_tempfile(capture_file *cf)
1079 return cf->is_tempfile;
1082 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
1084 cf->is_tempfile = is_tempfile;
1088 /* XXX - use a macro instead? */
1089 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
1091 cf->drops_known = drops_known;
1094 /* XXX - use a macro instead? */
1095 void cf_set_drops(capture_file *cf, guint32 drops)
1100 /* XXX - use a macro instead? */
1101 gboolean cf_get_drops_known(capture_file *cf)
1103 return cf->drops_known;
1106 /* XXX - use a macro instead? */
1107 guint32 cf_get_drops(capture_file *cf)
1112 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1114 cf->rfcode = rfcode;
1118 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
1119 dfilter_t *dfcode, gboolean create_proto_tree, column_info *cinfo,
1120 struct wtap_pkthdr *phdr, const guint8 *buf, gboolean add_to_packet_list)
1125 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1126 &first_ts, prev_dis, prev_cap);
1129 /* Dissect the frame. */
1130 epan_dissect_init(&edt, create_proto_tree, FALSE);
1132 if (dfcode != NULL) {
1133 epan_dissect_prime_dfilter(&edt, dfcode);
1136 epan_dissect_run_with_taps(&edt, phdr, buf, fdata, cinfo);
1138 /* If we don't have a display filter, set "passed_dfilter" to 1. */
1139 if (dfcode != NULL) {
1140 fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, &edt) ? 1 : 0;
1142 if (fdata->flags.passed_dfilter) {
1143 /* This frame passed the display filter but it may depend on other
1144 * (potentially not displayed) frames. Find those frames and mark them
1147 g_slist_foreach(edt.pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
1150 fdata->flags.passed_dfilter = 1;
1152 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1153 cf->displayed_count++;
1155 if (add_to_packet_list) {
1156 /* We fill the needed columns from new_packet_list */
1157 row = packet_list_append(cinfo, fdata, &edt.pi);
1160 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1162 frame_data_set_after_dissect(fdata, &cum_bytes);
1165 /* If we haven't yet seen the first frame, this is it.
1167 XXX - we must do this before we add the row to the display,
1168 as, if the display's GtkCList's selection mode is
1169 GTK_SELECTION_BROWSE, when the first entry is added to it,
1170 "cf_select_packet()" will be called, and it will fetch the row
1171 data for the 0th row, and will get a null pointer rather than
1172 "fdata", as "gtk_clist_append()" won't yet have returned and
1173 thus "gtk_clist_set_row_data()" won't yet have been called.
1175 We thus need to leave behind bread crumbs so that
1176 "cf_select_packet()" can find this frame. See the comment
1177 in "cf_select_packet()". */
1178 if (cf->first_displayed == 0)
1179 cf->first_displayed = fdata->num;
1181 /* This is the last frame we've seen so far. */
1182 cf->last_displayed = fdata->num;
1185 epan_dissect_cleanup(&edt);
1189 /* read in a new packet */
1190 /* returns the row of the new packet in the packet list or -1 if not displayed */
1192 read_packet(capture_file *cf, dfilter_t *dfcode,
1193 gboolean create_proto_tree, column_info *cinfo, gint64 offset)
1195 struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
1196 const guint8 *buf = wtap_buf_ptr(cf->wth);
1203 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
1204 it's not already there.
1205 XXX - yes, this is O(N), so if every packet had a different
1206 link-layer encapsulation type, it'd be O(N^2) to read the file, but
1207 there are probably going to be a small number of encapsulation types
1209 cf_add_encapsulation_type(cf, phdr->pkt_encap);
1211 /* The frame number of this packet is one more than the count of
1212 frames in the file so far. */
1213 framenum = cf->count + 1;
1215 frame_data_init(&fdlocal, framenum, phdr, offset, cum_bytes);
1220 epan_dissect_init(&edt, TRUE, FALSE);
1221 epan_dissect_prime_dfilter(&edt, cf->rfcode);
1222 epan_dissect_run(&edt, phdr, buf, &fdlocal, NULL);
1223 passed = dfilter_apply_edt(cf->rfcode, &edt);
1224 epan_dissect_cleanup(&edt);
1228 /* This does a shallow copy of fdlocal, which is good enough. */
1229 fdata = frame_data_sequence_add(cf->frames, &fdlocal);
1232 if (fdlocal.opt_comment != NULL)
1233 cf->packet_comment_count++;
1234 cf->f_datalen = offset + fdlocal.cap_len;
1236 if (!cf->redissecting) {
1237 row = add_packet_to_packet_list(fdata, cf, dfcode,
1238 create_proto_tree, cinfo,
1247 cf_merge_files(char **out_filenamep, int in_file_count,
1248 char *const *in_filenames, int file_type, gboolean do_append)
1250 merge_in_file_t *in_files, *in_file;
1255 int open_err, read_err, write_err, close_err;
1259 gboolean got_read_error = FALSE, got_write_error = FALSE;
1261 progdlg_t *progbar = NULL;
1263 gint64 f_len, file_pos;
1265 GTimeVal start_time;
1266 gchar status_str[100];
1267 gint64 progbar_nextstep;
1268 gint64 progbar_quantum;
1269 gchar *display_basename;
1270 int selected_frame_type;
1271 gboolean fake_interface_ids = FALSE;
1273 /* open the input files */
1274 if (!merge_open_in_files(in_file_count, in_filenames, &in_files,
1275 &open_err, &err_info, &err_fileno)) {
1277 cf_open_failure_alert_box(in_filenames[err_fileno], open_err, err_info,
1282 if (*out_filenamep != NULL) {
1283 out_filename = *out_filenamep;
1284 out_fd = ws_open(out_filename, O_CREAT|O_TRUNC|O_BINARY, 0600);
1288 out_fd = create_tempfile(&tmpname, "wireshark");
1291 out_filename = g_strdup(tmpname);
1292 *out_filenamep = out_filename;
1296 merge_close_in_files(in_file_count, in_files);
1298 cf_open_failure_alert_box(out_filename, open_err, NULL, TRUE, file_type);
1302 selected_frame_type = merge_select_frame_type(in_file_count, in_files);
1304 /* If we are trying to merge a number of libpcap files with different encapsulation types
1305 * change the output file type to pcapng and create SHB and IDB:s for the new file use the
1306 * interface index stored in in_files per file to change the phdr before writing the datablock.
1307 * XXX should it be an option to convert to pcapng?
1309 * We need something similar when merging pcapng files possibly with an option to say
1310 * the same interface(s) used in all in files. SHBs comments should be merged together.
1312 if ((selected_frame_type == WTAP_ENCAP_PER_PACKET)&&(file_type == WTAP_FILE_PCAP)) {
1313 /* Write output in pcapng format */
1314 wtapng_section_t *shb_hdr;
1315 wtapng_iface_descriptions_t *idb_inf, *idb_inf_merge_file;
1316 wtapng_if_descr_t int_data, *file_int_data;
1317 GString *comment_gstr;
1319 fake_interface_ids = TRUE;
1320 /* Create SHB info */
1321 shb_hdr = wtap_file_get_shb_info(in_files[0].wth);
1322 comment_gstr = g_string_new("");
1323 g_string_append_printf(comment_gstr, "%s \n",shb_hdr->opt_comment);
1324 g_string_append_printf(comment_gstr, "File created by merging: \n");
1325 file_type = WTAP_FILE_PCAPNG;
1327 for (i = 0; i < in_file_count; i++) {
1328 g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
1330 shb_hdr->section_length = -1;
1332 shb_hdr->opt_comment = g_string_free(comment_gstr, FALSE); /* NULL if not available */
1333 shb_hdr->shb_hardware = NULL; /* NULL if not available, UTF-8 string containing the */
1334 /* description of the hardware used to create this section. */
1335 shb_hdr->shb_os = NULL; /* NULL if not available, UTF-8 string containing the name */
1336 /* of the operating system used to create this section. */
1337 shb_hdr->shb_user_appl = "Wireshark"; /* NULL if not available, UTF-8 string containing the name */
1338 /* of the application used to create this section. */
1340 /* create fake IDB info */
1341 idb_inf = g_new(wtapng_iface_descriptions_t,1);
1342 idb_inf->number_of_interfaces = in_file_count; /* TODO make this the number of DIFFERENT encapsulation types
1343 * check that snaplength is the same too?
1345 idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));
1347 for (i = 0; i < in_file_count; i++) {
1348 idb_inf_merge_file = wtap_file_get_idb_info(in_files[i].wth);
1349 /* read the interface data from the in file to our combined interfca data */
1350 file_int_data = &g_array_index (idb_inf_merge_file->interface_data, wtapng_if_descr_t, 0);
1351 int_data.wtap_encap = file_int_data->wtap_encap;
1352 int_data.time_units_per_second = file_int_data->time_units_per_second;
1353 int_data.link_type = file_int_data->link_type;
1354 int_data.snap_len = file_int_data->snap_len;
1355 int_data.if_name = g_strdup(file_int_data->if_name);
1356 int_data.opt_comment = NULL;
1357 int_data.if_description = NULL;
1358 int_data.if_speed = 0;
1359 int_data.if_tsresol = 6;
1360 int_data.if_filter_str = NULL;
1361 int_data.bpf_filter_len = 0;
1362 int_data.if_filter_bpf_bytes = NULL;
1363 int_data.if_os = NULL;
1364 int_data.if_fcslen = -1;
1365 int_data.num_stat_entries = 0; /* Number of ISB:s */
1366 int_data.interface_statistics = NULL;
1368 g_array_append_val(idb_inf->interface_data, int_data);
1369 g_free(idb_inf_merge_file);
1371 /* Set fake interface Id in per file data */
1372 in_files[i].interface_id = i;
1375 pdh = wtap_dump_fdopen_ng(out_fd, file_type,
1376 selected_frame_type,
1377 merge_max_snapshot_length(in_file_count, in_files),
1378 FALSE /* compressed */, shb_hdr, idb_inf /* wtapng_iface_descriptions_t *idb_inf */, &open_err);
1382 merge_close_in_files(in_file_count, in_files);
1384 cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
1391 pdh = wtap_dump_fdopen(out_fd, file_type,
1392 selected_frame_type,
1393 merge_max_snapshot_length(in_file_count, in_files),
1394 FALSE /* compressed */, &open_err);
1397 merge_close_in_files(in_file_count, in_files);
1399 cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
1405 /* Get the sum of the sizes of all the files. */
1407 for (i = 0; i < in_file_count; i++)
1408 f_len += in_files[i].size;
1410 /* Update the progress bar when it gets to this value. */
1411 progbar_nextstep = 0;
1412 /* When we reach the value that triggers a progress bar update,
1413 bump that value by this amount. */
1414 progbar_quantum = f_len/N_PROGBAR_UPDATES;
1415 /* Progress so far. */
1419 g_get_current_time(&start_time);
1421 /* do the merge (or append) */
1424 in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
1427 in_file = merge_read_packet(in_file_count, in_files, &read_err,
1429 if (in_file == NULL) {
1434 if (read_err != 0) {
1435 /* I/O error reading from in_file */
1436 got_read_error = TRUE;
1440 /* Get the sum of the data offsets in all of the files. */
1442 for (i = 0; i < in_file_count; i++)
1443 data_offset += in_files[i].data_offset;
1445 /* Create the progress bar if necessary.
1446 We check on every iteration of the loop, so that it takes no
1447 longer than the standard time to create it (otherwise, for a
1448 large file, we might take considerably longer than that standard
1449 time in order to get to the next progress bar step). */
1450 if (progbar == NULL) {
1451 progbar = delayed_create_progress_dlg(NULL, "Merging", "files",
1452 FALSE, &stop_flag, &start_time, progbar_val);
1455 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1456 when we update it, we have to run the GTK+ main loop to get it
1457 to repaint what's pending, and doing so may involve an "ioctl()"
1458 to see if there's any pending input from an X server, and doing
1459 that for every packet can be costly, especially on a big file. */
1460 if (data_offset >= progbar_nextstep) {
1461 /* Get the sum of the seek positions in all of the files. */
1463 for (i = 0; i < in_file_count; i++)
1464 file_pos += wtap_read_so_far(in_files[i].wth);
1465 progbar_val = (gfloat) file_pos / (gfloat) f_len;
1466 if (progbar_val > 1.0f) {
1467 /* Some file probably grew while we were reading it.
1468 That "shouldn't happen", so we'll just clip the progress
1472 if (progbar != NULL) {
1473 g_snprintf(status_str, sizeof(status_str),
1474 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
1475 file_pos / 1024, f_len / 1024);
1476 update_progress_dlg(progbar, progbar_val, status_str);
1478 progbar_nextstep += progbar_quantum;
1482 /* Well, the user decided to abort the merge. */
1486 /* If we have WTAP_ENCAP_PER_PACKETend the infiles are of type WTAP_FILE_PCAP
1487 * we need to set the interface id in the paket header = the interface index we used
1488 * in the IDBs interface description for this file(encapsulation type).
1490 if (fake_interface_ids) {
1491 struct wtap_pkthdr *phdr;
1493 phdr = wtap_phdr(in_file->wth);
1494 phdr->interface_id = in_file->interface_id;
1495 phdr->presence_flags = phdr->presence_flags | WTAP_HAS_INTERFACE_ID;
1497 if (!wtap_dump(pdh, wtap_phdr(in_file->wth),
1498 wtap_buf_ptr(in_file->wth), &write_err)) {
1499 got_write_error = TRUE;
1504 /* We're done merging the files; destroy the progress bar if it was created. */
1505 if (progbar != NULL)
1506 destroy_progress_dlg(progbar);
1508 merge_close_in_files(in_file_count, in_files);
1509 if (!got_read_error && !got_write_error) {
1510 if (!wtap_dump_close(pdh, &write_err))
1511 got_write_error = TRUE;
1513 wtap_dump_close(pdh, &close_err);
1515 if (got_read_error) {
1517 * Find the file on which we got the error, and report the error.
1519 for (i = 0; i < in_file_count; i++) {
1520 if (in_files[i].state == GOT_ERROR) {
1521 /* Put up a message box noting that a read failed somewhere along
1523 display_basename = g_filename_display_basename(in_files[i].filename);
1526 case WTAP_ERR_UNSUPPORTED_ENCAP:
1527 simple_error_message_box(
1528 "The capture file %s has a packet with a network type that Wireshark doesn't support.\n(%s)",
1529 display_basename, err_info);
1533 case WTAP_ERR_CANT_READ:
1534 simple_error_message_box(
1535 "An attempt to read from the capture file %s failed for"
1536 " some unknown reason.", display_basename);
1539 case WTAP_ERR_SHORT_READ:
1540 simple_error_message_box(
1541 "The capture file %s appears to have been cut short"
1542 " in the middle of a packet.", display_basename);
1545 case WTAP_ERR_BAD_FILE:
1546 simple_error_message_box(
1547 "The capture file %s appears to be damaged or corrupt.\n(%s)",
1548 display_basename, err_info);
1552 case WTAP_ERR_DECOMPRESS:
1553 simple_error_message_box(
1554 "The compressed capture file %s appears to be damaged or corrupt.\n"
1555 "(%s)", display_basename, err_info);
1560 simple_error_message_box(
1561 "An error occurred while reading the"
1562 " capture file %s: %s.",
1563 display_basename, wtap_strerror(read_err));
1566 g_free(display_basename);
1571 if (got_write_error) {
1572 /* Put up an alert box for the write error. */
1573 if (write_err < 0) {
1574 /* Wiretap error. */
1575 switch (write_err) {
1577 case WTAP_ERR_UNSUPPORTED_ENCAP:
1579 * This is a problem with the particular frame we're writing;
1580 * note that, and give the frame number.
1582 display_basename = g_filename_display_basename(in_file->filename);
1583 simple_error_message_box(
1584 "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.",
1585 in_file->packet_num, display_basename,
1586 wtap_file_type_string(file_type));
1587 g_free(display_basename);
1591 display_basename = g_filename_display_basename(out_filename);
1592 simple_error_message_box(
1593 "An error occurred while writing to the file \"%s\": %s.",
1594 out_filename, wtap_strerror(write_err));
1595 g_free(display_basename);
1600 write_failure_alert_box(out_filename, write_err);
1604 if (got_read_error || got_write_error || stop_flag) {
1605 /* Callers aren't expected to treat an error or an explicit abort
1606 differently - we put up error dialogs ourselves, so they don't
1614 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1616 const char *filter_new = dftext ? dftext : "";
1617 const char *filter_old = cf->dfilter ? cf->dfilter : "";
1619 GTimeVal start_time;
1621 /* if new filter equals old one, do nothing unless told to do so */
1622 if (!force && strcmp(filter_new, filter_old) == 0) {
1628 if (dftext == NULL) {
1629 /* The new filter is an empty filter (i.e., display all packets).
1630 * so leave dfcode==NULL
1634 * We have a filter; make a copy of it (as we'll be saving it),
1635 * and try to compile it.
1637 dftext = g_strdup(dftext);
1638 if (!dfilter_compile(dftext, &dfcode)) {
1639 /* The attempt failed; report an error. */
1640 simple_message_box(ESD_TYPE_ERROR, NULL,
1641 "See the help for a description of the display filter syntax.",
1642 "\"%s\" isn't a valid display filter: %s",
1643 dftext, dfilter_error_msg);
1649 if (dfcode == NULL) {
1650 /* Yes - free the filter text, and set it to null. */
1656 /* We have a valid filter. Replace the current filter. */
1657 g_free(cf->dfilter);
1658 cf->dfilter = dftext;
1659 g_get_current_time(&start_time);
1662 /* Now rescan the packet list, applying the new filter, but not
1663 throwing away information constructed on a previous pass. */
1664 if (dftext == NULL) {
1665 rescan_packets(cf, "Resetting", "Filter", FALSE);
1667 rescan_packets(cf, "Filtering", dftext, FALSE);
1670 /* Cleanup and release all dfilter resources */
1671 dfilter_free(dfcode);
1677 cf_reftime_packets(capture_file *cf)
1679 ref_time_packets(cf);
1683 cf_redissect_packets(capture_file *cf)
1685 rescan_packets(cf, "Reprocessing", "all packets", TRUE);
1689 cf_read_frame_r(capture_file *cf, frame_data *fdata,
1690 struct wtap_pkthdr *phdr, Buffer *buf)
1694 gchar *display_basename;
1696 #ifdef WANT_PACKET_EDITOR
1697 /* if fdata->file_off == -1 it means packet was edited, and we must find data inside edited_frames tree */
1698 if (G_UNLIKELY(fdata->file_off == -1)) {
1699 const modified_frame_data *frame = (const modified_frame_data *) g_tree_lookup(cf->edited_frames, GINT_TO_POINTER(fdata->num));
1702 simple_error_message_box("fdata->file_off == -1, but can't find modified frame!");
1706 *phdr = frame->phdr;
1707 memcpy(pd, frame->pd, fdata->cap_len);
1712 if (!wtap_seek_read(cf->wth, fdata->file_off, phdr, buf,
1713 fdata->cap_len, &err, &err_info)) {
1714 display_basename = g_filename_display_basename(cf->filename);
1717 case WTAP_ERR_UNSUPPORTED_ENCAP:
1718 simple_error_message_box("The file \"%s\" has a packet with a network type that Wireshark doesn't support.\n(%s)",
1719 display_basename, err_info);
1723 case WTAP_ERR_BAD_FILE:
1724 simple_error_message_box("An error occurred while reading from the file \"%s\": %s.\n(%s)",
1725 display_basename, wtap_strerror(err), err_info);
1730 simple_error_message_box(
1731 "An error occurred while reading from the file \"%s\": %s.",
1732 display_basename, wtap_strerror(err));
1735 g_free(display_basename);
1742 cf_read_frame(capture_file *cf, frame_data *fdata)
1744 return cf_read_frame_r(cf, fdata, &cf->phdr, &cf->buf);
1747 /* Rescan the list of packets, reconstructing the CList.
1749 "action" describes why we're doing this; it's used in the progress
1752 "action_item" describes what we're doing; it's used in the progress
1755 "redissect" is TRUE if we need to make the dissectors reconstruct
1756 any state information they have (because a preference that affects
1757 some dissector has changed, meaning some dissector might construct
1758 its state differently from the way it was constructed the last time). */
1760 rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
1762 /* Rescan packets new packet list */
1765 progdlg_t *progbar = NULL;
1768 frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1769 int selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
1770 gboolean selected_frame_seen;
1772 GTimeVal start_time;
1773 gchar status_str[100];
1774 int progbar_nextstep;
1775 int progbar_quantum;
1778 gboolean create_proto_tree;
1780 gboolean add_to_packet_list = FALSE;
1782 guint32 frames_count;
1784 /* Compile the current display filter.
1785 * We assume this will not fail since cf->dfilter is only set in
1786 * cf_filter IFF the filter was valid.
1788 compiled = dfilter_compile(cf->dfilter, &dfcode);
1789 g_assert(!cf->dfilter || (compiled && dfcode));
1791 /* Get the union of the flags for all tap listeners. */
1792 tap_flags = union_of_tap_listener_flags();
1793 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
1795 (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
1797 reset_tap_listeners();
1798 /* Which frame, if any, is the currently selected frame?
1799 XXX - should the selected frame or the focus frame be the "current"
1800 frame, that frame being the one from which "Find Frame" searches
1802 selected_frame = cf->current_frame;
1804 /* Mark frame num as not found */
1805 selected_frame_num = -1;
1807 /* Freeze the packet list while we redo it, so we don't get any
1808 screen updates while it happens. */
1809 packet_list_freeze();
1812 /* We need to re-initialize all the state information that protocols
1813 keep, because some preference that controls a dissector has changed,
1814 which might cause the state information to be constructed differently
1815 by that dissector. */
1817 /* We might receive new packets while redissecting, and we don't
1818 want to dissect those before their time. */
1819 cf->redissecting = TRUE;
1821 /* Cleanup all data structures used for dissection. */
1822 cleanup_dissection();
1823 /* Initialize all data structures used for dissection. */
1826 /* We need to redissect the packets so we have to discard our old
1827 * packet list store. */
1828 packet_list_clear();
1829 add_to_packet_list = TRUE;
1832 /* We don't yet know which will be the first and last frames displayed. */
1833 cf->first_displayed = 0;
1834 cf->last_displayed = 0;
1836 /* We currently don't display any packets */
1837 cf->displayed_count = 0;
1839 /* Iterate through the list of frames. Call a routine for each frame
1840 to check whether it should be displayed and, if so, add it to
1841 the display list. */
1842 nstime_set_unset(&first_ts);
1847 /* Update the progress bar when it gets to this value. */
1848 progbar_nextstep = 0;
1849 /* When we reach the value that triggers a progress bar update,
1850 bump that value by this amount. */
1851 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1852 /* Count of packets at which we've looked. */
1854 /* Progress so far. */
1858 g_get_current_time(&start_time);
1860 /* no previous row yet */
1861 prev_frame_num = -1;
1864 preceding_frame_num = -1;
1865 preceding_frame = NULL;
1866 following_frame_num = -1;
1867 following_frame = NULL;
1869 selected_frame_seen = FALSE;
1871 frames_count = cf->count;
1872 for (framenum = 1; framenum <= frames_count; framenum++) {
1873 fdata = frame_data_sequence_find(cf->frames, framenum);
1875 /* Create the progress bar if necessary.
1876 We check on every iteration of the loop, so that it takes no
1877 longer than the standard time to create it (otherwise, for a
1878 large file, we might take considerably longer than that standard
1879 time in order to get to the next progress bar step). */
1880 if (progbar == NULL)
1881 progbar = delayed_create_progress_dlg(cf->window, action, action_item, TRUE,
1882 &stop_flag, &start_time,
1885 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1886 when we update it, we have to run the GTK+ main loop to get it
1887 to repaint what's pending, and doing so may involve an "ioctl()"
1888 to see if there's any pending input from an X server, and doing
1889 that for every packet can be costly, especially on a big file. */
1890 if (count >= progbar_nextstep) {
1891 /* let's not divide by zero. I should never be started
1892 * with count == 0, so let's assert that
1894 g_assert(cf->count > 0);
1895 progbar_val = (gfloat) count / frames_count;
1897 if (progbar != NULL) {
1898 g_snprintf(status_str, sizeof(status_str),
1899 "%4u of %u frames", count, frames_count);
1900 update_progress_dlg(progbar, progbar_val, status_str);
1903 progbar_nextstep += progbar_quantum;
1907 /* Well, the user decided to abort the filtering. Just stop.
1909 XXX - go back to the previous filter? Users probably just
1910 want not to wait for a filtering operation to finish;
1911 unless we cancel by having no filter, reverting to the
1912 previous filter will probably be even more expensive than
1913 continuing the filtering, as it involves going back to the
1914 beginning and filtering, and even with no filter we currently
1915 have to re-generate the entire clist, which is also expensive.
1917 I'm not sure what Network Monitor does, but it doesn't appear
1918 to give you an unfiltered display if you cancel. */
1925 /* Since all state for the frame was destroyed, mark the frame
1926 * as not visited, free the GSList referring to the state
1927 * data (the per-frame data itself was freed by
1928 * "init_dissection()"), and null out the GSList pointer. */
1929 frame_data_reset(fdata);
1930 frames_count = cf->count;
1933 /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1934 fdata->flags.dependent_of_displayed = 0;
1936 if (!cf_read_frame(cf, fdata))
1937 break; /* error reading the frame */
1939 /* If the previous frame is displayed, and we haven't yet seen the
1940 selected frame, remember that frame - it's the closest one we've
1941 yet seen before the selected frame. */
1942 if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->flags.passed_dfilter) {
1943 preceding_frame_num = prev_frame_num;
1944 preceding_frame = prev_frame;
1946 add_packet_to_packet_list(fdata, cf, dfcode, create_proto_tree,
1948 buffer_start_ptr(&cf->buf),
1949 add_to_packet_list);
1951 /* If this frame is displayed, and this is the first frame we've
1952 seen displayed after the selected frame, remember this frame -
1953 it's the closest one we've yet seen at or after the selected
1955 if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1956 following_frame_num = fdata->num;
1957 following_frame = fdata;
1959 if (fdata == selected_frame) {
1960 selected_frame_seen = TRUE;
1961 if (fdata->flags.passed_dfilter)
1962 selected_frame_num = fdata->num;
1965 /* Remember this frame - it'll be the previous frame
1966 on the next pass through the loop. */
1967 prev_frame_num = fdata->num;
1971 /* We are done redissecting the packet list. */
1972 cf->redissecting = FALSE;
1975 frames_count = cf->count;
1976 /* Clear out what remains of the visited flags and per-frame data
1979 XXX - that may cause various forms of bogosity when dissecting
1980 these frames, as they won't have been seen by this sequential
1981 pass, but the only alternative I see is to keep scanning them
1982 even though the user requested that the scan stop, and that
1983 would leave the user stuck with an Wireshark grinding on
1984 until it finishes. Should we just stick them with that? */
1985 for (; framenum <= frames_count; framenum++) {
1986 fdata = frame_data_sequence_find(cf->frames, framenum);
1987 frame_data_reset(fdata);
1991 /* We're done filtering the packets; destroy the progress bar if it
1993 if (progbar != NULL)
1994 destroy_progress_dlg(progbar);
1996 /* Unfreeze the packet list. */
1997 if (!add_to_packet_list)
1998 packet_list_recreate_visible_rows();
2000 /* Compute the time it took to filter the file */
2001 compute_elapsed(&start_time);
2005 if (selected_frame_num == -1) {
2006 /* The selected frame didn't pass the filter. */
2007 if (selected_frame == NULL) {
2008 /* That's because there *was* no selected frame. Make the first
2009 displayed frame the current frame. */
2010 selected_frame_num = 0;
2012 /* Find the nearest displayed frame to the selected frame (whether
2013 it's before or after that frame) and make that the current frame.
2014 If the next and previous displayed frames are equidistant from the
2015 selected frame, choose the next one. */
2016 g_assert(following_frame == NULL ||
2017 following_frame->num >= selected_frame->num);
2018 g_assert(preceding_frame == NULL ||
2019 preceding_frame->num <= selected_frame->num);
2020 if (following_frame == NULL) {
2021 /* No frame after the selected frame passed the filter, so we
2022 have to select the last displayed frame before the selected
2024 selected_frame_num = preceding_frame_num;
2025 selected_frame = preceding_frame;
2026 } else if (preceding_frame == NULL) {
2027 /* No frame before the selected frame passed the filter, so we
2028 have to select the first displayed frame after the selected
2030 selected_frame_num = following_frame_num;
2031 selected_frame = following_frame;
2033 /* Frames before and after the selected frame passed the filter, so
2034 we'll select the previous frame */
2035 selected_frame_num = preceding_frame_num;
2036 selected_frame = preceding_frame;
2041 if (selected_frame_num == -1) {
2042 /* There are no frames displayed at all. */
2043 cf_unselect_packet(cf);
2045 /* Either the frame that was selected passed the filter, or we've
2046 found the nearest displayed frame to that frame. Select it, make
2047 it the focus row, and make it visible. */
2048 /* Set to invalid to force update of packet list and packet details */
2049 cf->current_row = -1;
2050 if (selected_frame_num == 0) {
2051 packet_list_select_first_row();
2053 if (!packet_list_select_row_from_data(selected_frame)) {
2054 /* We didn't find a row corresponding to this frame.
2055 This means that the frame isn't being displayed currently,
2056 so we can't select it. */
2057 simple_message_box(ESD_TYPE_INFO, NULL,
2058 "The capture file is probably not fully dissected.",
2059 "End of capture exceeded!");
2064 /* Cleanup and release all dfilter resources */
2065 dfilter_free(dfcode);
2070 * Scan trough all frame data and recalculate the ref time
2071 * without rereading the file.
2072 * XXX - do we need a progres bar or is this fast enough?
2075 ref_time_packets(capture_file *cf)
2080 nstime_set_unset(&first_ts);
2084 for (framenum = 1; framenum <= cf->count; framenum++) {
2085 fdata = frame_data_sequence_find(cf->frames, framenum);
2087 /* just add some value here until we know if it is being displayed or not */
2088 fdata->cum_bytes = cum_bytes + fdata->pkt_len;
2094 /* If we don't have the time stamp of the first packet in the
2095 capture, it's because this is the first packet. Save the time
2096 stamp of this packet as the time stamp of the first packet. */
2097 if (nstime_is_unset(&first_ts)) {
2098 first_ts = fdata->abs_ts;
2100 /* if this frames is marked as a reference time frame, reset
2101 firstsec and firstusec to this frame */
2102 if (fdata->flags.ref_time) {
2103 first_ts = fdata->abs_ts;
2106 /* If we don't have the time stamp of the previous displayed packet,
2107 it's because this is the first displayed packet. Save the time
2108 stamp of this packet as the time stamp of the previous displayed
2110 if (prev_dis == NULL) {
2114 /* Get the time elapsed between the first packet and this packet. */
2115 nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2117 /* If it's greater than the current elapsed time, set the elapsed time
2118 to it (we check for "greater than" so as not to be confused by
2119 time moving backwards). */
2120 if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2121 || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2122 cf->elapsed_time = fdata->rel_ts;
2125 /* If this frame is displayed, get the time elapsed between the
2126 previous displayed packet and this packet. */
2127 if ( fdata->flags.passed_dfilter ) {
2128 fdata->prev_dis = prev_dis;
2135 if ( (fdata->flags.passed_dfilter) || (fdata->flags.ref_time) ) {
2136 /* This frame either passed the display filter list or is marked as
2137 a time reference frame. All time reference frames are displayed
2138 even if they dont pass the display filter */
2139 if (fdata->flags.ref_time) {
2140 /* if this was a TIME REF frame we should reset the cum_bytes field */
2141 cum_bytes = fdata->pkt_len;
2142 fdata->cum_bytes = cum_bytes;
2144 /* increase cum_bytes with this packets length */
2145 cum_bytes += fdata->pkt_len;
2158 process_specified_packets(capture_file *cf, packet_range_t *range,
2159 const char *string1, const char *string2, gboolean terminate_is_stop,
2160 gboolean (*callback)(capture_file *, frame_data *,
2161 struct wtap_pkthdr *, const guint8 *, void *),
2162 void *callback_args)
2167 psp_return_t ret = PSP_FINISHED;
2169 progdlg_t *progbar = NULL;
2172 gboolean progbar_stop_flag;
2173 GTimeVal progbar_start_time;
2174 gchar progbar_status_str[100];
2175 int progbar_nextstep;
2176 int progbar_quantum;
2177 range_process_e process_this;
2178 struct wtap_pkthdr phdr;
2180 buffer_init(&buf, 1500);
2182 /* Update the progress bar when it gets to this value. */
2183 progbar_nextstep = 0;
2184 /* When we reach the value that triggers a progress bar update,
2185 bump that value by this amount. */
2186 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2187 /* Count of packets at which we've looked. */
2189 /* Progress so far. */
2192 progbar_stop_flag = FALSE;
2193 g_get_current_time(&progbar_start_time);
2196 packet_range_process_init(range);
2198 /* Iterate through all the packets, printing the packets that
2199 were selected by the current display filter. */
2200 for (framenum = 1; framenum <= cf->count; framenum++) {
2201 fdata = frame_data_sequence_find(cf->frames, framenum);
2203 /* Create the progress bar if necessary.
2204 We check on every iteration of the loop, so that it takes no
2205 longer than the standard time to create it (otherwise, for a
2206 large file, we might take considerably longer than that standard
2207 time in order to get to the next progress bar step). */
2208 if (progbar == NULL)
2209 progbar = delayed_create_progress_dlg(cf->window, string1, string2,
2212 &progbar_start_time,
2215 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
2216 when we update it, we have to run the GTK+ main loop to get it
2217 to repaint what's pending, and doing so may involve an "ioctl()"
2218 to see if there's any pending input from an X server, and doing
2219 that for every packet can be costly, especially on a big file. */
2220 if (progbar_count >= progbar_nextstep) {
2221 /* let's not divide by zero. I should never be started
2222 * with count == 0, so let's assert that
2224 g_assert(cf->count > 0);
2225 progbar_val = (gfloat) progbar_count / cf->count;
2227 if (progbar != NULL) {
2228 g_snprintf(progbar_status_str, sizeof(progbar_status_str),
2229 "%4u of %u packets", progbar_count, cf->count);
2230 update_progress_dlg(progbar, progbar_val, progbar_status_str);
2233 progbar_nextstep += progbar_quantum;
2236 if (progbar_stop_flag) {
2237 /* Well, the user decided to abort the operation. Just stop,
2238 and arrange to return PSP_STOPPED to our caller, so they know
2239 it was stopped explicitly. */
2246 if (range != NULL) {
2247 /* do we have to process this packet? */
2248 process_this = packet_range_process_packet(range, fdata);
2249 if (process_this == range_process_next) {
2250 /* this packet uninteresting, continue with next one */
2252 } else if (process_this == range_processing_finished) {
2253 /* all interesting packets processed, stop the loop */
2258 /* Get the packet */
2259 if (!cf_read_frame_r(cf, fdata, &phdr, &buf)) {
2260 /* Attempt to get the packet failed. */
2264 /* Process the packet */
2265 if (!callback(cf, fdata, &phdr, buffer_start_ptr(&buf), callback_args)) {
2266 /* Callback failed. We assume it reported the error appropriately. */
2272 /* We're done printing the packets; destroy the progress bar if
2274 if (progbar != NULL)
2275 destroy_progress_dlg(progbar);
2283 gboolean construct_protocol_tree;
2285 } retap_callback_args_t;
2288 retap_packet(capture_file *cf _U_, frame_data *fdata,
2289 struct wtap_pkthdr *phdr, const guint8 *pd,
2292 retap_callback_args_t *args = (retap_callback_args_t *)argsp;
2295 epan_dissect_init(&edt, args->construct_protocol_tree, FALSE);
2296 epan_dissect_run_with_taps(&edt, phdr, pd, fdata, args->cinfo);
2297 epan_dissect_cleanup(&edt);
2303 cf_retap_packets(capture_file *cf)
2305 packet_range_t range;
2306 retap_callback_args_t callback_args;
2307 gboolean filtering_tap_listeners;
2310 /* Do we have any tap listeners with filters? */
2311 filtering_tap_listeners = have_filtering_tap_listeners();
2313 tap_flags = union_of_tap_listener_flags();
2315 /* If any tap listeners have filters, or require the protocol tree,
2316 construct the protocol tree. */
2317 callback_args.construct_protocol_tree = filtering_tap_listeners ||
2318 (tap_flags & TL_REQUIRES_PROTO_TREE);
2320 /* If any tap listeners require the columns, construct them. */
2321 callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
2323 /* Reset the tap listeners. */
2324 reset_tap_listeners();
2326 /* Iterate through the list of packets, dissecting all packets and
2327 re-running the taps. */
2328 packet_range_init(&range, cf);
2329 packet_range_process_init(&range);
2330 switch (process_specified_packets(cf, &range, "Recalculating statistics on",
2331 "all packets", TRUE, retap_packet,
2334 /* Completed successfully. */
2338 /* Well, the user decided to abort the refiltering.
2339 Return CF_READ_ABORTED so our caller knows they did that. */
2340 return CF_READ_ABORTED;
2343 /* Error while retapping. */
2344 return CF_READ_ERROR;
2347 g_assert_not_reached();
2352 print_args_t *print_args;
2353 gboolean print_header_line;
2354 char *header_line_buf;
2355 int header_line_buf_len;
2356 gboolean print_formfeed;
2357 gboolean print_separator;
2361 int num_visible_cols;
2363 } print_callback_args_t;
2366 print_packet(capture_file *cf, frame_data *fdata,
2367 struct wtap_pkthdr *phdr, const guint8 *pd,
2370 print_callback_args_t *args = (print_callback_args_t *)argsp;
2377 gboolean proto_tree_needed;
2378 char bookmark_name[9+10+1]; /* "__frameNNNNNNNNNN__\0" */
2379 char bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0" */
2381 /* Create the protocol tree, and make it visible, if we're printing
2382 the dissection or the hex data.
2383 XXX - do we need it if we're just printing the hex data? */
2385 args->print_args->print_dissections != print_dissections_none || args->print_args->print_hex || have_custom_cols(&cf->cinfo);
2386 epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2388 /* Fill in the column information if we're printing the summary
2390 if (args->print_args->print_summary) {
2391 col_custom_prime_edt(&edt, &cf->cinfo);
2392 epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2393 epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2395 epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2397 if (args->print_formfeed) {
2398 if (!new_page(args->print_args->stream))
2401 if (args->print_separator) {
2402 if (!print_line(args->print_args->stream, 0, ""))
2408 * We generate bookmarks, if the output format supports them.
2409 * The name is "__frameN__".
2411 g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2413 if (args->print_args->print_summary) {
2414 if (!args->print_args->print_col_headings)
2415 args->print_header_line = FALSE;
2416 if (args->print_header_line) {
2417 if (!print_line(args->print_args->stream, 0, args->header_line_buf))
2419 args->print_header_line = FALSE; /* we might not need to print any more */
2421 cp = &args->line_buf[0];
2423 for (i = 0; i < args->num_visible_cols; i++) {
2424 /* Find the length of the string for this column. */
2425 column_len = (int) strlen(cf->cinfo.col_data[args->visible_cols[i]]);
2426 if (args->col_widths[i] > column_len)
2427 column_len = args->col_widths[i];
2429 /* Make sure there's room in the line buffer for the column; if not,
2430 double its length. */
2431 line_len += column_len + 1; /* "+1" for space */
2432 if (line_len > args->line_buf_len) {
2433 cp_off = (int) (cp - args->line_buf);
2434 args->line_buf_len = 2 * line_len;
2435 args->line_buf = (char *)g_realloc(args->line_buf, args->line_buf_len + 1);
2436 cp = args->line_buf + cp_off;
2439 /* Right-justify the packet number column. */
2440 if (cf->cinfo.col_fmt[args->visible_cols[i]] == COL_NUMBER)
2441 g_snprintf(cp, column_len+1, "%*s", args->col_widths[i], cf->cinfo.col_data[args->visible_cols[i]]);
2443 g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], cf->cinfo.col_data[args->visible_cols[i]]);
2445 if (i != args->num_visible_cols - 1)
2451 * Generate a bookmark, using the summary line as the title.
2453 if (!print_bookmark(args->print_args->stream, bookmark_name,
2457 if (!print_line(args->print_args->stream, 0, args->line_buf))
2461 * Generate a bookmark, using "Frame N" as the title, as we're not
2462 * printing the summary line.
2464 g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2465 if (!print_bookmark(args->print_args->stream, bookmark_name,
2468 } /* if (print_summary) */
2470 if (args->print_args->print_dissections != print_dissections_none) {
2471 if (args->print_args->print_summary) {
2472 /* Separate the summary line from the tree with a blank line. */
2473 if (!print_line(args->print_args->stream, 0, ""))
2477 /* Print the information in that tree. */
2478 if (!proto_tree_print(args->print_args, &edt, args->print_args->stream))
2481 /* Print a blank line if we print anything after this (aka more than one packet). */
2482 args->print_separator = TRUE;
2484 /* Print a header line if we print any more packet summaries */
2485 if (args->print_args->print_col_headings)
2486 args->print_header_line = TRUE;
2489 if (args->print_args->print_hex) {
2490 if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
2491 if (!print_line(args->print_args->stream, 0, ""))
2494 /* Print the full packet data as hex. */
2495 if (!print_hex_data(args->print_args->stream, &edt))
2498 /* Print a blank line if we print anything after this (aka more than one packet). */
2499 args->print_separator = TRUE;
2501 /* Print a header line if we print any more packet summaries */
2502 if (args->print_args->print_col_headings)
2503 args->print_header_line = TRUE;
2504 } /* if (args->print_args->print_dissections != print_dissections_none) */
2506 epan_dissect_cleanup(&edt);
2508 /* do we want to have a formfeed between each packet from now on? */
2509 if (args->print_args->print_formfeed) {
2510 args->print_formfeed = TRUE;
2516 epan_dissect_cleanup(&edt);
2521 cf_print_packets(capture_file *cf, print_args_t *print_args)
2523 print_callback_args_t callback_args;
2526 int i, cp_off, column_len, line_len;
2527 int num_visible_col = 0, last_visible_col = 0, visible_col_count;
2532 callback_args.print_args = print_args;
2533 callback_args.print_header_line = print_args->print_col_headings;
2534 callback_args.header_line_buf = NULL;
2535 callback_args.header_line_buf_len = 256;
2536 callback_args.print_formfeed = FALSE;
2537 callback_args.print_separator = FALSE;
2538 callback_args.line_buf = NULL;
2539 callback_args.line_buf_len = 256;
2540 callback_args.col_widths = NULL;
2541 callback_args.num_visible_cols = 0;
2542 callback_args.visible_cols = NULL;
2544 if (!print_preamble(print_args->stream, cf->filename)) {
2545 destroy_print_stream(print_args->stream);
2546 return CF_PRINT_WRITE_ERROR;
2549 if (print_args->print_summary) {
2550 /* We're printing packet summaries. Allocate the header line buffer
2551 and get the column widths. */
2552 callback_args.header_line_buf = (char *)g_malloc(callback_args.header_line_buf_len + 1);
2554 /* Find the number of visible columns and the last visible column */
2555 for (i = 0; i < prefs.num_cols; i++) {
2557 clp = g_list_nth(prefs.col_list, i);
2558 if (clp == NULL) /* Sanity check, Invalid column requested */
2561 cfmt = (fmt_data *) clp->data;
2562 if (cfmt->visible) {
2564 last_visible_col = i;
2568 /* Find the widths for each of the columns - maximum of the
2569 width of the title and the width of the data - and construct
2570 a buffer with a line containing the column titles. */
2571 callback_args.num_visible_cols = num_visible_col;
2572 callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2573 callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2574 cp = &callback_args.header_line_buf[0];
2576 visible_col_count = 0;
2577 for (i = 0; i < cf->cinfo.num_cols; i++) {
2579 clp = g_list_nth(prefs.col_list, i);
2580 if (clp == NULL) /* Sanity check, Invalid column requested */
2583 cfmt = (fmt_data *) clp->data;
2584 if (cfmt->visible == FALSE)
2587 /* Save the order of visible columns */
2588 callback_args.visible_cols[visible_col_count] = i;
2590 /* Don't pad the last column. */
2591 if (i == last_visible_col)
2592 callback_args.col_widths[visible_col_count] = 0;
2594 callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.col_title[i]);
2595 data_width = get_column_char_width(get_column_format(i));
2596 if (data_width > callback_args.col_widths[visible_col_count])
2597 callback_args.col_widths[visible_col_count] = data_width;
2600 /* Find the length of the string for this column. */
2601 column_len = (int) strlen(cf->cinfo.col_title[i]);
2602 if (callback_args.col_widths[i] > column_len)
2603 column_len = callback_args.col_widths[visible_col_count];
2605 /* Make sure there's room in the line buffer for the column; if not,
2606 double its length. */
2607 line_len += column_len + 1; /* "+1" for space */
2608 if (line_len > callback_args.header_line_buf_len) {
2609 cp_off = (int) (cp - callback_args.header_line_buf);
2610 callback_args.header_line_buf_len = 2 * line_len;
2611 callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2612 callback_args.header_line_buf_len + 1);
2613 cp = callback_args.header_line_buf + cp_off;
2616 /* Right-justify the packet number column. */
2617 /* if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2618 g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.col_title[i]);
2620 g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.col_title[i]);
2622 if (i != cf->cinfo.num_cols - 1)
2625 visible_col_count++;
2629 /* Now start out the main line buffer with the same length as the
2630 header line buffer. */
2631 callback_args.line_buf_len = callback_args.header_line_buf_len;
2632 callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2633 } /* if (print_summary) */
2635 /* Iterate through the list of packets, printing the packets we were
2637 ret = process_specified_packets(cf, &print_args->range, "Printing",
2638 "selected packets", TRUE, print_packet,
2641 g_free(callback_args.header_line_buf);
2642 g_free(callback_args.line_buf);
2643 g_free(callback_args.col_widths);
2644 g_free(callback_args.visible_cols);
2649 /* Completed successfully. */
2653 /* Well, the user decided to abort the printing.
2655 XXX - note that what got generated before they did that
2656 will get printed if we're piping to a print program; we'd
2657 have to write to a file and then hand that to the print
2658 program to make it actually not print anything. */
2662 /* Error while printing.
2664 XXX - note that what got generated before they did that
2665 will get printed if we're piping to a print program; we'd
2666 have to write to a file and then hand that to the print
2667 program to make it actually not print anything. */
2668 destroy_print_stream(print_args->stream);
2669 return CF_PRINT_WRITE_ERROR;
2672 if (!print_finale(print_args->stream)) {
2673 destroy_print_stream(print_args->stream);
2674 return CF_PRINT_WRITE_ERROR;
2677 if (!destroy_print_stream(print_args->stream))
2678 return CF_PRINT_WRITE_ERROR;
2684 write_pdml_packet(capture_file *cf _U_, frame_data *fdata,
2685 struct wtap_pkthdr *phdr, const guint8 *pd,
2688 FILE *fh = (FILE *)argsp;
2691 /* Create the protocol tree, but don't fill in the column information. */
2692 epan_dissect_init(&edt, TRUE, TRUE);
2693 epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2695 /* Write out the information in that tree. */
2696 proto_tree_write_pdml(&edt, fh);
2698 epan_dissect_cleanup(&edt);
2704 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2709 fh = ws_fopen(print_args->file, "w");
2711 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2713 write_pdml_preamble(fh, cf->filename);
2716 return CF_PRINT_WRITE_ERROR;
2719 /* Iterate through the list of packets, printing the packets we were
2721 ret = process_specified_packets(cf, &print_args->range, "Writing PDML",
2722 "selected packets", TRUE,
2723 write_pdml_packet, fh);
2728 /* Completed successfully. */
2732 /* Well, the user decided to abort the printing. */
2736 /* Error while printing. */
2738 return CF_PRINT_WRITE_ERROR;
2741 write_pdml_finale(fh);
2744 return CF_PRINT_WRITE_ERROR;
2747 /* XXX - check for an error */
2754 write_psml_packet(capture_file *cf, frame_data *fdata,
2755 struct wtap_pkthdr *phdr, const guint8 *pd,
2758 FILE *fh = (FILE *)argsp;
2760 gboolean proto_tree_needed;
2762 /* Fill in the column information, only create the protocol tree
2763 if having custom columns. */
2764 proto_tree_needed = have_custom_cols(&cf->cinfo);
2765 epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2766 col_custom_prime_edt(&edt, &cf->cinfo);
2767 epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2768 epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2770 /* Write out the information in that tree. */
2771 proto_tree_write_psml(&edt, fh);
2773 epan_dissect_cleanup(&edt);
2779 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2784 fh = ws_fopen(print_args->file, "w");
2786 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2788 write_psml_preamble(fh);
2791 return CF_PRINT_WRITE_ERROR;
2794 /* Iterate through the list of packets, printing the packets we were
2796 ret = process_specified_packets(cf, &print_args->range, "Writing PSML",
2797 "selected packets", TRUE,
2798 write_psml_packet, fh);
2803 /* Completed successfully. */
2807 /* Well, the user decided to abort the printing. */
2811 /* Error while printing. */
2813 return CF_PRINT_WRITE_ERROR;
2816 write_psml_finale(fh);
2819 return CF_PRINT_WRITE_ERROR;
2822 /* XXX - check for an error */
2829 write_csv_packet(capture_file *cf, frame_data *fdata,
2830 struct wtap_pkthdr *phdr, const guint8 *pd,
2833 FILE *fh = (FILE *)argsp;
2835 gboolean proto_tree_needed;
2837 /* Fill in the column information, only create the protocol tree
2838 if having custom columns. */
2839 proto_tree_needed = have_custom_cols(&cf->cinfo);
2840 epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2841 col_custom_prime_edt(&edt, &cf->cinfo);
2842 epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2843 epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2845 /* Write out the information in that tree. */
2846 proto_tree_write_csv(&edt, fh);
2848 epan_dissect_cleanup(&edt);
2854 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2859 fh = ws_fopen(print_args->file, "w");
2861 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2863 write_csv_preamble(fh);
2866 return CF_PRINT_WRITE_ERROR;
2869 /* Iterate through the list of packets, printing the packets we were
2871 ret = process_specified_packets(cf, &print_args->range, "Writing CSV",
2872 "selected packets", TRUE,
2873 write_csv_packet, fh);
2878 /* Completed successfully. */
2882 /* Well, the user decided to abort the printing. */
2886 /* Error while printing. */
2888 return CF_PRINT_WRITE_ERROR;
2891 write_csv_finale(fh);
2894 return CF_PRINT_WRITE_ERROR;
2897 /* XXX - check for an error */
2904 write_carrays_packet(capture_file *cf _U_, frame_data *fdata,
2905 struct wtap_pkthdr *phdr,
2906 const guint8 *pd, void *argsp)
2908 FILE *fh = (FILE *)argsp;
2911 epan_dissect_init(&edt, TRUE, TRUE);
2912 epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2913 proto_tree_write_carrays(fdata->num, fh, &edt);
2914 epan_dissect_cleanup(&edt);
2920 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2925 fh = ws_fopen(print_args->file, "w");
2928 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2930 write_carrays_preamble(fh);
2934 return CF_PRINT_WRITE_ERROR;
2937 /* Iterate through the list of packets, printing the packets we were
2939 ret = process_specified_packets(cf, &print_args->range,
2941 "selected packets", TRUE,
2942 write_carrays_packet, fh);
2945 /* Completed successfully. */
2948 /* Well, the user decided to abort the printing. */
2951 /* Error while printing. */
2953 return CF_PRINT_WRITE_ERROR;
2956 write_carrays_finale(fh);
2960 return CF_PRINT_WRITE_ERROR;
2968 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2969 search_direction dir)
2973 mdata.string = string;
2974 mdata.string_len = strlen(string);
2975 return find_packet(cf, match_protocol_tree, &mdata, dir);
2979 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree, match_data *mdata)
2981 mdata->frame_matched = FALSE;
2982 mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2983 mdata->string_len = strlen(mdata->string);
2985 /* Iterate through all the nodes looking for matching text */
2986 proto_tree_children_foreach(tree, match_subtree_text, mdata);
2987 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2991 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2993 match_data *mdata = (match_data *)criterion;
2996 /* Load the frame's data. */
2997 if (!cf_read_frame(cf, fdata)) {
2998 /* Attempt to get the packet failed. */
3002 /* Construct the protocol tree, including the displayed text */
3003 epan_dissect_init(&edt, TRUE, TRUE);
3004 /* We don't need the column information */
3005 epan_dissect_run(&edt, &cf->phdr, buffer_start_ptr(&cf->buf), fdata, NULL);
3007 /* Iterate through all the nodes, seeing if they have text that matches. */
3009 mdata->frame_matched = FALSE;
3010 proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
3011 epan_dissect_cleanup(&edt);
3012 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
3016 match_subtree_text(proto_node *node, gpointer data)
3018 match_data *mdata = (match_data *) data;
3019 const gchar *string = mdata->string;
3020 size_t string_len = mdata->string_len;
3021 capture_file *cf = mdata->cf;
3022 field_info *fi = PNODE_FINFO(node);
3023 gchar label_str[ITEM_LABEL_LENGTH];
3030 /* dissection with an invisible proto tree? */
3033 if (mdata->frame_matched) {
3034 /* We already had a match; don't bother doing any more work. */
3038 /* Don't match invisible entries. */
3039 if (PROTO_ITEM_IS_HIDDEN(node))
3042 /* was a free format label produced? */
3044 label_ptr = fi->rep->representation;
3046 /* no, make a generic label */
3047 label_ptr = label_str;
3048 proto_item_fill_label(fi, label_str);
3051 /* Does that label match? */
3052 label_len = strlen(label_ptr);
3053 for (i = 0; i < label_len; i++) {
3054 c_char = label_ptr[i];
3056 c_char = toupper(c_char);
3057 if (c_char == string[c_match]) {
3059 if (c_match == string_len) {
3060 /* No need to look further; we have a match */
3061 mdata->frame_matched = TRUE;
3069 /* Recurse into the subtree, if it exists */
3070 if (node->first_child != NULL)
3071 proto_tree_children_foreach(node, match_subtree_text, mdata);
3075 cf_find_packet_summary_line(capture_file *cf, const char *string,
3076 search_direction dir)
3080 mdata.string = string;
3081 mdata.string_len = strlen(string);
3082 return find_packet(cf, match_summary_line, &mdata, dir);
3086 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
3088 match_data *mdata = (match_data *)criterion;
3089 const gchar *string = mdata->string;
3090 size_t string_len = mdata->string_len;
3092 const char *info_column;
3093 size_t info_column_len;
3094 match_result result = MR_NOTMATCHED;
3100 /* Load the frame's data. */
3101 if (!cf_read_frame(cf, fdata)) {
3102 /* Attempt to get the packet failed. */
3106 /* Don't bother constructing the protocol tree */
3107 epan_dissect_init(&edt, FALSE, FALSE);
3108 /* Get the column information */
3109 epan_dissect_run(&edt, &cf->phdr, buffer_start_ptr(&cf->buf), fdata,
3112 /* Find the Info column */
3113 for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3114 if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
3115 /* Found it. See if we match. */
3116 info_column = edt.pi.cinfo->col_data[colx];
3117 info_column_len = strlen(info_column);
3118 for (i = 0; i < info_column_len; i++) {
3119 c_char = info_column[i];
3121 c_char = toupper(c_char);
3122 if (c_char == string[c_match]) {
3124 if (c_match == string_len) {
3125 result = MR_MATCHED;
3134 epan_dissect_cleanup(&edt);
3141 } cbs_t; /* "Counted byte string" */
3145 * The current match_* routines only support ASCII case insensitivity and don't
3146 * convert UTF-8 inputs to UTF-16 for matching.
3148 * We could modify them to use the GLib Unicode routines or the International
3149 * Components for Unicode library but it's not apparent that we could do so
3150 * without consuming a lot more CPU and memory or that searching would be
3151 * significantly better.
3155 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3156 search_direction dir)
3161 info.data_len = string_size;
3163 /* String or hex search? */
3165 /* String search - what type of string? */
3166 switch (cf->scs_type) {
3168 case SCS_NARROW_AND_WIDE:
3169 return find_packet(cf, match_narrow_and_wide, &info, dir);
3172 return find_packet(cf, match_narrow, &info, dir);
3175 return find_packet(cf, match_wide, &info, dir);
3178 g_assert_not_reached();
3182 return find_packet(cf, match_binary, &info, dir);
3186 match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
3188 cbs_t *info = (cbs_t *)criterion;
3189 const guint8 *ascii_text = info->data;
3190 size_t textlen = info->data_len;
3191 match_result result;
3198 /* Load the frame's data. */
3199 if (!cf_read_frame(cf, fdata)) {
3200 /* Attempt to get the packet failed. */
3204 result = MR_NOTMATCHED;
3205 buf_len = fdata->cap_len;
3206 pd = buffer_start_ptr(&cf->buf);
3208 while (i < buf_len) {
3211 c_char = toupper(c_char);
3212 if (c_char != '\0') {
3213 if (c_char == ascii_text[c_match]) {
3215 if (c_match == textlen) {
3216 result = MR_MATCHED;
3217 cf->search_pos = i; /* Save the position of the last character
3218 for highlighting the field. */
3223 g_assert(i>=c_match);
3224 i -= (guint32)c_match;
3234 match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
3237 cbs_t *info = (cbs_t *)criterion;
3238 const guint8 *ascii_text = info->data;
3239 size_t textlen = info->data_len;
3240 match_result result;
3246 /* Load the frame's data. */
3247 if (!cf_read_frame(cf, fdata)) {
3248 /* Attempt to get the packet failed. */
3252 result = MR_NOTMATCHED;
3253 buf_len = fdata->cap_len;
3254 pd = buffer_start_ptr(&cf->buf);
3256 while (i < buf_len) {
3259 c_char = toupper(c_char);
3260 if (c_char == ascii_text[c_match]) {
3262 if (c_match == textlen) {
3263 result = MR_MATCHED;
3264 cf->search_pos = i; /* Save the position of the last character
3265 for highlighting the field. */
3270 g_assert(i>=c_match);
3271 i -= (guint32)c_match;
3281 match_wide(capture_file *cf, frame_data *fdata, void *criterion)
3283 cbs_t *info = (cbs_t *)criterion;
3284 const guint8 *ascii_text = info->data;
3285 size_t textlen = info->data_len;
3286 match_result result;
3293 /* Load the frame's data. */
3294 if (!cf_read_frame(cf, fdata)) {
3295 /* Attempt to get the packet failed. */
3299 result = MR_NOTMATCHED;
3300 buf_len = fdata->cap_len;
3301 pd = buffer_start_ptr(&cf->buf);
3303 while (i < buf_len) {
3306 c_char = toupper(c_char);
3307 if (c_char == ascii_text[c_match]) {
3309 if (c_match == textlen) {
3310 result = MR_MATCHED;
3311 cf->search_pos = i; /* Save the position of the last character
3312 for highlighting the field. */
3318 g_assert(i>=(c_match*2));
3319 i -= (guint32)c_match*2;
3328 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3330 cbs_t *info = (cbs_t *)criterion;
3331 const guint8 *binary_data = info->data;
3332 size_t datalen = info->data_len;
3333 match_result result;
3339 /* Load the frame's data. */
3340 if (!cf_read_frame(cf, fdata)) {
3341 /* Attempt to get the packet failed. */
3345 result = MR_NOTMATCHED;
3346 buf_len = fdata->cap_len;
3347 pd = buffer_start_ptr(&cf->buf);
3349 while (i < buf_len) {
3350 if (pd[i] == binary_data[c_match]) {
3352 if (c_match == datalen) {
3353 result = MR_MATCHED;
3354 cf->search_pos = i; /* Save the position of the last character
3355 for highlighting the field. */
3360 g_assert(i>=c_match);
3361 i -= (guint32)c_match;
3370 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3371 search_direction dir)
3373 return find_packet(cf, match_dfilter, sfcode, dir);
3377 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3378 search_direction dir)
3383 if (!dfilter_compile(filter, &sfcode)) {
3385 * XXX - this shouldn't happen, as the filter string is machine
3390 if (sfcode == NULL) {
3392 * XXX - this shouldn't happen, as the filter string is machine
3397 result = find_packet(cf, match_dfilter, sfcode, dir);
3398 dfilter_free(sfcode);
3403 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3405 dfilter_t *sfcode = (dfilter_t *)criterion;
3407 match_result result;
3409 /* Load the frame's data. */
3410 if (!cf_read_frame(cf, fdata)) {
3411 /* Attempt to get the packet failed. */
3415 epan_dissect_init(&edt, TRUE, FALSE);
3416 epan_dissect_prime_dfilter(&edt, sfcode);
3417 epan_dissect_run(&edt, &cf->phdr, buffer_start_ptr(&cf->buf), fdata, NULL);
3418 result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3419 epan_dissect_cleanup(&edt);
3424 cf_find_packet_marked(capture_file *cf, search_direction dir)
3426 return find_packet(cf, match_marked, NULL, dir);
3430 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3432 return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3436 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3438 return find_packet(cf, match_time_reference, NULL, dir);
3442 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3444 return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3448 find_packet(capture_file *cf,
3449 match_result (*match_function)(capture_file *, frame_data *, void *),
3450 void *criterion, search_direction dir)
3452 frame_data *start_fd;
3455 frame_data *new_fd = NULL;
3456 progdlg_t *progbar = NULL;
3461 GTimeVal start_time;
3462 gchar status_str[100];
3463 int progbar_nextstep;
3464 int progbar_quantum;
3466 match_result result;
3468 start_fd = cf->current_frame;
3469 if (start_fd != NULL) {
3470 /* Iterate through the list of packets, starting at the packet we've
3471 picked, calling a routine to run the filter on the packet, see if
3472 it matches, and stop if so. */
3474 framenum = start_fd->num;
3476 /* Update the progress bar when it gets to this value. */
3477 progbar_nextstep = 0;
3478 /* When we reach the value that triggers a progress bar update,
3479 bump that value by this amount. */
3480 progbar_quantum = cf->count/N_PROGBAR_UPDATES;
3481 /* Progress so far. */
3485 g_get_current_time(&start_time);
3487 title = cf->sfilter?cf->sfilter:"";
3489 /* Create the progress bar if necessary.
3490 We check on every iteration of the loop, so that it takes no
3491 longer than the standard time to create it (otherwise, for a
3492 large file, we might take considerably longer than that standard
3493 time in order to get to the next progress bar step). */
3494 if (progbar == NULL)
3495 progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3496 FALSE, &stop_flag, &start_time, progbar_val);
3498 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
3499 when we update it, we have to run the GTK+ main loop to get it
3500 to repaint what's pending, and doing so may involve an "ioctl()"
3501 to see if there's any pending input from an X server, and doing
3502 that for every packet can be costly, especially on a big file. */
3503 if (count >= progbar_nextstep) {
3504 /* let's not divide by zero. I should never be started
3505 * with count == 0, so let's assert that
3507 g_assert(cf->count > 0);
3509 progbar_val = (gfloat) count / cf->count;
3511 if (progbar != NULL) {
3512 g_snprintf(status_str, sizeof(status_str),
3513 "%4u of %u packets", count, cf->count);
3514 update_progress_dlg(progbar, progbar_val, status_str);
3517 progbar_nextstep += progbar_quantum;
3521 /* Well, the user decided to abort the search. Go back to the
3522 frame where we started. */
3527 /* Go past the current frame. */
3528 if (dir == SD_BACKWARD) {
3529 /* Go on to the previous frame. */
3530 if (framenum == 1) {
3532 * XXX - other apps have a bit more of a detailed message
3533 * for this, and instead of offering "OK" and "Cancel",
3534 * they offer things such as "Continue" and "Cancel";
3535 * we need an API for popping up alert boxes with
3536 * {Verb} and "Cancel".
3539 if (prefs.gui_find_wrap)
3541 statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3542 framenum = cf->count; /* wrap around */
3546 statusbar_push_temporary_msg("Search reached the beginning.");
3547 framenum = start_fd->num; /* stay on previous packet */
3552 /* Go on to the next frame. */
3553 if (framenum == cf->count) {
3554 if (prefs.gui_find_wrap)
3556 statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3557 framenum = 1; /* wrap around */
3561 statusbar_push_temporary_msg("Search reached the end.");
3562 framenum = start_fd->num; /* stay on previous packet */
3567 fdata = frame_data_sequence_find(cf->frames, framenum);
3571 /* Is this packet in the display? */
3572 if (fdata->flags.passed_dfilter) {
3573 /* Yes. Does it match the search criterion? */
3574 result = (*match_function)(cf, fdata, criterion);
3575 if (result == MR_ERROR) {
3576 /* Error; our caller has reported the error. Go back to the frame
3577 where we started. */
3580 } else if (result == MR_MATCHED) {
3581 /* Yes. Go to the new frame. */
3587 if (fdata == start_fd) {
3588 /* We're back to the frame we were on originally, and that frame
3589 doesn't match the search filter. The search failed. */
3594 /* We're done scanning the packets; destroy the progress bar if it
3596 if (progbar != NULL)
3597 destroy_progress_dlg(progbar);
3600 if (new_fd != NULL) {
3601 /* Find and select */
3602 cf->search_in_progress = TRUE;
3603 found = packet_list_select_row_from_data(new_fd);
3604 cf->search_in_progress = FALSE;
3605 cf->search_pos = 0; /* Reset the position */
3607 /* We didn't find a row corresponding to this frame.
3608 This means that the frame isn't being displayed currently,
3609 so we can't select it. */
3610 simple_message_box(ESD_TYPE_INFO, NULL,
3611 "The capture file is probably not fully dissected.",
3612 "End of capture exceeded!");
3615 return TRUE; /* success */
3617 return FALSE; /* failure */
3621 cf_goto_frame(capture_file *cf, guint fnumber)
3625 fdata = frame_data_sequence_find(cf->frames, fnumber);
3627 if (fdata == NULL) {
3628 /* we didn't find a packet with that packet number */
3629 statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3630 return FALSE; /* we failed to go to that packet */
3632 if (!fdata->flags.passed_dfilter) {
3633 /* that packet currently isn't displayed */
3634 /* XXX - add it to the set of displayed packets? */
3635 statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3636 return FALSE; /* we failed to go to that packet */
3639 if (!packet_list_select_row_from_data(fdata)) {
3640 /* We didn't find a row corresponding to this frame.
3641 This means that the frame isn't being displayed currently,
3642 so we can't select it. */
3643 simple_message_box(ESD_TYPE_INFO, NULL,
3644 "The capture file is probably not fully dissected.",
3645 "End of capture exceeded!");
3648 return TRUE; /* we got to that packet */
3652 cf_goto_top_frame(void)
3654 /* Find and select */
3655 packet_list_select_first_row();
3656 return TRUE; /* we got to that packet */
3660 cf_goto_bottom_frame(void)
3662 /* Find and select */
3663 packet_list_select_last_row();
3664 return TRUE; /* we got to that packet */
3668 * Go to frame specified by currently selected protocol tree item.
3671 cf_goto_framenum(capture_file *cf)
3673 header_field_info *hfinfo;
3676 if (cf->finfo_selected) {
3677 hfinfo = cf->finfo_selected->hfinfo;
3679 if (hfinfo->type == FT_FRAMENUM) {
3680 framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3682 return cf_goto_frame(cf, framenum);
3689 /* Select the packet on a given row. */
3691 cf_select_packet(capture_file *cf, int row)
3693 epan_dissect_t *old_edt;
3696 /* Get the frame data struct pointer for this frame */
3697 fdata = packet_list_get_row_data(row);
3699 if (fdata == NULL) {
3700 /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
3701 the first entry is added to it by "real_insert_row()", that row
3702 is selected (see "real_insert_row()", in "ui/gtk/gtkclist.c", in both
3703 our version and the vanilla GTK+ version).
3705 This means that a "select-row" signal is emitted; this causes
3706 "packet_list_select_cb()" to be called, which causes "cf_select_packet()"
3709 "cf_select_packet()" fetches, above, the data associated with the
3710 row that was selected; however, as "gtk_clist_append()", which
3711 called "real_insert_row()", hasn't yet returned, we haven't yet
3712 associated any data with that row, so we get back a null pointer.
3714 We can't assume that there's only one frame in the frame list,
3715 either, as we may be filtering the display.
3717 We therefore assume that, if "row" is 0, i.e. the first row
3718 is being selected, and "cf->first_displayed" equals
3719 "cf->last_displayed", i.e. there's only one frame being
3720 displayed, that frame is the frame we want.
3722 This means we have to set "cf->first_displayed" and
3723 "cf->last_displayed" before adding the row to the
3724 GtkCList; see the comment in "add_packet_to_packet_list()". */
3726 if (row == 0 && cf->first_displayed == cf->last_displayed)
3727 fdata = frame_data_sequence_find(cf->frames, cf->first_displayed);
3730 /* If fdata _still_ isn't set simply give up. */
3731 if (fdata == NULL) {
3735 /* Get the data in that frame. */
3736 if (!cf_read_frame (cf, fdata)) {
3740 /* Record that this frame is the current frame. */
3741 cf->current_frame = fdata;
3742 cf->current_row = row;
3745 /* Create the logical protocol tree. */
3746 /* We don't need the columns here. */
3747 cf->edt = epan_dissect_new(TRUE, TRUE);
3749 tap_build_interesting(cf->edt);
3750 epan_dissect_run(cf->edt, &cf->phdr, buffer_start_ptr(&cf->buf),
3751 cf->current_frame, NULL);
3753 dfilter_macro_build_ftv_cache(cf->edt->tree);
3755 cf_callback_invoke(cf_cb_packet_selected, cf);
3757 if (old_edt != NULL)
3758 epan_dissect_free(old_edt);
3762 /* Unselect the selected packet, if any. */
3764 cf_unselect_packet(capture_file *cf)
3766 epan_dissect_t *old_edt = cf->edt;
3770 /* No packet is selected. */
3771 cf->current_frame = NULL;
3772 cf->current_row = 0;
3774 cf_callback_invoke(cf_cb_packet_unselected, cf);
3776 /* No protocol tree means no selected field. */
3777 cf_unselect_field(cf);
3779 /* Destroy the epan_dissect_t for the unselected packet. */
3780 if (old_edt != NULL)
3781 epan_dissect_free(old_edt);
3784 /* Unset the selected protocol tree field, if any. */
3786 cf_unselect_field(capture_file *cf)
3788 cf->finfo_selected = NULL;
3790 cf_callback_invoke(cf_cb_field_unselected, cf);
3794 * Mark a particular frame.
3797 cf_mark_frame(capture_file *cf, frame_data *frame)
3799 if (! frame->flags.marked) {
3800 frame->flags.marked = TRUE;
3801 if (cf->count > cf->marked_count)
3807 * Unmark a particular frame.
3810 cf_unmark_frame(capture_file *cf, frame_data *frame)
3812 if (frame->flags.marked) {
3813 frame->flags.marked = FALSE;
3814 if (cf->marked_count > 0)
3820 * Ignore a particular frame.
3823 cf_ignore_frame(capture_file *cf, frame_data *frame)
3825 if (! frame->flags.ignored) {
3826 frame->flags.ignored = TRUE;
3827 if (cf->count > cf->ignored_count)
3828 cf->ignored_count++;
3833 * Un-ignore a particular frame.
3836 cf_unignore_frame(capture_file *cf, frame_data *frame)
3838 if (frame->flags.ignored) {
3839 frame->flags.ignored = FALSE;
3840 if (cf->ignored_count > 0)
3841 cf->ignored_count--;
3846 * Read the comment in SHB block
3850 cf_read_shb_comment(capture_file *cf)
3852 wtapng_section_t *shb_inf;
3853 const gchar *temp_str;
3855 /* Get info from SHB */
3856 shb_inf = wtap_file_get_shb_info(cf->wth);
3857 if (shb_inf == NULL)
3859 temp_str = shb_inf->opt_comment;
3867 cf_update_capture_comment(capture_file *cf, gchar *comment)
3869 wtapng_section_t *shb_inf;
3871 /* Get info from SHB */
3872 shb_inf = wtap_file_get_shb_info(cf->wth);
3874 /* See if the comment has changed or not */
3875 if (shb_inf && shb_inf->opt_comment) {
3876 if (strcmp(shb_inf->opt_comment, comment) == 0) {
3885 /* The comment has changed, let's update it */
3886 wtap_write_shb_comment(cf->wth, comment);
3887 /* Mark the file as having unsaved changes */
3888 cf->unsaved_changes = TRUE;
3892 cf_update_packet_comment(capture_file *cf, frame_data *fdata, gchar *comment)
3894 if (fdata->opt_comment != NULL) {
3895 /* OK, remove the old comment. */
3896 g_free(fdata->opt_comment);
3897 fdata->opt_comment = NULL;
3898 cf->packet_comment_count--;
3900 if (comment != NULL) {
3901 /* Add the new comment. */
3902 fdata->opt_comment = comment;
3903 cf->packet_comment_count++;
3906 expert_update_comment_count(cf->packet_comment_count);
3908 /* OK, we have unsaved changes. */
3909 cf->unsaved_changes = TRUE;
3913 * What types of comments does this capture file have?
3916 cf_comment_types(capture_file *cf)
3918 guint32 comment_types = 0;
3920 if (cf_read_shb_comment(cf) != NULL)
3921 comment_types |= WTAP_COMMENT_PER_SECTION;
3922 if (cf->packet_comment_count != 0)
3923 comment_types |= WTAP_COMMENT_PER_PACKET;
3924 return comment_types;
3931 } save_callback_args_t;
3934 * Save a capture to a file, in a particular format, saving either
3935 * all packets, all currently-displayed packets, or all marked packets.
3937 * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3938 * up a message box for the failure.
3941 save_packet(capture_file *cf _U_, frame_data *fdata,
3942 struct wtap_pkthdr *phdr, const guint8 *pd,
3945 save_callback_args_t *args = (save_callback_args_t *)argsp;
3946 struct wtap_pkthdr hdr;
3948 gchar *display_basename;
3950 /* init the wtap header for saving */
3951 /* TODO: reuse phdr */
3952 /* XXX - these are the only flags that correspond to data that we have
3953 in the frame_data structure and that matter on a per-packet basis.
3955 For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3956 and "on the wire" lengths, or it doesn't.
3958 For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3961 For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3962 from the packet flags. */
3963 hdr.presence_flags = 0;
3964 if (fdata->flags.has_ts)
3965 hdr.presence_flags |= WTAP_HAS_TS;
3966 if (fdata->flags.has_if_id)
3967 hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3968 if (fdata->flags.has_pack_flags)
3969 hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
3970 hdr.ts.secs = fdata->abs_ts.secs;
3971 hdr.ts.nsecs = fdata->abs_ts.nsecs;
3972 hdr.caplen = fdata->cap_len;
3973 hdr.len = fdata->pkt_len;
3974 hdr.pkt_encap = fdata->lnk_t;
3976 hdr.interface_id = fdata->interface_id; /* identifier of the interface. */
3978 hdr.pack_flags = fdata->pack_flags;
3979 hdr.opt_comment = fdata->opt_comment; /* NULL if not available */
3981 hdr.pseudo_header = phdr->pseudo_header;
3984 hdr.pack_flags = /* XXX - 0 for now (any value for "we don't have it"?) */
3986 /* and save the packet */
3987 if (!wtap_dump(args->pdh, &hdr, pd, &err)) {
3989 /* Wiretap error. */
3992 case WTAP_ERR_UNSUPPORTED_ENCAP:
3994 * This is a problem with the particular frame we're writing;
3995 * note that, and give the frame number.
3997 simple_error_message_box(
3998 "Frame %u has a network type that can't be saved in a \"%s\" file.",
3999 fdata->num, wtap_file_type_string(args->file_type));
4003 display_basename = g_filename_display_basename(args->fname);
4004 simple_error_message_box(
4005 "An error occurred while writing to the file \"%s\": %s.",
4006 display_basename, wtap_strerror(err));
4007 g_free(display_basename);
4012 write_failure_alert_box(args->fname, err);
4020 * Can this capture file be written out in any format using Wiretap
4021 * rather than by copying the raw data?
4024 cf_can_write_with_wiretap(capture_file *cf)
4026 /* We don't care whether we support the comments in this file or not;
4027 if we can't, we'll offer the user the option of discarding the
4029 return wtap_dump_can_write(cf->linktypes, 0);
4033 * Should we let the user do a save?
4037 * the file has unsaved changes, and we can save it in some
4038 * format through Wiretap
4042 * the file is a temporary file and has no unsaved changes (so
4043 * that "saving" it just means copying it).
4045 * XXX - we shouldn't allow files to be edited if they can't be saved,
4046 * so cf->unsaved_changes should be true only if the file can be saved.
4048 * We don't care whether we support the comments in this file or not;
4049 * if we can't, we'll offer the user the option of discarding the
4053 cf_can_save(capture_file *cf)
4055 if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
4056 /* Saved changes, and we can write it out with Wiretap. */
4060 if (cf->is_tempfile && !cf->unsaved_changes) {
4062 * Temporary file with no unsaved changes, so we can just do a
4068 /* Nothing to save. */
4073 * Should we let the user do a "save as"?
4077 * we can save it in some format through Wiretap
4081 * the file is a temporary file and has no unsaved changes (so
4082 * that "saving" it just means copying it).
4084 * XXX - we shouldn't allow files to be edited if they can't be saved,
4085 * so cf->unsaved_changes should be true only if the file can be saved.
4087 * We don't care whether we support the comments in this file or not;
4088 * if we can't, we'll offer the user the option of discarding the
4092 cf_can_save_as(capture_file *cf)
4094 if (wtap_dump_can_write(cf->linktypes, 0)) {
4095 /* We can write it out with Wiretap. */
4099 if (cf->is_tempfile && !cf->unsaved_changes) {
4101 * Temporary file with no unsaved changes, so we can just do a
4107 /* Nothing to save. */
4112 * Does this file have unsaved data?
4115 cf_has_unsaved_data(capture_file *cf)
4118 * If this is a temporary file, or a file with unsaved changes, it
4121 return cf->is_tempfile || cf->unsaved_changes;
4125 * Quick scan to find packet offsets.
4127 static cf_read_status_t
4128 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
4130 const struct wtap_pkthdr *phdr;
4135 progdlg_t *progbar = NULL;
4139 GTimeVal start_time;
4140 gchar status_str[100];
4141 gint64 progbar_nextstep;
4142 gint64 progbar_quantum;
4147 int displayed_once = 0;
4150 /* Close the old handle. */
4151 wtap_close(cf->wth);
4153 /* Open the new file. */
4154 cf->wth = wtap_open_offline(fname, err, &err_info, TRUE);
4155 if (cf->wth == NULL) {
4156 cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
4157 return CF_READ_ERROR;
4160 /* We're scanning a file whose contents should be the same as what
4161 we had before, so we don't discard dissection state etc.. */
4164 /* Set the file name because we need it to set the follow stream filter.
4165 XXX - is that still true? We need it for other reasons, though,
4167 cf->filename = g_strdup(fname);
4169 /* Indicate whether it's a permanent or temporary file. */
4170 cf->is_tempfile = is_tempfile;
4172 /* No user changes yet. */
4173 cf->unsaved_changes = FALSE;
4175 cf->cd_t = wtap_file_type(cf->wth);
4176 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4178 cf->snap = wtap_snapshot_length(cf->wth);
4179 if (cf->snap == 0) {
4180 /* Snapshot length not known. */
4181 cf->has_snap = FALSE;
4182 cf->snap = WTAP_MAX_PACKET_SIZE;
4184 cf->has_snap = TRUE;
4186 name_ptr = g_filename_display_basename(cf->filename);
4188 cf_callback_invoke(cf_cb_file_rescan_started, cf);
4190 /* Record whether the file is compressed.
4191 XXX - do we know this at open time? */
4192 cf->iscompressed = wtap_iscompressed(cf->wth);
4194 /* Find the size of the file. */
4195 size = wtap_file_size(cf->wth, NULL);
4197 /* Update the progress bar when it gets to this value. */
4198 progbar_nextstep = 0;
4199 /* When we reach the value that triggers a progress bar update,
4200 bump that value by this amount. */
4202 progbar_quantum = size/N_PROGBAR_UPDATES;
4203 if (progbar_quantum < MIN_QUANTUM)
4204 progbar_quantum = MIN_QUANTUM;
4206 progbar_quantum = 0;
4207 /* Progress so far. */
4211 g_get_current_time(&start_time);
4214 phdr = wtap_phdr(cf->wth);
4215 while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
4217 fdata = frame_data_sequence_find(cf->frames, framenum);
4218 fdata->file_off = data_offset;
4221 file_pos = wtap_read_so_far(cf->wth);
4223 /* Create the progress bar if necessary.
4224 * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
4226 if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
4227 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
4228 progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4229 TRUE, &stop_flag, &start_time, progbar_val);
4232 /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
4233 when we update it, we have to run the GTK+ main loop to get it
4234 to repaint what's pending, and doing so may involve an "ioctl()"
4235 to see if there's any pending input from an X server, and doing
4236 that for every packet can be costly, especially on a big file. */
4237 if (file_pos >= progbar_nextstep) {
4238 if (progbar != NULL) {
4239 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
4240 /* update the packet bar content on the first run or frequently on very large files */
4242 if (progbar_quantum > 500000 || displayed_once == 0) {
4243 if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
4245 packets_bar_update();
4248 #endif /* HAVE_LIBPCAP */
4249 update_progress_dlg(progbar, progbar_val, status_str);
4251 progbar_nextstep += progbar_quantum;
4256 /* Well, the user decided to abort the rescan. Sadly, as this
4257 isn't a reread, recovering is difficult, so we'll just
4258 close the current capture. */
4262 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4263 it's not already there.
4264 XXX - yes, this is O(N), so if every packet had a different
4265 link-layer encapsulation type, it'd be O(N^2) to read the file, but
4266 there are probably going to be a small number of encapsulation types
4268 cf_add_encapsulation_type(cf, phdr->pkt_encap);
4271 /* Free the display name */
4274 /* We're done reading the file; destroy the progress bar if it was created. */
4275 if (progbar != NULL)
4276 destroy_progress_dlg(progbar);
4278 /* We're done reading sequentially through the file. */
4279 cf->state = FILE_READ_DONE;
4281 /* Close the sequential I/O side, to free up memory it requires. */
4282 wtap_sequential_close(cf->wth);
4284 /* compute the time it took to load the file */
4285 compute_elapsed(&start_time);
4287 /* Set the file encapsulation type now; we don't know what it is until
4288 we've looked at all the packets, as we don't know until then whether
4289 there's more than one type (and thus whether it's
4290 WTAP_ENCAP_PER_PACKET). */
4291 cf->lnk_t = wtap_file_encap(cf->wth);
4293 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4296 /* Our caller will give up at this point. */
4297 return CF_READ_ABORTED;
4301 /* Put up a message box noting that the read failed somewhere along
4302 the line. Don't throw out the stuff we managed to read, though,
4306 case WTAP_ERR_UNSUPPORTED:
4307 simple_error_message_box(
4308 "The capture file contains record data that Wireshark doesn't support.\n(%s)",
4313 case WTAP_ERR_UNSUPPORTED_ENCAP:
4314 simple_error_message_box(
4315 "The capture file has a packet with a network type that Wireshark doesn't support.\n(%s)",
4320 case WTAP_ERR_CANT_READ:
4321 simple_error_message_box(
4322 "An attempt to read from the capture file failed for"
4323 " some unknown reason.");
4326 case WTAP_ERR_SHORT_READ:
4327 simple_error_message_box(
4328 "The capture file appears to have been cut short"
4329 " in the middle of a packet.");
4332 case WTAP_ERR_BAD_FILE:
4333 simple_error_message_box(
4334 "The capture file appears to be damaged or corrupt.\n(%s)",
4339 case WTAP_ERR_DECOMPRESS:
4340 simple_error_message_box(
4341 "The compressed capture file appears to be damaged or corrupt.\n"
4347 simple_error_message_box(
4348 "An error occurred while reading the"
4349 " capture file: %s.", wtap_strerror(*err));
4352 return CF_READ_ERROR;
4358 cf_save_packets(capture_file *cf, const char *fname, guint save_format,
4359 gboolean compressed, gboolean discard_comments,
4360 gboolean dont_reopen)
4363 gchar *fname_new = NULL;
4366 struct addrinfo *addrs;
4370 gchar *display_basename;
4377 save_callback_args_t callback_args;
4379 cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4381 addrs = get_addrinfo_list();
4383 if (save_format == cf->cd_t && compressed == cf->iscompressed
4384 && !discard_comments && !cf->unsaved_changes
4385 && !(addrs && addrs->ai_next &&
4386 wtap_dump_has_name_resolution(save_format))) {
4387 /* We're saving in the format it's already in, and we're
4388 not discarding comments, and there are no changes we have
4389 in memory that aren't saved to the file, and we have no name
4390 resolution blocks to write, so we can just move or copy the raw data. */
4392 if (cf->is_tempfile) {
4393 /* The file being saved is a temporary file from a live
4394 capture, so it doesn't need to stay around under that name;
4395 first, try renaming the capture buffer file to the new name.
4396 This acts as a "safe save", in that, if the file already
4397 exists, the existing file will be removed only if the rename
4400 Sadly, on Windows, as we have the current capture file
4401 open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4402 (to cause the rename to remove an existing target), as
4403 done by ws_stdio_rename() (ws_rename() is #defined to
4404 be ws_stdio_rename() on Windows) will fail.
4406 According to the MSDN documentation for CreateFile(), if,
4407 when we open a capture file, we were to directly do a CreateFile(),
4408 opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4409 convert it to a file descriptor with _open_osfhandle(),
4410 that would allow the file to be renamed out from under us.
4412 However, that doesn't work in practice. Perhaps the problem
4413 is that the process doing the rename is the process that
4414 has the file open. */
4416 if (ws_rename(cf->filename, fname) == 0) {
4417 /* That succeeded - there's no need to copy the source file. */
4418 how_to_save = SAVE_WITH_MOVE;
4420 if (errno == EXDEV) {
4421 /* They're on different file systems, so we have to copy the
4423 how_to_save = SAVE_WITH_COPY;
4425 /* The rename failed, but not because they're on different
4426 file systems - put up an error message. (Or should we
4427 just punt and try to copy? The only reason why I'd
4428 expect the rename to fail and the copy to succeed would
4429 be if we didn't have permission to remove the file from
4430 the temporary directory, and that might be fixable - but
4431 is it worth requiring the user to go off and fix it?) */
4432 cf_rename_failure_alert_box(fname, errno);
4437 how_to_save = SAVE_WITH_COPY;
4440 /* It's a permanent file, so we should copy it, and not remove the
4442 how_to_save = SAVE_WITH_COPY;
4445 if (how_to_save == SAVE_WITH_COPY) {
4446 /* Copy the file, if we haven't moved it. If we're overwriting
4447 an existing file, we do it with a "safe save", by writing
4448 to a new file and, if the write succeeds, renaming the
4449 new file on top of the old file. */
4450 if (file_exists(fname)) {
4451 fname_new = g_strdup_printf("%s~", fname);
4452 if (!copy_file_binary_mode(cf->filename, fname_new))
4455 if (!copy_file_binary_mode(cf->filename, fname))
4460 /* Either we're saving in a different format or we're saving changes,
4461 such as added, modified, or removed comments, that haven't yet
4462 been written to the underlying file; we can't do that by copying
4463 or moving the capture file, we have to do it by writing the packets
4466 wtapng_section_t *shb_hdr = NULL;
4467 wtapng_iface_descriptions_t *idb_inf = NULL;
4470 shb_hdr = wtap_file_get_shb_info(cf->wth);
4471 idb_inf = wtap_file_get_idb_info(cf->wth);
4473 /* Determine what file encapsulation type we should use. */
4474 encap = wtap_dump_file_encap_type(cf->linktypes);
4476 if (file_exists(fname)) {
4477 /* We're overwriting an existing file; write out to a new file,
4478 and, if that succeeds, rename the new file on top of the
4479 old file. That makes this a "safe save", so that we don't
4480 lose the old file if we have a problem writing out the new
4481 file. (If the existing file is the current capture file,
4482 we *HAVE* to do that, otherwise we're overwriting the file
4483 from which we're reading the packets that we're writing!) */
4484 fname_new = g_strdup_printf("%s~", fname);
4485 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4486 compressed, shb_hdr, idb_inf, &err);
4488 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4489 compressed, shb_hdr, idb_inf, &err);
4495 cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4499 /* Add address resolution */
4500 wtap_dump_set_addrinfo_list(pdh, addrs);
4502 /* Iterate through the list of packets, processing all the packets. */
4503 callback_args.pdh = pdh;
4504 callback_args.fname = fname;
4505 callback_args.file_type = save_format;
4506 switch (process_specified_packets(cf, NULL, "Saving", "packets",
4507 TRUE, save_packet, &callback_args)) {
4510 /* Completed successfully. */
4514 /* The user decided to abort the saving.
4515 If we're writing to a temporary file, remove it.
4516 XXX - should we do so even if we're not writing to a
4518 wtap_dump_close(pdh, &err);
4519 if (fname_new != NULL)
4520 ws_unlink(fname_new);
4521 cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4522 return CF_WRITE_ABORTED;
4525 /* Error while saving.
4526 If we're writing to a temporary file, remove it. */
4527 if (fname_new != NULL)
4528 ws_unlink(fname_new);
4529 wtap_dump_close(pdh, &err);
4533 if (!wtap_dump_close(pdh, &err)) {
4534 cf_close_failure_alert_box(fname, err);
4538 how_to_save = SAVE_WITH_WTAP;
4541 if (fname_new != NULL) {
4542 /* We wrote out to fname_new, and should rename it on top of
4543 fname. fname_new is now closed, so that should be possible even
4544 on Windows. However, on Windows, we first need to close whatever
4545 file descriptors we have open for fname. */
4547 wtap_fdclose(cf->wth);
4549 /* Now do the rename. */
4550 if (ws_rename(fname_new, fname) == -1) {
4551 /* Well, the rename failed. */
4552 cf_rename_failure_alert_box(fname, errno);
4554 /* Attempt to reopen the random file descriptor using the
4555 current file's filename. (At this point, the sequential
4556 file descriptor is closed.) */
4557 if (!wtap_fdreopen(cf->wth, cf->filename, &err)) {
4558 /* Oh, well, we're screwed. */
4559 display_basename = g_filename_display_basename(cf->filename);
4560 simple_error_message_box(
4561 file_open_error_message(err, FALSE), display_basename);
4562 g_free(display_basename);
4569 cf_callback_invoke(cf_cb_file_save_finished, NULL);
4570 cf->unsaved_changes = FALSE;
4573 switch (how_to_save) {
4575 case SAVE_WITH_MOVE:
4576 /* We just moved the file, so the wtap structure refers to the
4577 new file, and all the information other than the filename
4578 and the "is temporary" status applies to the new file; just
4580 g_free(cf->filename);
4581 cf->filename = g_strdup(fname);
4582 cf->is_tempfile = FALSE;
4583 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4586 case SAVE_WITH_COPY:
4587 /* We just copied the file, s all the information other than
4588 the wtap structure, the filename, and the "is temporary"
4589 status applies to the new file; just update that. */
4590 wtap_close(cf->wth);
4591 cf->wth = wtap_open_offline(fname, &err, &err_info, TRUE);
4592 if (cf->wth == NULL) {
4593 cf_open_failure_alert_box(fname, err, err_info, FALSE, 0);
4596 g_free(cf->filename);
4597 cf->filename = g_strdup(fname);
4598 cf->is_tempfile = FALSE;
4600 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4603 case SAVE_WITH_WTAP:
4604 /* Open and read the file we saved to.
4606 XXX - this is somewhat of a waste; we already have the
4607 packets, all this gets us is updated file type information
4608 (which we could just stuff into "cf"), and having the new
4609 file be the one we have opened and from which we're reading
4610 the data, and it means we have to spend time opening and
4611 reading the file, which could be a significant amount of
4612 time if the file is large.
4614 If the capture-file-writing code were to return the
4615 seek offset of each packet it writes, we could save that
4616 in the frame_data structure for the frame, and just open
4617 the file without reading it again...
4619 ...as long as, for gzipped files, the process of writing
4620 out the file *also* generates the information needed to
4621 support fast random access to the compressed file. */
4622 if (rescan_file(cf, fname, FALSE, &err) != CF_READ_OK) {
4623 /* The rescan failed; just close the file. Either
4624 a dialog was popped up for the failure, so the
4625 user knows what happened, or they stopped the
4626 rescan, in which case they know what happened. */
4632 /* If we were told to discard the comments, do so. */
4633 if (discard_comments) {
4634 /* Remove SHB comment, if any. */
4635 wtap_write_shb_comment(cf->wth, NULL);
4637 /* Remove packet comments. */
4638 for (framenum = 1; framenum <= cf->count; framenum++) {
4639 fdata = frame_data_sequence_find(cf->frames, framenum);
4640 if (fdata->opt_comment) {
4641 g_free(fdata->opt_comment);
4642 fdata->opt_comment = NULL;
4643 cf->packet_comment_count--;
4651 if (fname_new != NULL) {
4652 /* We were trying to write to a temporary file; get rid of it if it
4653 exists. (We don't care whether this fails, as, if it fails,
4654 there's not much we can do about it. I guess if it failed for
4655 a reason other than "it doesn't exist", we could report an
4656 error, so the user knows there's a junk file that they might
4657 want to clean up.) */
4658 ws_unlink(fname_new);
4661 cf_callback_invoke(cf_cb_file_save_failed, NULL);
4662 return CF_WRITE_ERROR;
4666 cf_export_specified_packets(capture_file *cf, const char *fname,
4667 packet_range_t *range, guint save_format,
4668 gboolean compressed)
4670 gchar *fname_new = NULL;
4673 save_callback_args_t callback_args;
4674 wtapng_section_t *shb_hdr;
4675 wtapng_iface_descriptions_t *idb_inf;
4678 cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4680 packet_range_process_init(range);
4682 /* We're writing out specified packets from the specified capture
4683 file to another file. Even if all captured packets are to be
4684 written, don't special-case the operation - read each packet
4685 and then write it out if it's one of the specified ones. */
4687 shb_hdr = wtap_file_get_shb_info(cf->wth);
4688 idb_inf = wtap_file_get_idb_info(cf->wth);
4690 /* Determine what file encapsulation type we should use. */
4691 encap = wtap_dump_file_encap_type(cf->linktypes);
4693 if (file_exists(fname)) {
4694 /* We're overwriting an existing file; write out to a new file,
4695 and, if that succeeds, rename the new file on top of the
4696 old file. That makes this a "safe save", so that we don't
4697 lose the old file if we have a problem writing out the new
4698 file. (If the existing file is the current capture file,
4699 we *HAVE* to do that, otherwise we're overwriting the file
4700 from which we're reading the packets that we're writing!) */
4701 fname_new = g_strdup_printf("%s~", fname);
4702 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4703 compressed, shb_hdr, idb_inf, &err);
4705 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4706 compressed, shb_hdr, idb_inf, &err);
4712 cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4716 /* Add address resolution */
4717 wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4719 /* Iterate through the list of packets, processing the packets we were
4722 XXX - we've already called "packet_range_process_init(range)", but
4723 "process_specified_packets()" will do it again. Fortunately,
4724 that's harmless in this case, as we haven't done anything to
4725 "range" since we initialized it. */
4726 callback_args.pdh = pdh;
4727 callback_args.fname = fname;
4728 callback_args.file_type = save_format;
4729 switch (process_specified_packets(cf, range, "Writing", "specified packets",
4730 TRUE, save_packet, &callback_args)) {
4733 /* Completed successfully. */
4737 /* The user decided to abort the saving.
4738 If we're writing to a temporary file, remove it.
4739 XXX - should we do so even if we're not writing to a
4741 wtap_dump_close(pdh, &err);
4742 if (fname_new != NULL)
4743 ws_unlink(fname_new);
4744 cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4745 return CF_WRITE_ABORTED;
4749 /* Error while saving.
4750 If we're writing to a temporary file, remove it. */
4751 if (fname_new != NULL)
4752 ws_unlink(fname_new);
4753 wtap_dump_close(pdh, &err);
4757 if (!wtap_dump_close(pdh, &err)) {
4758 cf_close_failure_alert_box(fname, err);
4762 if (fname_new != NULL) {
4763 /* We wrote out to fname_new, and should rename it on top of
4764 fname; fname is now closed, so that should be possible even
4765 on Windows. Do the rename. */
4766 if (ws_rename(fname_new, fname) == -1) {
4767 /* Well, the rename failed. */
4768 cf_rename_failure_alert_box(fname, errno);
4773 cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4777 if (fname_new != NULL) {
4778 /* We were trying to write to a temporary file; get rid of it if it
4779 exists. (We don't care whether this fails, as, if it fails,
4780 there's not much we can do about it. I guess if it failed for
4781 a reason other than "it doesn't exist", we could report an
4782 error, so the user knows there's a junk file that they might
4783 want to clean up.) */
4784 ws_unlink(fname_new);
4787 cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4788 return CF_WRITE_ERROR;
4792 cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
4793 gboolean for_writing, int file_type)
4795 gchar *display_basename;
4798 /* Wiretap error. */
4799 display_basename = g_filename_display_basename(filename);
4802 case WTAP_ERR_NOT_REGULAR_FILE:
4803 simple_error_message_box(
4804 "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
4808 case WTAP_ERR_RANDOM_OPEN_PIPE:
4809 /* Seen only when opening a capture file for reading. */
4810 simple_error_message_box(
4811 "The file \"%s\" is a pipe or FIFO; Wireshark can't read pipe or FIFO files.\n"
4812 "To capture from a pipe or FIFO use wireshark -i -",
4816 case WTAP_ERR_FILE_UNKNOWN_FORMAT:
4817 /* Seen only when opening a capture file for reading. */
4818 simple_error_message_box(
4819 "The file \"%s\" isn't a capture file in a format Wireshark understands.",
4823 case WTAP_ERR_UNSUPPORTED:
4824 /* Seen only when opening a capture file for reading. */
4825 simple_error_message_box(
4826 "The file \"%s\" isn't a capture file in a format Wireshark understands.\n"
4828 display_basename, err_info);
4832 case WTAP_ERR_CANT_WRITE_TO_PIPE:
4833 /* Seen only when opening a capture file for writing. */
4834 simple_error_message_box(
4835 "The file \"%s\" is a pipe, and %s capture files can't be "
4836 "written to a pipe.",
4837 display_basename, wtap_file_type_string(file_type));
4840 case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
4841 /* Seen only when opening a capture file for writing. */
4842 simple_error_message_box(
4843 "Wireshark doesn't support writing capture files in that format.");
4846 case WTAP_ERR_UNSUPPORTED_ENCAP:
4848 simple_error_message_box("Wireshark can't save this capture in that format.");
4850 simple_error_message_box(
4851 "The file \"%s\" is a capture for a network type that Wireshark doesn't support.\n"
4853 display_basename, err_info);
4858 case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
4860 simple_error_message_box(
4861 "Wireshark can't save this capture in that format.");
4863 simple_error_message_box(
4864 "The file \"%s\" is a capture for a network type that Wireshark doesn't support.",
4869 case WTAP_ERR_BAD_FILE:
4870 /* Seen only when opening a capture file for reading. */
4871 simple_error_message_box(
4872 "The file \"%s\" appears to be damaged or corrupt.\n"
4874 display_basename, err_info);
4878 case WTAP_ERR_CANT_OPEN:
4880 simple_error_message_box(
4881 "The file \"%s\" could not be created for some unknown reason.",
4884 simple_error_message_box(
4885 "The file \"%s\" could not be opened for some unknown reason.",
4890 case WTAP_ERR_SHORT_READ:
4891 simple_error_message_box(
4892 "The file \"%s\" appears to have been cut short"
4893 " in the middle of a packet or other data.",
4897 case WTAP_ERR_SHORT_WRITE:
4898 simple_error_message_box(
4899 "A full header couldn't be written to the file \"%s\".",
4903 case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
4904 simple_error_message_box(
4905 "This file type cannot be written as a compressed file.");
4908 case WTAP_ERR_DECOMPRESS:
4909 simple_error_message_box(
4910 "The compressed file \"%s\" appears to be damaged or corrupt.\n"
4911 "(%s)", display_basename, err_info);
4916 simple_error_message_box(
4917 "The file \"%s\" could not be %s: %s.",
4919 for_writing ? "created" : "opened",
4920 wtap_strerror(err));
4923 g_free(display_basename);
4926 open_failure_alert_box(filename, err, for_writing);
4931 * XXX - whether we mention the source pathname, the target pathname,
4932 * or both depends on the error and on what we find if we look for
4933 * one or both of them.
4936 cf_rename_failure_alert_box(const char *filename, int err)
4938 gchar *display_basename;
4940 display_basename = g_filename_display_basename(filename);
4944 /* XXX - should check whether the source exists and, if not,
4945 report it as the problem and, if so, report the destination
4947 simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4952 /* XXX - if we're doing a rename after a safe save, we should
4953 probably say something else. */
4954 simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4959 /* XXX - this should probably mention both the source and destination
4961 simple_error_message_box("The file \"%s\" could not be moved: %s.",
4962 display_basename, wtap_strerror(err));
4965 g_free(display_basename);
4968 /* Check for write errors - if the file is being written to an NFS server,
4969 a write error may not show up until the file is closed, as NFS clients
4970 might not send writes to the server until the "write()" call finishes,
4971 so that the write may fail on the server but the "write()" may succeed. */
4973 cf_close_failure_alert_box(const char *filename, int err)
4975 gchar *display_basename;
4978 /* Wiretap error. */
4979 display_basename = g_filename_display_basename(filename);
4982 case WTAP_ERR_CANT_CLOSE:
4983 simple_error_message_box(
4984 "The file \"%s\" couldn't be closed for some unknown reason.",
4988 case WTAP_ERR_SHORT_WRITE:
4989 simple_error_message_box(
4990 "Not all the packets could be written to the file \"%s\".",
4995 simple_error_message_box(
4996 "An error occurred while closing the file \"%s\": %s.",
4997 display_basename, wtap_strerror(err));
5000 g_free(display_basename);
5003 We assume that a close error from the OS is really a write error. */
5004 write_failure_alert_box(filename, err);
5008 /* Reload the current capture file. */
5010 cf_reload(capture_file *cf) {
5012 gboolean is_tempfile;
5015 /* If the file could be opened, "cf_open()" calls "cf_close()"
5016 to get rid of state for the old capture file before filling in state
5017 for the new capture file. "cf_close()" will remove the file if
5018 it's a temporary file; we don't want that to happen (for one thing,
5019 it'd prevent subsequent reopens from working). Remember whether it's
5020 a temporary file, mark it as not being a temporary file, and then
5021 reopen it as the type of file it was.
5023 Also, "cf_close()" will free "cf->filename", so we must make
5024 a copy of it first. */
5025 filename = g_strdup(cf->filename);
5026 is_tempfile = cf->is_tempfile;
5027 cf->is_tempfile = FALSE;
5028 if (cf_open(cf, filename, is_tempfile, &err) == CF_OK) {
5029 switch (cf_read(cf, TRUE)) {
5033 /* Just because we got an error, that doesn't mean we were unable
5034 to read any of the file; we handle what we could get from the
5038 case CF_READ_ABORTED:
5039 /* The user bailed out of re-reading the capture file; the
5040 capture file has been closed - just free the capture file name
5041 string and return (without changing the last containing
5047 /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
5048 Instead, the file was left open, so we should restore "cf->is_tempfile"
5051 XXX - change the menu? Presumably "cf_open()" will do that;
5052 make sure it does! */
5053 cf->is_tempfile = is_tempfile;
5055 /* "cf_open()" made a copy of the file name we handed it, so
5056 we should free up our copy. */
5066 * indent-tabs-mode: nil
5069 * ex: set shiftwidth=2 tabstop=8 expandtab:
5070 * :indentSize=2:tabSize=8:noTabs=true: