4 * Wireshark - Network traffic analyzer
5 * By Gerald Combs <gerald@wireshark.org>
6 * Copyright 1998 Gerald Combs
8 * SPDX-License-Identifier: GPL-2.0+
21 #include <wsutil/tempfile.h>
22 #include <wsutil/file_util.h>
23 #include <wsutil/filesystem.h>
24 #include <version_info.h>
26 #include <wiretap/merge.h>
28 #include <epan/exceptions.h>
29 #include <epan/epan.h>
30 #include <epan/column.h>
31 #include <epan/packet.h>
32 #include <epan/column-utils.h>
33 #include <epan/expert.h>
34 #include <epan/prefs.h>
35 #include <epan/dfilter/dfilter.h>
36 #include <epan/epan_dissect.h>
38 #include <epan/dissectors/packet-ber.h>
39 #include <epan/timestamp.h>
40 #include <epan/dfilter/dfilter-macro.h>
41 #include <epan/strutil.h>
42 #include <epan/addr_resolv.h>
43 #include <epan/color_filters.h>
48 #include "frame_tvbuff.h"
50 #include "ui/alert_box.h"
51 #include "ui/simple_dialog.h"
52 #include "ui/main_statusbar.h"
53 #include "ui/progress_dlg.h"
54 #include "ui/ws_ui_util.h"
56 /* Needed for addrinfo */
57 #ifdef HAVE_SYS_TYPES_H
58 # include <sys/types.h>
61 #ifdef HAVE_SYS_SOCKET_H
62 #include <sys/socket.h>
65 #ifdef HAVE_NETINET_IN_H
66 # include <netinet/in.h>
70 # include <winsock2.h>
71 # include <ws2tcpip.h>
75 gboolean auto_scroll_live; /* GTK+ only? */
78 static int read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
79 column_info *cinfo, gint64 offset);
81 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);
88 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
90 static void match_subtree_text(proto_node *node, gpointer data);
91 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
93 static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
95 static match_result match_narrow(capture_file *cf, frame_data *fdata,
97 static match_result match_wide(capture_file *cf, frame_data *fdata,
99 static match_result match_binary(capture_file *cf, frame_data *fdata,
101 static match_result match_regex(capture_file *cf, frame_data *fdata,
103 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
105 static match_result match_marked(capture_file *cf, frame_data *fdata,
107 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
109 static gboolean find_packet(capture_file *cf,
110 match_result (*match_function)(capture_file *, frame_data *, void *),
111 void *criterion, search_direction dir);
113 static void cf_rename_failure_alert_box(const char *filename, int err);
114 static void ref_time_packets(capture_file *cf);
116 /* Seconds spent processing packets between pushing UI updates. */
117 #define PROGBAR_UPDATE_INTERVAL 0.150
119 /* Show the progress bar after this many seconds. */
120 #define PROGBAR_SHOW_DELAY 0.5
123 * We could probably use g_signal_...() instead of the callbacks below but that
124 * would require linking our CLI programs to libgobject and creating an object
125 * instance for the signals.
128 cf_callback_t cb_fct;
130 } cf_callback_data_t;
132 static GList *cf_callbacks = NULL;
135 cf_callback_invoke(int event, gpointer data)
137 cf_callback_data_t *cb;
138 GList *cb_item = cf_callbacks;
140 /* there should be at least one interested */
141 g_assert(cb_item != NULL);
143 while (cb_item != NULL) {
144 cb = (cf_callback_data_t *)cb_item->data;
145 cb->cb_fct(event, data, cb->user_data);
146 cb_item = g_list_next(cb_item);
152 cf_callback_add(cf_callback_t func, gpointer user_data)
154 cf_callback_data_t *cb;
156 cb = g_new(cf_callback_data_t,1);
158 cb->user_data = user_data;
160 cf_callbacks = g_list_prepend(cf_callbacks, cb);
164 cf_callback_remove(cf_callback_t func, gpointer user_data)
166 cf_callback_data_t *cb;
167 GList *cb_item = cf_callbacks;
169 while (cb_item != NULL) {
170 cb = (cf_callback_data_t *)cb_item->data;
171 if (cb->cb_fct == func && cb->user_data == user_data) {
172 cf_callbacks = g_list_remove(cf_callbacks, cb);
176 cb_item = g_list_next(cb_item);
179 g_assert_not_reached();
183 cf_timestamp_auto_precision(capture_file *cf)
187 /* don't try to get the file's precision if none is opened */
188 if (cf->state == FILE_CLOSED) {
192 /* Set the column widths of those columns that show the time in
193 "command-line-specified" format. */
194 for (i = 0; i < cf->cinfo.num_cols; i++) {
195 if (col_has_time_fmt(&cf->cinfo, i)) {
196 packet_list_resize_column(i);
202 cf_get_computed_elapsed(capture_file *cf)
204 return cf->computed_elapsed;
208 * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
211 static void compute_elapsed(capture_file *cf, GTimeVal *start_time)
216 g_get_current_time(&time_now);
218 delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
219 time_now.tv_usec - start_time->tv_usec;
221 cf->computed_elapsed = (gulong) (delta_time / 1000); /* ms */
224 static const nstime_t *
225 ws_get_frame_ts(struct packet_provider_data *prov, guint32 frame_num)
227 if (prov->prev_dis && prov->prev_dis->num == frame_num)
228 return &prov->prev_dis->abs_ts;
230 if (prov->prev_cap && prov->prev_cap->num == frame_num)
231 return &prov->prev_cap->abs_ts;
234 frame_data *fd = frame_data_sequence_find(prov->frames, frame_num);
236 return (fd) ? &fd->abs_ts : NULL;
243 ws_epan_new(capture_file *cf)
245 static const struct packet_provider_funcs funcs = {
247 cap_file_provider_get_interface_name,
248 cap_file_provider_get_interface_description,
249 cap_file_provider_get_user_comment
252 return epan_new(&cf->provider, &funcs);
256 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
261 wth = wtap_open_offline(fname, type, err, &err_info, TRUE);
265 /* The open succeeded. Close whatever capture file we had open,
266 and fill in the information for this file. */
269 /* Initialize the packet header. */
270 wtap_phdr_init(&cf->phdr);
272 /* XXX - we really want to initialize this after we've read all
273 the packets, so we know how much we'll ultimately need. */
274 ws_buffer_init(&cf->buf, 1500);
276 /* Create new epan session for dissection.
277 * (The old one was freed in cf_close().)
279 cf->epan = ws_epan_new(cf);
281 /* We're about to start reading the file. */
282 cf->state = FILE_READ_IN_PROGRESS;
284 cf->provider.wth = wth;
287 /* Set the file name because we need it to set the follow stream filter.
288 XXX - is that still true? We need it for other reasons, though,
290 cf->filename = g_strdup(fname);
292 /* Indicate whether it's a permanent or temporary file. */
293 cf->is_tempfile = is_tempfile;
295 /* No user changes yet. */
296 cf->unsaved_changes = FALSE;
298 cf->computed_elapsed = 0;
300 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
301 cf->open_type = type;
302 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
304 cf->packet_comment_count = 0;
305 cf->displayed_count = 0;
306 cf->marked_count = 0;
307 cf->ignored_count = 0;
308 cf->ref_time_count = 0;
309 cf->drops_known = FALSE;
311 cf->snap = wtap_snapshot_length(cf->provider.wth);
313 /* Allocate a frame_data_sequence for the frames in this file */
314 cf->provider.frames = new_frame_data_sequence();
316 nstime_set_zero(&cf->elapsed_time);
317 cf->provider.ref = NULL;
318 cf->provider.prev_dis = NULL;
319 cf->provider.prev_cap = NULL;
322 packet_list_queue_draw();
323 cf_callback_invoke(cf_cb_file_opened, cf);
325 if (cf->cd_t == WTAP_FILE_TYPE_SUBTYPE_BER) {
326 /* tell the BER dissector the file name */
327 ber_set_filename(cf->filename);
330 wtap_set_cb_new_ipv4(cf->provider.wth, add_ipv4_name);
331 wtap_set_cb_new_ipv6(cf->provider.wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
336 cfile_open_failure_alert_box(fname, *err, err_info);
341 * Add an encapsulation type to cf->linktypes.
344 cf_add_encapsulation_type(capture_file *cf, int encap)
348 for (i = 0; i < cf->linktypes->len; i++) {
349 if (g_array_index(cf->linktypes, gint, i) == encap)
350 return; /* it's already there */
352 /* It's not already there - add it. */
353 g_array_append_val(cf->linktypes, encap);
356 /* Reset everything to a pristine state */
358 cf_close(capture_file *cf)
360 cf->stop_flag = FALSE;
361 if (cf->state == FILE_CLOSED)
362 return; /* Nothing to do */
364 /* Die if we're in the middle of reading a file. */
365 g_assert(cf->state != FILE_READ_IN_PROGRESS);
367 cf_callback_invoke(cf_cb_file_closing, cf);
369 /* close things, if not already closed before */
370 color_filters_cleanup();
372 if (cf->provider.wth) {
373 wtap_close(cf->provider.wth);
374 cf->provider.wth = NULL;
376 /* We have no file open... */
377 if (cf->filename != NULL) {
378 /* If it's a temporary file, remove it. */
380 ws_unlink(cf->filename);
381 g_free(cf->filename);
384 /* ...which means we have no changes to that file to save. */
385 cf->unsaved_changes = FALSE;
387 /* no open_routine type */
388 cf->open_type = WTAP_TYPE_AUTO;
390 /* Clean up the packet header. */
391 wtap_phdr_cleanup(&cf->phdr);
393 /* Free up the packet buffer. */
394 ws_buffer_free(&cf->buf);
396 dfilter_free(cf->rfcode);
398 if (cf->provider.frames != NULL) {
399 free_frame_data_sequence(cf->provider.frames);
400 cf->provider.frames = NULL;
402 if (cf->provider.frames_user_comments) {
403 g_tree_destroy(cf->provider.frames_user_comments);
404 cf->provider.frames_user_comments = NULL;
406 cf_unselect_packet(cf); /* nothing to select */
407 cf->first_displayed = 0;
408 cf->last_displayed = 0;
410 /* No frames, no frame selected, no field in that frame selected. */
412 cf->current_frame = 0;
414 cf->finfo_selected = NULL;
416 /* No frame link-layer types, either. */
417 if (cf->linktypes != NULL) {
418 g_array_free(cf->linktypes, TRUE);
419 cf->linktypes = NULL;
422 /* Clear the packet list. */
423 packet_list_freeze();
428 nstime_set_zero(&cf->elapsed_time);
430 reset_tap_listeners();
435 /* We have no file open. */
436 cf->state = FILE_CLOSED;
438 cf_callback_invoke(cf_cb_file_closed, cf);
442 * TRUE if the progress dialog doesn't exist and it looks like we'll
443 * take > 2s to load, FALSE otherwise.
445 static inline gboolean
446 progress_is_slow(progdlg_t *progdlg, GTimer *prog_timer, gint64 size, gint64 pos)
450 if (progdlg) return FALSE;
451 elapsed = g_timer_elapsed(prog_timer, NULL);
452 if ((elapsed / 2 > PROGBAR_SHOW_DELAY && (size / pos) > 2) /* It looks like we're going to be slow. */
453 || elapsed > PROGBAR_SHOW_DELAY) { /* We are indeed slow. */
460 calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
464 progbar_val = (gfloat) file_pos / (gfloat) size;
465 if (progbar_val > 1.0) {
467 /* The file probably grew while we were reading it.
468 * Update file size, and try again.
470 size = wtap_file_size(cf->provider.wth, NULL);
473 progbar_val = (gfloat) file_pos / (gfloat) size;
475 /* If it's still > 1, either "wtap_file_size()" failed (in which
476 * case there's not much we can do about it), or the file
477 * *shrank* (in which case there's not much we can do about
478 * it); just clip the progress value at 1.0.
480 if (progbar_val > 1.0f)
484 g_snprintf(status_str, status_size,
485 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
486 file_pos / 1024, size / 1024);
492 cf_read(capture_file *cf, gboolean reloading)
495 gchar *err_info = NULL;
497 progdlg_t *volatile progbar = NULL;
498 GTimer *prog_timer = g_timer_new();
502 volatile gboolean create_proto_tree;
505 volatile gboolean is_read_aborted = FALSE;
507 /* Compile the current display filter.
508 * We assume this will not fail since cf->dfilter is only set in
509 * cf_filter IFF the filter was valid.
511 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
512 g_assert(!cf->dfilter || (compiled && dfcode));
514 /* Get the union of the flags for all tap listeners. */
515 tap_flags = union_of_tap_listener_flags();
518 * Determine whether we need to create a protocol tree.
521 * we're going to apply a display filter;
523 * one of the tap listeners is going to apply a filter;
525 * one of the tap listeners requires a protocol tree;
527 * a postdissector wants field values or protocols on
531 (dfcode != NULL || have_filtering_tap_listeners() ||
532 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
534 reset_tap_listeners();
536 name_ptr = g_filename_display_basename(cf->filename);
539 cf_callback_invoke(cf_cb_file_reload_started, cf);
541 cf_callback_invoke(cf_cb_file_read_started, cf);
543 /* Record whether the file is compressed.
544 XXX - do we know this at open time? */
545 cf->iscompressed = wtap_iscompressed(cf->provider.wth);
547 /* The packet list window will be empty until the file is completly loaded */
548 packet_list_freeze();
550 cf->stop_flag = FALSE;
551 g_get_current_time(&start_time);
553 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
563 gchar status_str[100];
567 /* If any tap listeners require the columns, construct them. */
568 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
570 /* Find the size of the file. */
571 size = wtap_file_size(cf->provider.wth, NULL);
573 g_timer_start(prog_timer);
575 while ((wtap_read(cf->provider.wth, &err, &err_info, &data_offset))) {
578 file_pos = wtap_read_so_far(cf->provider.wth);
580 /* Create the progress bar if necessary. */
581 if (progress_is_slow(progbar, prog_timer, size, file_pos)) {
582 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
584 progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
585 TRUE, &cf->stop_flag, &start_time, progbar_val);
587 progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
588 TRUE, &cf->stop_flag, &start_time, progbar_val);
592 * Update the progress bar, but do it only after
593 * PROGBAR_UPDATE_INTERVAL has elapsed. Calling update_progress_dlg
594 * and packets_bar_update will likely trigger UI paint events, which
595 * might take a while depending on the platform and display. Reset
596 * our timer *after* painting.
598 if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
599 progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
600 /* update the packet bar content on the first run or frequently on very large files */
601 update_progress_dlg(progbar, progbar_val, status_str);
602 compute_elapsed(cf, &start_time);
603 packets_bar_update();
604 g_timer_start(prog_timer);
608 if (cf->state == FILE_READ_ABORTED) {
609 /* Well, the user decided to exit Wireshark. Break out of the
610 loop, and let the code below (which is called even if there
611 aren't any packets left to read) exit. */
612 is_read_aborted = TRUE;
616 /* Well, the user decided to abort the read. He/She will be warned and
617 it might be enough for him/her to work with the already loaded
619 This is especially true for very large capture files, where you don't
620 want to wait loading the whole file (which may last minutes or even
621 hours even on fast machines) just to see that it was the wrong file. */
624 read_packet(cf, dfcode, &edt, cinfo, data_offset);
627 CATCH(OutOfMemoryError) {
628 simple_message_box(ESD_TYPE_ERROR, NULL,
629 "More information and workarounds can be found at\n"
630 "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
631 "Sorry, but Wireshark has run out of memory and has to terminate now.");
633 /* Could we close the current capture and free up memory from that? */
635 /* we have to terminate, as we cannot recover from the memory error */
641 /* Free the display name */
644 /* Cleanup and release all dfilter resources */
645 dfilter_free(dfcode);
647 epan_dissect_cleanup(&edt);
649 /* We're done reading the file; destroy the progress bar if it was created. */
651 destroy_progress_dlg(progbar);
652 g_timer_destroy(prog_timer);
654 /* We're done reading sequentially through the file. */
655 cf->state = FILE_READ_DONE;
657 /* Close the sequential I/O side, to free up memory it requires. */
658 wtap_sequential_close(cf->provider.wth);
660 /* Allow the protocol dissectors to free up memory that they
661 * don't need after the sequential run-through of the packets. */
662 postseq_cleanup_all_protocols();
664 /* compute the time it took to load the file */
665 compute_elapsed(cf, &start_time);
667 /* Set the file encapsulation type now; we don't know what it is until
668 we've looked at all the packets, as we don't know until then whether
669 there's more than one type (and thus whether it's
670 WTAP_ENCAP_PER_PACKET). */
671 cf->lnk_t = wtap_file_encap(cf->provider.wth);
673 cf->current_frame = frame_data_sequence_find(cf->provider.frames, cf->first_displayed);
678 cf_callback_invoke(cf_cb_file_reload_finished, cf);
680 cf_callback_invoke(cf_cb_file_read_finished, cf);
682 /* If we have any displayed packets to select, select the first of those
683 packets by making the first row the selected row. */
684 if (cf->first_displayed != 0) {
685 packet_list_select_first_row();
688 if (is_read_aborted) {
690 * Well, the user decided to exit Wireshark while reading this *offline*
691 * capture file (Live captures are handled by something like
692 * cf_continue_tail). Clean up accordingly.
695 return CF_READ_ABORTED;
699 simple_message_box(ESD_TYPE_WARN, NULL,
700 "The remaining packets in the file were discarded.\n"
702 "As a lot of packets from the original file will be missing,\n"
703 "remember to be careful when saving the current content to a file.\n",
704 "File loading was cancelled.");
705 return CF_READ_ERROR;
709 /* Put up a message box noting that the read failed somewhere along
710 the line. Don't throw out the stuff we managed to read, though,
712 cfile_read_failure_alert_box(NULL, err, err_info);
713 return CF_READ_ERROR;
720 cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
723 volatile int newly_displayed_packets = 0;
726 gboolean create_proto_tree;
730 /* Compile the current display filter.
731 * We assume this will not fail since cf->dfilter is only set in
732 * cf_filter IFF the filter was valid.
734 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
735 g_assert(!cf->dfilter || (compiled && dfcode));
737 /* Get the union of the flags for all tap listeners. */
738 tap_flags = union_of_tap_listener_flags();
741 * Determine whether we need to create a protocol tree.
744 * we're going to apply a display filter;
746 * one of the tap listeners is going to apply a filter;
748 * one of the tap listeners requires a protocol tree;
750 * a postdissector wants field values or protocols on
754 (dfcode != NULL || have_filtering_tap_listeners() ||
755 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
759 packet_list_check_end();
760 /* Don't freeze/thaw the list when doing live capture */
761 /*packet_list_freeze();*/
763 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
765 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
768 gint64 data_offset = 0;
771 /* If any tap listeners require the columns, construct them. */
772 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
774 while (to_read != 0) {
775 wtap_cleareof(cf->provider.wth);
776 if (!wtap_read(cf->provider.wth, err, &err_info, &data_offset)) {
779 if (cf->state == FILE_READ_ABORTED) {
780 /* Well, the user decided to exit Wireshark. Break out of the
781 loop, and let the code below (which is called even if there
782 aren't any packets left to read) exit. */
785 if (read_packet(cf, dfcode, &edt, (column_info *) cinfo, data_offset) != -1) {
786 newly_displayed_packets++;
791 CATCH(OutOfMemoryError) {
792 simple_message_box(ESD_TYPE_ERROR, NULL,
793 "More information and workarounds can be found at\n"
794 "https://wiki.wireshark.org/KnownBugs/OutOfMemory",
795 "Sorry, but Wireshark has run out of memory and has to terminate now.");
797 /* Could we close the current capture and free up memory from that? */
798 return CF_READ_ABORTED;
800 /* we have to terminate, as we cannot recover from the memory error */
806 /* Update the file encapsulation; it might have changed based on the
807 packets we've read. */
808 cf->lnk_t = wtap_file_encap(cf->provider.wth);
810 /* Cleanup and release all dfilter resources */
811 dfilter_free(dfcode);
813 epan_dissect_cleanup(&edt);
815 /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
816 cf->count, cf->state, *err);*/
818 /* Don't freeze/thaw the list when doing live capture */
819 /*packet_list_thaw();*/
820 /* With the new packet list the first packet
821 * isn't automatically selected.
823 if (!cf->current_frame)
824 packet_list_select_first_row();
826 /* moving to the end of the packet list - if the user requested so and
827 we have some new packets. */
828 if (newly_displayed_packets && auto_scroll_live && cf->count != 0)
829 packet_list_moveto_end();
831 if (cf->state == FILE_READ_ABORTED) {
832 /* Well, the user decided to exit Wireshark. Return CF_READ_ABORTED
833 so that our caller can kill off the capture child process;
834 this will cause an EOF on the pipe from the child, so
835 "cf_finish_tail()" will be called, and it will clean up
837 return CF_READ_ABORTED;
838 } else if (*err != 0) {
839 /* We got an error reading the capture file.
840 XXX - pop up a dialog box instead? */
841 if (err_info != NULL) {
842 g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
843 wtap_strerror(*err), cf->filename, err_info);
846 g_warning("Error \"%s\" while reading \"%s\"",
847 wtap_strerror(*err), cf->filename);
849 return CF_READ_ERROR;
855 cf_fake_continue_tail(capture_file *cf) {
856 cf->state = FILE_READ_DONE;
860 cf_finish_tail(capture_file *cf, int *err)
867 gboolean create_proto_tree;
871 /* Compile the current display filter.
872 * We assume this will not fail since cf->dfilter is only set in
873 * cf_filter IFF the filter was valid.
875 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
876 g_assert(!cf->dfilter || (compiled && dfcode));
878 /* Get the union of the flags for all tap listeners. */
879 tap_flags = union_of_tap_listener_flags();
881 /* If any tap listeners require the columns, construct them. */
882 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
885 * Determine whether we need to create a protocol tree.
888 * we're going to apply a display filter;
890 * one of the tap listeners is going to apply a filter;
892 * one of the tap listeners requires a protocol tree;
894 * a postdissector wants field values or protocols on
898 (dfcode != NULL || have_filtering_tap_listeners() ||
899 (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
901 if (cf->provider.wth == NULL) {
903 return CF_READ_ERROR;
906 packet_list_check_end();
907 /* Don't freeze/thaw the list when doing live capture */
908 /*packet_list_freeze();*/
910 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
912 while ((wtap_read(cf->provider.wth, err, &err_info, &data_offset))) {
913 if (cf->state == FILE_READ_ABORTED) {
914 /* Well, the user decided to abort the read. Break out of the
915 loop, and let the code below (which is called even if there
916 aren't any packets left to read) exit. */
919 read_packet(cf, dfcode, &edt, cinfo, data_offset);
922 /* Cleanup and release all dfilter resources */
923 dfilter_free(dfcode);
925 epan_dissect_cleanup(&edt);
927 /* Don't freeze/thaw the list when doing live capture */
928 /*packet_list_thaw();*/
930 if (cf->state == FILE_READ_ABORTED) {
931 /* Well, the user decided to abort the read. We're only called
932 when the child capture process closes the pipe to us (meaning
933 it's probably exited), so we can just close the capture
934 file; we return CF_READ_ABORTED so our caller can do whatever
935 is appropriate when that happens. */
937 return CF_READ_ABORTED;
940 if (auto_scroll_live && cf->count != 0)
941 packet_list_moveto_end();
943 /* We're done reading sequentially through the file. */
944 cf->state = FILE_READ_DONE;
946 /* We're done reading sequentially through the file; close the
947 sequential I/O side, to free up memory it requires. */
948 wtap_sequential_close(cf->provider.wth);
950 /* Allow the protocol dissectors to free up memory that they
951 * don't need after the sequential run-through of the packets. */
952 postseq_cleanup_all_protocols();
954 /* Update the file encapsulation; it might have changed based on the
955 packets we've read. */
956 cf->lnk_t = wtap_file_encap(cf->provider.wth);
958 /* Update the details in the file-set dialog, as the capture file
959 * has likely grown since we first stat-ed it */
960 fileset_update_file(cf->filename);
963 /* We got an error reading the capture file.
964 XXX - pop up a dialog box? */
965 if (err_info != NULL) {
966 g_warning("Error \"%s\" while reading \"%s\" (\"%s\")",
967 wtap_strerror(*err), cf->filename, err_info);
970 g_warning("Error \"%s\" while reading \"%s\"",
971 wtap_strerror(*err), cf->filename);
973 return CF_READ_ERROR;
978 #endif /* HAVE_LIBPCAP */
981 cf_get_display_name(capture_file *cf)
985 /* Return a name to use in displays */
986 if (!cf->is_tempfile) {
987 /* Get the last component of the file name, and use that. */
989 displayname = g_filename_display_basename(cf->filename);
991 displayname=g_strdup("(No file)");
994 /* The file we read is a temporary file from a live capture or
995 a merge operation; we don't mention its name, but, if it's
996 from a capture, give the source of the capture. */
998 displayname = g_strdup(cf->source);
1000 displayname = g_strdup("(Untitled)");
1006 void cf_set_tempfile_source(capture_file *cf, gchar *source) {
1012 cf->source = g_strdup(source);
1014 cf->source = g_strdup("");
1018 const gchar *cf_get_tempfile_source(capture_file *cf) {
1026 /* XXX - use a macro instead? */
1028 cf_get_packet_count(capture_file *cf)
1033 /* XXX - use a macro instead? */
1035 cf_is_tempfile(capture_file *cf)
1037 return cf->is_tempfile;
1040 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
1042 cf->is_tempfile = is_tempfile;
1046 /* XXX - use a macro instead? */
1047 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
1049 cf->drops_known = drops_known;
1052 /* XXX - use a macro instead? */
1053 void cf_set_drops(capture_file *cf, guint32 drops)
1058 /* XXX - use a macro instead? */
1059 gboolean cf_get_drops_known(capture_file *cf)
1061 return cf->drops_known;
1064 /* XXX - use a macro instead? */
1065 guint32 cf_get_drops(capture_file *cf)
1070 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1072 cf->rfcode = rfcode;
1076 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
1077 epan_dissect_t *edt, dfilter_t *dfcode, column_info *cinfo,
1078 struct wtap_pkthdr *phdr, const guint8 *buf, gboolean add_to_packet_list)
1082 frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1083 &cf->provider.ref, cf->provider.prev_dis);
1084 cf->provider.prev_cap = fdata;
1086 if (dfcode != NULL) {
1087 epan_dissect_prime_with_dfilter(edt, dfcode);
1090 /* Prepare coloring rules, this ensures that display filter rules containing
1091 * frame.color_rule references are still processed.
1092 * TODO: actually detect that situation or maybe apply other optimizations? */
1093 if (edt->tree && color_filters_used()) {
1094 color_filters_prime_edt(edt);
1095 fdata->flags.need_colorize = 1;
1099 if (!fdata->flags.visited) {
1100 /* This is the first pass, so prime the epan_dissect_t with the
1101 hfids postdissectors want on the first pass. */
1102 prime_epan_dissect_with_postdissector_wanted_hfids(edt);
1105 /* Dissect the frame. */
1106 epan_dissect_run_with_taps(edt, cf->cd_t, phdr,
1107 frame_tvbuff_new(&cf->provider, fdata, buf),
1110 /* If we don't have a display filter, set "passed_dfilter" to 1. */
1111 if (dfcode != NULL) {
1112 fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, edt) ? 1 : 0;
1114 if (fdata->flags.passed_dfilter) {
1115 /* This frame passed the display filter but it may depend on other
1116 * (potentially not displayed) frames. Find those frames and mark them
1119 g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
1122 fdata->flags.passed_dfilter = 1;
1124 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1125 cf->displayed_count++;
1127 if (add_to_packet_list) {
1128 /* We fill the needed columns from new_packet_list */
1129 row = packet_list_append(cinfo, fdata);
1132 if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1134 frame_data_set_after_dissect(fdata, &cf->cum_bytes);
1135 cf->provider.prev_dis = fdata;
1137 /* If we haven't yet seen the first frame, this is it. */
1138 if (cf->first_displayed == 0)
1139 cf->first_displayed = fdata->num;
1141 /* This is the last frame we've seen so far. */
1142 cf->last_displayed = fdata->num;
1145 epan_dissect_reset(edt);
1149 /* read in a new packet */
1150 /* returns the row of the new packet in the packet list or -1 if not displayed */
1152 read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
1153 column_info *cinfo, gint64 offset)
1155 struct wtap_pkthdr *phdr = wtap_phdr(cf->provider.wth);
1156 const guint8 *buf = wtap_buf_ptr(cf->provider.wth);
1160 gboolean passed = TRUE;
1163 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
1164 it's not already there.
1165 XXX - yes, this is O(N), so if every packet had a different
1166 link-layer encapsulation type, it'd be O(N^2) to read the file, but
1167 there are probably going to be a small number of encapsulation types
1169 cf_add_encapsulation_type(cf, phdr->pkt_encap);
1171 /* The frame number of this packet is one more than the count of
1172 frames in the file so far. */
1173 framenum = cf->count + 1;
1175 frame_data_init(&fdlocal, framenum, phdr, offset, cf->cum_bytes);
1178 epan_dissect_t rf_edt;
1180 epan_dissect_init(&rf_edt, cf->epan, TRUE, FALSE);
1181 epan_dissect_prime_with_dfilter(&rf_edt, cf->rfcode);
1182 epan_dissect_run(&rf_edt, cf->cd_t, phdr,
1183 frame_tvbuff_new(&cf->provider, &fdlocal, buf),
1185 passed = dfilter_apply_edt(cf->rfcode, &rf_edt);
1186 epan_dissect_cleanup(&rf_edt);
1190 /* This does a shallow copy of fdlocal, which is good enough. */
1191 fdata = frame_data_sequence_add(cf->provider.frames, &fdlocal);
1194 if (phdr->opt_comment != NULL)
1195 cf->packet_comment_count++;
1196 cf->f_datalen = offset + fdlocal.cap_len;
1198 if (!cf->redissecting) {
1199 row = add_packet_to_packet_list(fdata, cf, edt, dfcode,
1200 cinfo, phdr, buf, TRUE);
1208 typedef struct _callback_data_t {
1211 GTimeVal start_time;
1219 merge_callback(merge_event event, int num _U_,
1220 const merge_in_file_t in_files[], const guint in_file_count,
1224 callback_data_t *cb_data = (callback_data_t*) data;
1226 g_assert(cb_data != NULL);
1230 case MERGE_EVENT_INPUT_FILES_OPENED:
1234 case MERGE_EVENT_FRAME_TYPE_SELECTED:
1238 case MERGE_EVENT_READY_TO_MERGE:
1239 /* Get the sum of the sizes of all the files. */
1240 for (i = 0; i < in_file_count; i++)
1241 cb_data->f_len += in_files[i].size;
1243 cb_data->prog_timer = g_timer_new();
1244 g_timer_start(cb_data->prog_timer);
1246 g_get_current_time(&cb_data->start_time);
1249 case MERGE_EVENT_PACKET_WAS_READ:
1251 gint64 data_offset = 0;
1253 /* Get the sum of the data offsets in all of the files. */
1255 for (i = 0; i < in_file_count; i++)
1256 data_offset += in_files[i].data_offset;
1258 /* Create the progress bar if necessary.
1259 We check on every iteration of the loop, so that it takes no
1260 longer than the standard time to create it (otherwise, for a
1261 large file, we might take considerably longer than that standard
1262 time in order to get to the next progress bar step). */
1263 if (cb_data->progbar == NULL) {
1264 cb_data->progbar = delayed_create_progress_dlg(cb_data->pd_window, "Merging", "files",
1265 FALSE, &cb_data->stop_flag, &cb_data->start_time, 0.0f);
1269 * Update the progress bar, but do it only after
1270 * PROGBAR_UPDATE_INTERVAL has elapsed. Calling update_progress_dlg
1271 * and packets_bar_update will likely trigger UI paint events, which
1272 * might take a while depending on the platform and display. Reset
1273 * our timer *after* painting.
1275 if (g_timer_elapsed(cb_data->prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
1277 gint64 file_pos = 0;
1278 /* Get the sum of the seek positions in all of the files. */
1279 for (i = 0; i < in_file_count; i++)
1280 file_pos += wtap_read_so_far(in_files[i].wth);
1282 progbar_val = (gfloat) file_pos / (gfloat) cb_data->f_len;
1283 if (progbar_val > 1.0f) {
1284 /* Some file probably grew while we were reading it.
1285 That "shouldn't happen", so we'll just clip the progress
1290 if (cb_data->progbar != NULL) {
1291 gchar status_str[100];
1292 g_snprintf(status_str, sizeof(status_str),
1293 "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
1294 file_pos / 1024, cb_data->f_len / 1024);
1295 update_progress_dlg(cb_data->progbar, progbar_val, status_str);
1297 g_timer_start(cb_data->prog_timer);
1302 case MERGE_EVENT_DONE:
1303 /* We're done merging the files; destroy the progress bar if it was created. */
1304 if (cb_data->progbar != NULL)
1305 destroy_progress_dlg(cb_data->progbar);
1306 g_timer_destroy(cb_data->prog_timer);
1310 return cb_data->stop_flag;
1316 cf_merge_files_to_tempfile(gpointer pd_window, char **out_filenamep,
1317 int in_file_count, char *const *in_filenames,
1318 int file_type, gboolean do_append)
1321 gchar *err_info = NULL;
1323 guint32 err_framenum;
1324 merge_result status;
1325 merge_progress_callback_t cb;
1326 callback_data_t *cb_data = g_new0(callback_data_t, 1);
1328 /* prepare our callback routine */
1329 cb_data->pd_window = pd_window;
1330 cb.callback_func = merge_callback;
1333 cf_callback_invoke(cf_cb_file_merge_started, NULL);
1335 /* merge the files */
1336 status = merge_files_to_tempfile(out_filenamep, "wireshark", file_type,
1337 (const char *const *) in_filenames,
1338 in_file_count, do_append,
1339 IDB_MERGE_MODE_ALL_SAME, 0 /* snaplen */,
1340 "Wireshark", &cb, &err, &err_info,
1341 &err_fileno, &err_framenum);
1349 case MERGE_USER_ABORTED:
1350 /* this isn't really an error, though we will return CF_ERROR later */
1353 case MERGE_ERR_CANT_OPEN_INFILE:
1354 cfile_open_failure_alert_box(in_filenames[err_fileno], err, err_info);
1357 case MERGE_ERR_CANT_OPEN_OUTFILE:
1358 cfile_dump_open_failure_alert_box(*out_filenamep, err, file_type);
1361 case MERGE_ERR_CANT_READ_INFILE:
1362 cfile_read_failure_alert_box(in_filenames[err_fileno], err, err_info);
1365 case MERGE_ERR_BAD_PHDR_INTERFACE_ID:
1366 simple_error_message_box("Record %u of \"%s\" has an interface ID that does not match any IDB in its file.",
1367 err_framenum, in_filenames[err_fileno]);
1370 case MERGE_ERR_CANT_WRITE_OUTFILE:
1371 cfile_write_failure_alert_box(in_filenames[err_fileno],
1372 *out_filenamep, err, err_info,
1373 err_framenum, file_type);
1376 case MERGE_ERR_CANT_CLOSE_OUTFILE:
1377 cfile_close_failure_alert_box(*out_filenamep, err);
1381 simple_error_message_box("Unknown merge_files error %d", status);
1385 cf_callback_invoke(cf_cb_file_merge_finished, NULL);
1387 if (status != MERGE_OK) {
1388 /* Callers aren't expected to treat an error or an explicit abort
1389 differently - we put up error dialogs ourselves, so they don't
1397 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1399 const char *filter_new = dftext ? dftext : "";
1400 const char *filter_old = cf->dfilter ? cf->dfilter : "";
1403 GTimeVal start_time;
1405 /* if new filter equals old one, do nothing unless told to do so */
1406 if (!force && strcmp(filter_new, filter_old) == 0) {
1412 if (dftext == NULL) {
1413 /* The new filter is an empty filter (i.e., display all packets).
1414 * so leave dfcode==NULL
1418 * We have a filter; make a copy of it (as we'll be saving it),
1419 * and try to compile it.
1421 dftext = g_strdup(dftext);
1422 if (!dfilter_compile(dftext, &dfcode, &err_msg)) {
1423 /* The attempt failed; report an error. */
1424 simple_message_box(ESD_TYPE_ERROR, NULL,
1425 "See the help for a description of the display filter syntax.",
1426 "\"%s\" isn't a valid display filter: %s",
1434 if (dfcode == NULL) {
1435 /* Yes - free the filter text, and set it to null. */
1441 /* We have a valid filter. Replace the current filter. */
1442 g_free(cf->dfilter);
1443 cf->dfilter = dftext;
1444 g_get_current_time(&start_time);
1447 /* Now rescan the packet list, applying the new filter, but not
1448 throwing away information constructed on a previous pass. */
1449 if (cf->state != FILE_CLOSED) {
1450 if (dftext == NULL) {
1451 rescan_packets(cf, "Resetting", "Filter", FALSE);
1453 rescan_packets(cf, "Filtering", dftext, FALSE);
1457 /* Cleanup and release all dfilter resources */
1458 dfilter_free(dfcode);
1464 cf_reftime_packets(capture_file *cf)
1466 ref_time_packets(cf);
1470 cf_redissect_packets(capture_file *cf)
1472 if (cf->state != FILE_CLOSED) {
1473 rescan_packets(cf, "Reprocessing", "all packets", TRUE);
1478 cf_read_record_r(capture_file *cf, const frame_data *fdata,
1479 struct wtap_pkthdr *phdr, Buffer *buf)
1484 if (!wtap_seek_read(cf->provider.wth, fdata->file_off, phdr, buf, &err, &err_info)) {
1485 cfile_read_failure_alert_box(cf->filename, err, err_info);
1492 cf_read_record(capture_file *cf, frame_data *fdata)
1494 return cf_read_record_r(cf, fdata, &cf->phdr, &cf->buf);
1497 /* Rescan the list of packets, reconstructing the CList.
1499 "action" describes why we're doing this; it's used in the progress
1502 "action_item" describes what we're doing; it's used in the progress
1505 "redissect" is TRUE if we need to make the dissectors reconstruct
1506 any state information they have (because a preference that affects
1507 some dissector has changed, meaning some dissector might construct
1508 its state differently from the way it was constructed the last time). */
1510 rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
1512 /* Rescan packets new packet list */
1515 progdlg_t *progbar = NULL;
1516 GTimer *prog_timer = g_timer_new();
1518 frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1519 int selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
1520 gboolean selected_frame_seen;
1522 GTimeVal start_time;
1523 gchar status_str[100];
1527 gboolean create_proto_tree;
1529 gboolean add_to_packet_list = FALSE;
1531 guint32 frames_count;
1533 /* Compile the current display filter.
1534 * We assume this will not fail since cf->dfilter is only set in
1535 * cf_filter IFF the filter was valid.
1537 compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
1538 g_assert(!cf->dfilter || (compiled && dfcode));
1540 /* Get the union of the flags for all tap listeners. */
1541 tap_flags = union_of_tap_listener_flags();
1543 /* If any tap listeners require the columns, construct them. */
1544 cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
1547 * Determine whether we need to create a protocol tree.
1550 * we're going to apply a display filter;
1552 * one of the tap listeners is going to apply a filter;
1554 * one of the tap listeners requires a protocol tree;
1556 * we're redissecting and a postdissector wants field
1557 * values or protocols on the first pass.
1560 (dfcode != NULL || have_filtering_tap_listeners() ||
1561 (tap_flags & TL_REQUIRES_PROTO_TREE) ||
1562 (redissect && postdissectors_want_hfids()));
1564 reset_tap_listeners();
1565 /* Which frame, if any, is the currently selected frame?
1566 XXX - should the selected frame or the focus frame be the "current"
1567 frame, that frame being the one from which "Find Frame" searches
1569 selected_frame = cf->current_frame;
1571 /* Mark frame num as not found */
1572 selected_frame_num = -1;
1574 /* Freeze the packet list while we redo it, so we don't get any
1575 screen updates while it happens. */
1576 packet_list_freeze();
1579 /* We need to re-initialize all the state information that protocols
1580 keep, because some preference that controls a dissector has changed,
1581 which might cause the state information to be constructed differently
1582 by that dissector. */
1584 /* We might receive new packets while redissecting, and we don't
1585 want to dissect those before their time. */
1586 cf->redissecting = TRUE;
1588 /* 'reset' dissection session */
1589 epan_free(cf->epan);
1590 if (cf->edt && cf->edt->pi.fd) {
1591 /* All pointers in "per frame proto data" for the currently selected
1592 packet are allocated in wmem_file_scope() and deallocated in epan_free().
1593 Free them here to avoid unintended usage in packet_list_clear(). */
1594 frame_data_destroy(cf->edt->pi.fd);
1596 cf->epan = ws_epan_new(cf);
1597 cf->cinfo.epan = cf->epan;
1599 /* A new Lua tap listener may be registered in lua_prime_all_fields()
1600 called via epan_new() / init_dissection() when reloading Lua plugins. */
1601 if (!create_proto_tree && have_filtering_tap_listeners()) {
1602 create_proto_tree = TRUE;
1605 /* We need to redissect the packets so we have to discard our old
1606 * packet list store. */
1607 packet_list_clear();
1608 add_to_packet_list = TRUE;
1611 /* We don't yet know which will be the first and last frames displayed. */
1612 cf->first_displayed = 0;
1613 cf->last_displayed = 0;
1615 /* We currently don't display any packets */
1616 cf->displayed_count = 0;
1618 /* Iterate through the list of frames. Call a routine for each frame
1619 to check whether it should be displayed and, if so, add it to
1620 the display list. */
1621 cf->provider.ref = NULL;
1622 cf->provider.prev_dis = NULL;
1623 cf->provider.prev_cap = NULL;
1626 cf_callback_invoke(cf_cb_file_rescan_started, cf);
1628 g_timer_start(prog_timer);
1629 /* Count of packets at which we've looked. */
1631 /* Progress so far. */
1634 cf->stop_flag = FALSE;
1635 g_get_current_time(&start_time);
1637 /* no previous row yet */
1638 prev_frame_num = -1;
1641 preceding_frame_num = -1;
1642 preceding_frame = NULL;
1643 following_frame_num = -1;
1644 following_frame = NULL;
1646 selected_frame_seen = FALSE;
1648 frames_count = cf->count;
1650 epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
1652 for (framenum = 1; framenum <= frames_count; framenum++) {
1653 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1655 /* Create the progress bar if necessary.
1656 We check on every iteration of the loop, so that it takes no
1657 longer than the standard time to create it (otherwise, for a
1658 large file, we might take considerably longer than that standard
1659 time in order to get to the next progress bar step). */
1660 if (progbar == NULL)
1661 progbar = delayed_create_progress_dlg(cf->window, action, action_item, TRUE,
1667 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
1668 * has elapsed. Calling update_progress_dlg and packets_bar_update will
1669 * likely trigger UI paint events, which might take a while depending on
1670 * the platform and display. Reset our timer *after* painting.
1672 if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
1673 /* let's not divide by zero. I should never be started
1674 * with count == 0, so let's assert that
1676 g_assert(cf->count > 0);
1677 progbar_val = (gfloat) count / frames_count;
1679 if (progbar != NULL) {
1680 g_snprintf(status_str, sizeof(status_str),
1681 "%4u of %u frames", count, frames_count);
1682 update_progress_dlg(progbar, progbar_val, status_str);
1685 g_timer_start(prog_timer);
1688 if (cf->stop_flag) {
1689 /* Well, the user decided to abort the filtering. Just stop.
1691 XXX - go back to the previous filter? Users probably just
1692 want not to wait for a filtering operation to finish;
1693 unless we cancel by having no filter, reverting to the
1694 previous filter will probably be even more expensive than
1695 continuing the filtering, as it involves going back to the
1696 beginning and filtering, and even with no filter we currently
1697 have to re-generate the entire clist, which is also expensive.
1699 I'm not sure what Network Monitor does, but it doesn't appear
1700 to give you an unfiltered display if you cancel. */
1707 /* Since all state for the frame was destroyed, mark the frame
1708 * as not visited, free the GSList referring to the state
1709 * data (the per-frame data itself was freed by
1710 * "init_dissection()"), and null out the GSList pointer. */
1711 frame_data_reset(fdata);
1712 frames_count = cf->count;
1715 /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1716 fdata->flags.dependent_of_displayed = 0;
1718 if (!cf_read_record(cf, fdata))
1719 break; /* error reading the frame */
1721 /* If the previous frame is displayed, and we haven't yet seen the
1722 selected frame, remember that frame - it's the closest one we've
1723 yet seen before the selected frame. */
1724 if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->flags.passed_dfilter) {
1725 preceding_frame_num = prev_frame_num;
1726 preceding_frame = prev_frame;
1729 add_packet_to_packet_list(fdata, cf, &edt, dfcode,
1731 ws_buffer_start_ptr(&cf->buf),
1732 add_to_packet_list);
1734 /* If this frame is displayed, and this is the first frame we've
1735 seen displayed after the selected frame, remember this frame -
1736 it's the closest one we've yet seen at or after the selected
1738 if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1739 following_frame_num = fdata->num;
1740 following_frame = fdata;
1742 if (fdata == selected_frame) {
1743 selected_frame_seen = TRUE;
1744 if (fdata->flags.passed_dfilter)
1745 selected_frame_num = fdata->num;
1748 /* Remember this frame - it'll be the previous frame
1749 on the next pass through the loop. */
1750 prev_frame_num = fdata->num;
1754 epan_dissect_cleanup(&edt);
1756 /* We are done redissecting the packet list. */
1757 cf->redissecting = FALSE;
1760 frames_count = cf->count;
1761 /* Clear out what remains of the visited flags and per-frame data
1764 XXX - that may cause various forms of bogosity when dissecting
1765 these frames, as they won't have been seen by this sequential
1766 pass, but the only alternative I see is to keep scanning them
1767 even though the user requested that the scan stop, and that
1768 would leave the user stuck with an Wireshark grinding on
1769 until it finishes. Should we just stick them with that? */
1770 for (; framenum <= frames_count; framenum++) {
1771 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1772 frame_data_reset(fdata);
1776 /* We're done filtering the packets; destroy the progress bar if it
1778 if (progbar != NULL)
1779 destroy_progress_dlg(progbar);
1780 g_timer_destroy(prog_timer);
1782 /* Unfreeze the packet list. */
1783 if (!add_to_packet_list)
1784 packet_list_recreate_visible_rows();
1786 /* Compute the time it took to filter the file */
1787 compute_elapsed(cf, &start_time);
1791 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
1793 if (selected_frame_num == -1) {
1794 /* The selected frame didn't pass the filter. */
1795 if (selected_frame == NULL) {
1796 /* That's because there *was* no selected frame. Make the first
1797 displayed frame the current frame. */
1798 selected_frame_num = 0;
1800 /* Find the nearest displayed frame to the selected frame (whether
1801 it's before or after that frame) and make that the current frame.
1802 If the next and previous displayed frames are equidistant from the
1803 selected frame, choose the next one. */
1804 g_assert(following_frame == NULL ||
1805 following_frame->num >= selected_frame->num);
1806 g_assert(preceding_frame == NULL ||
1807 preceding_frame->num <= selected_frame->num);
1808 if (following_frame == NULL) {
1809 /* No frame after the selected frame passed the filter, so we
1810 have to select the last displayed frame before the selected
1812 selected_frame_num = preceding_frame_num;
1813 selected_frame = preceding_frame;
1814 } else if (preceding_frame == NULL) {
1815 /* No frame before the selected frame passed the filter, so we
1816 have to select the first displayed frame after the selected
1818 selected_frame_num = following_frame_num;
1819 selected_frame = following_frame;
1821 /* Frames before and after the selected frame passed the filter, so
1822 we'll select the previous frame */
1823 selected_frame_num = preceding_frame_num;
1824 selected_frame = preceding_frame;
1829 if (selected_frame_num == -1) {
1830 /* There are no frames displayed at all. */
1831 cf_unselect_packet(cf);
1833 /* Either the frame that was selected passed the filter, or we've
1834 found the nearest displayed frame to that frame. Select it, make
1835 it the focus row, and make it visible. */
1836 /* Set to invalid to force update of packet list and packet details */
1837 cf->current_row = -1;
1838 if (selected_frame_num == 0) {
1839 packet_list_select_first_row();
1841 if (!packet_list_select_row_from_data(selected_frame)) {
1842 /* We didn't find a row corresponding to this frame.
1843 This means that the frame isn't being displayed currently,
1844 so we can't select it. */
1845 simple_message_box(ESD_TYPE_INFO, NULL,
1846 "The capture file is probably not fully dissected.",
1847 "End of capture exceeded.");
1852 /* Cleanup and release all dfilter resources */
1853 dfilter_free(dfcode);
1858 * Scan through all frame data and recalculate the ref time
1859 * without rereading the file.
1860 * XXX - do we need a progres bar or is this fast enough?
1863 ref_time_packets(capture_file *cf)
1869 cf->provider.ref = NULL;
1870 cf->provider.prev_dis = NULL;
1873 for (framenum = 1; framenum <= cf->count; framenum++) {
1874 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1876 /* just add some value here until we know if it is being displayed or not */
1877 fdata->cum_bytes = cf->cum_bytes + fdata->pkt_len;
1883 /* If we don't have the time stamp of the first packet in the
1884 capture, it's because this is the first packet. Save the time
1885 stamp of this packet as the time stamp of the first packet. */
1886 if (cf->provider.ref == NULL)
1887 cf->provider.ref = fdata;
1888 /* if this frames is marked as a reference time frame, reset
1889 firstsec and firstusec to this frame */
1890 if (fdata->flags.ref_time)
1891 cf->provider.ref = fdata;
1893 /* If we don't have the time stamp of the previous displayed packet,
1894 it's because this is the first displayed packet. Save the time
1895 stamp of this packet as the time stamp of the previous displayed
1897 if (cf->provider.prev_dis == NULL) {
1898 cf->provider.prev_dis = fdata;
1901 /* Get the time elapsed between the first packet and this packet. */
1902 fdata->frame_ref_num = (fdata != cf->provider.ref) ? cf->provider.ref->num : 0;
1903 nstime_delta(&rel_ts, &fdata->abs_ts, &cf->provider.ref->abs_ts);
1905 /* If it's greater than the current elapsed time, set the elapsed time
1906 to it (we check for "greater than" so as not to be confused by
1907 time moving backwards). */
1908 if ((gint32)cf->elapsed_time.secs < rel_ts.secs
1909 || ((gint32)cf->elapsed_time.secs == rel_ts.secs && (gint32)cf->elapsed_time.nsecs < rel_ts.nsecs)) {
1910 cf->elapsed_time = rel_ts;
1913 /* If this frame is displayed, get the time elapsed between the
1914 previous displayed packet and this packet. */
1915 if ( fdata->flags.passed_dfilter ) {
1916 fdata->prev_dis_num = cf->provider.prev_dis->num;
1917 cf->provider.prev_dis = fdata;
1923 if ( (fdata->flags.passed_dfilter) || (fdata->flags.ref_time) ) {
1924 /* This frame either passed the display filter list or is marked as
1925 a time reference frame. All time reference frames are displayed
1926 even if they don't pass the display filter */
1927 if (fdata->flags.ref_time) {
1928 /* if this was a TIME REF frame we should reset the cum_bytes field */
1929 cf->cum_bytes = fdata->pkt_len;
1930 fdata->cum_bytes = cf->cum_bytes;
1932 /* increase cum_bytes with this packets length */
1933 cf->cum_bytes += fdata->pkt_len;
1946 process_specified_records(capture_file *cf, packet_range_t *range,
1947 const char *string1, const char *string2, gboolean terminate_is_stop,
1948 gboolean (*callback)(capture_file *, frame_data *,
1949 struct wtap_pkthdr *, const guint8 *, void *),
1950 void *callback_args,
1951 gboolean show_progress_bar)
1956 psp_return_t ret = PSP_FINISHED;
1958 progdlg_t *progbar = NULL;
1959 GTimer *prog_timer = g_timer_new();
1962 GTimeVal progbar_start_time;
1963 gchar progbar_status_str[100];
1964 range_process_e process_this;
1965 struct wtap_pkthdr phdr;
1967 wtap_phdr_init(&phdr);
1968 ws_buffer_init(&buf, 1500);
1970 g_timer_start(prog_timer);
1971 /* Count of packets at which we've looked. */
1973 /* Progress so far. */
1976 cf->stop_flag = FALSE;
1977 g_get_current_time(&progbar_start_time);
1980 packet_range_process_init(range);
1982 /* Iterate through all the packets, printing the packets that
1983 were selected by the current display filter. */
1984 for (framenum = 1; framenum <= cf->count; framenum++) {
1985 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1987 /* Create the progress bar if necessary.
1988 We check on every iteration of the loop, so that it takes no
1989 longer than the standard time to create it (otherwise, for a
1990 large file, we might take considerably longer than that standard
1991 time in order to get to the next progress bar step). */
1992 if (show_progress_bar && progbar == NULL)
1993 progbar = delayed_create_progress_dlg(cf->window, string1, string2,
1996 &progbar_start_time,
2000 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
2001 * has elapsed. Calling update_progress_dlg and packets_bar_update will
2002 * likely trigger UI paint events, which might take a while depending on
2003 * the platform and display. Reset our timer *after* painting.
2005 if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
2006 /* let's not divide by zero. I should never be started
2007 * with count == 0, so let's assert that
2009 g_assert(cf->count > 0);
2010 progbar_val = (gfloat) progbar_count / cf->count;
2012 g_snprintf(progbar_status_str, sizeof(progbar_status_str),
2013 "%4u of %u packets", progbar_count, cf->count);
2014 update_progress_dlg(progbar, progbar_val, progbar_status_str);
2016 g_timer_start(prog_timer);
2019 if (cf->stop_flag) {
2020 /* Well, the user decided to abort the operation. Just stop,
2021 and arrange to return PSP_STOPPED to our caller, so they know
2022 it was stopped explicitly. */
2029 if (range != NULL) {
2030 /* do we have to process this packet? */
2031 process_this = packet_range_process_packet(range, fdata);
2032 if (process_this == range_process_next) {
2033 /* this packet uninteresting, continue with next one */
2035 } else if (process_this == range_processing_finished) {
2036 /* all interesting packets processed, stop the loop */
2041 /* Get the packet */
2042 if (!cf_read_record_r(cf, fdata, &phdr, &buf)) {
2043 /* Attempt to get the packet failed. */
2047 /* Process the packet */
2048 if (!callback(cf, fdata, &phdr, ws_buffer_start_ptr(&buf), callback_args)) {
2049 /* Callback failed. We assume it reported the error appropriately. */
2055 /* We're done printing the packets; destroy the progress bar if
2057 if (progbar != NULL)
2058 destroy_progress_dlg(progbar);
2059 g_timer_destroy(prog_timer);
2061 wtap_phdr_cleanup(&phdr);
2062 ws_buffer_free(&buf);
2070 } retap_callback_args_t;
2073 retap_packet(capture_file *cf, frame_data *fdata,
2074 struct wtap_pkthdr *phdr, const guint8 *pd,
2077 retap_callback_args_t *args = (retap_callback_args_t *)argsp;
2079 epan_dissect_run_with_taps(&args->edt, cf->cd_t, phdr,
2080 frame_tvbuff_new(&cf->provider, fdata, pd),
2081 fdata, args->cinfo);
2082 epan_dissect_reset(&args->edt);
2088 cf_retap_packets(capture_file *cf)
2090 packet_range_t range;
2091 retap_callback_args_t callback_args;
2092 gboolean create_proto_tree;
2096 /* Presumably the user closed the capture file. */
2098 return CF_READ_ABORTED;
2101 cf_callback_invoke(cf_cb_file_retap_started, cf);
2103 /* Get the union of the flags for all tap listeners. */
2104 tap_flags = union_of_tap_listener_flags();
2106 /* If any tap listeners require the columns, construct them. */
2107 callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
2110 * Determine whether we need to create a protocol tree.
2113 * one of the tap listeners is going to apply a filter;
2115 * one of the tap listeners requires a protocol tree.
2118 (have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
2120 /* Reset the tap listeners. */
2121 reset_tap_listeners();
2123 epan_dissect_init(&callback_args.edt, cf->epan, create_proto_tree, FALSE);
2125 /* Iterate through the list of packets, dissecting all packets and
2126 re-running the taps. */
2127 packet_range_init(&range, cf);
2128 packet_range_process_init(&range);
2130 ret = process_specified_records(cf, &range, "Recalculating statistics on",
2131 "all packets", TRUE, retap_packet,
2132 &callback_args, TRUE);
2134 epan_dissect_cleanup(&callback_args.edt);
2136 cf_callback_invoke(cf_cb_file_retap_finished, cf);
2140 /* Completed successfully. */
2144 /* Well, the user decided to abort the refiltering.
2145 Return CF_READ_ABORTED so our caller knows they did that. */
2146 return CF_READ_ABORTED;
2149 /* Error while retapping. */
2150 return CF_READ_ERROR;
2153 g_assert_not_reached();
2158 print_args_t *print_args;
2159 gboolean print_header_line;
2160 char *header_line_buf;
2161 int header_line_buf_len;
2162 gboolean print_formfeed;
2163 gboolean print_separator;
2167 int num_visible_cols;
2170 } print_callback_args_t;
2173 print_packet(capture_file *cf, frame_data *fdata,
2174 struct wtap_pkthdr *phdr, const guint8 *pd,
2177 print_callback_args_t *args = (print_callback_args_t *)argsp;
2183 char bookmark_name[9+10+1]; /* "__frameNNNNNNNNNN__\0" */
2184 char bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0" */
2185 col_item_t* col_item;
2187 /* Fill in the column information if we're printing the summary
2189 if (args->print_args->print_summary) {
2190 col_custom_prime_edt(&args->edt, &cf->cinfo);
2191 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2192 frame_tvbuff_new(&cf->provider, fdata, pd),
2194 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2196 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2197 frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2199 if (args->print_formfeed) {
2200 if (!new_page(args->print_args->stream))
2203 if (args->print_separator) {
2204 if (!print_line(args->print_args->stream, 0, ""))
2210 * We generate bookmarks, if the output format supports them.
2211 * The name is "__frameN__".
2213 g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2215 if (args->print_args->print_summary) {
2216 if (!args->print_args->print_col_headings)
2217 args->print_header_line = FALSE;
2218 if (args->print_header_line) {
2219 if (!print_line(args->print_args->stream, 0, args->header_line_buf))
2221 args->print_header_line = FALSE; /* we might not need to print any more */
2223 cp = &args->line_buf[0];
2225 for (i = 0; i < args->num_visible_cols; i++) {
2226 col_item = &cf->cinfo.columns[args->visible_cols[i]];
2227 /* Find the length of the string for this column. */
2228 column_len = (int) strlen(col_item->col_data);
2229 if (args->col_widths[i] > column_len)
2230 column_len = args->col_widths[i];
2232 /* Make sure there's room in the line buffer for the column; if not,
2233 double its length. */
2234 line_len += column_len + 1; /* "+1" for space */
2235 if (line_len > args->line_buf_len) {
2236 cp_off = (int) (cp - args->line_buf);
2237 args->line_buf_len = 2 * line_len;
2238 args->line_buf = (char *)g_realloc(args->line_buf, args->line_buf_len + 1);
2239 cp = args->line_buf + cp_off;
2242 /* Right-justify the packet number column. */
2243 if (col_item->col_fmt == COL_NUMBER)
2244 g_snprintf(cp, column_len+1, "%*s", args->col_widths[i], col_item->col_data);
2246 g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], col_item->col_data);
2248 if (i != args->num_visible_cols - 1)
2254 * Generate a bookmark, using the summary line as the title.
2256 if (!print_bookmark(args->print_args->stream, bookmark_name,
2260 if (!print_line(args->print_args->stream, 0, args->line_buf))
2264 * Generate a bookmark, using "Frame N" as the title, as we're not
2265 * printing the summary line.
2267 g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2268 if (!print_bookmark(args->print_args->stream, bookmark_name,
2271 } /* if (print_summary) */
2273 if (args->print_args->print_dissections != print_dissections_none) {
2274 if (args->print_args->print_summary) {
2275 /* Separate the summary line from the tree with a blank line. */
2276 if (!print_line(args->print_args->stream, 0, ""))
2280 /* Print the information in that tree. */
2281 if (!proto_tree_print(args->print_args->print_dissections,
2282 args->print_args->print_hex, &args->edt, NULL,
2283 args->print_args->stream))
2286 /* Print a blank line if we print anything after this (aka more than one packet). */
2287 args->print_separator = TRUE;
2289 /* Print a header line if we print any more packet summaries */
2290 if (args->print_args->print_col_headings)
2291 args->print_header_line = TRUE;
2294 if (args->print_args->print_hex) {
2295 if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
2296 if (!print_line(args->print_args->stream, 0, ""))
2299 /* Print the full packet data as hex. */
2300 if (!print_hex_data(args->print_args->stream, &args->edt))
2303 /* Print a blank line if we print anything after this (aka more than one packet). */
2304 args->print_separator = TRUE;
2306 /* Print a header line if we print any more packet summaries */
2307 if (args->print_args->print_col_headings)
2308 args->print_header_line = TRUE;
2309 } /* if (args->print_args->print_dissections != print_dissections_none) */
2311 epan_dissect_reset(&args->edt);
2313 /* do we want to have a formfeed between each packet from now on? */
2314 if (args->print_args->print_formfeed) {
2315 args->print_formfeed = TRUE;
2321 epan_dissect_reset(&args->edt);
2326 cf_print_packets(capture_file *cf, print_args_t *print_args,
2327 gboolean show_progress_bar)
2329 print_callback_args_t callback_args;
2332 int i, cp_off, column_len, line_len;
2333 int num_visible_col = 0, last_visible_col = 0, visible_col_count;
2337 gboolean proto_tree_needed;
2339 callback_args.print_args = print_args;
2340 callback_args.print_header_line = print_args->print_col_headings;
2341 callback_args.header_line_buf = NULL;
2342 callback_args.header_line_buf_len = 256;
2343 callback_args.print_formfeed = FALSE;
2344 callback_args.print_separator = FALSE;
2345 callback_args.line_buf = NULL;
2346 callback_args.line_buf_len = 256;
2347 callback_args.col_widths = NULL;
2348 callback_args.num_visible_cols = 0;
2349 callback_args.visible_cols = NULL;
2351 if (!print_preamble(print_args->stream, cf->filename, get_ws_vcs_version_info())) {
2352 destroy_print_stream(print_args->stream);
2353 return CF_PRINT_WRITE_ERROR;
2356 if (print_args->print_summary) {
2357 /* We're printing packet summaries. Allocate the header line buffer
2358 and get the column widths. */
2359 callback_args.header_line_buf = (char *)g_malloc(callback_args.header_line_buf_len + 1);
2361 /* Find the number of visible columns and the last visible column */
2362 for (i = 0; i < prefs.num_cols; i++) {
2364 clp = g_list_nth(prefs.col_list, i);
2365 if (clp == NULL) /* Sanity check, Invalid column requested */
2368 cfmt = (fmt_data *) clp->data;
2369 if (cfmt->visible) {
2371 last_visible_col = i;
2375 /* if num_visible_col is 0, we are done */
2376 if (num_visible_col == 0) {
2377 g_free(callback_args.header_line_buf);
2381 /* Find the widths for each of the columns - maximum of the
2382 width of the title and the width of the data - and construct
2383 a buffer with a line containing the column titles. */
2384 callback_args.num_visible_cols = num_visible_col;
2385 callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2386 callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2387 cp = &callback_args.header_line_buf[0];
2389 visible_col_count = 0;
2390 for (i = 0; i < cf->cinfo.num_cols; i++) {
2392 clp = g_list_nth(prefs.col_list, i);
2393 if (clp == NULL) /* Sanity check, Invalid column requested */
2396 cfmt = (fmt_data *) clp->data;
2397 if (cfmt->visible == FALSE)
2400 /* Save the order of visible columns */
2401 callback_args.visible_cols[visible_col_count] = i;
2403 /* Don't pad the last column. */
2404 if (i == last_visible_col)
2405 callback_args.col_widths[visible_col_count] = 0;
2407 callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.columns[i].col_title);
2408 data_width = get_column_char_width(get_column_format(i));
2409 if (data_width > callback_args.col_widths[visible_col_count])
2410 callback_args.col_widths[visible_col_count] = data_width;
2413 /* Find the length of the string for this column. */
2414 column_len = (int) strlen(cf->cinfo.columns[i].col_title);
2415 if (callback_args.col_widths[visible_col_count] > column_len)
2416 column_len = callback_args.col_widths[visible_col_count];
2418 /* Make sure there's room in the line buffer for the column; if not,
2419 double its length. */
2420 line_len += column_len + 1; /* "+1" for space */
2421 if (line_len > callback_args.header_line_buf_len) {
2422 cp_off = (int) (cp - callback_args.header_line_buf);
2423 callback_args.header_line_buf_len = 2 * line_len;
2424 callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2425 callback_args.header_line_buf_len + 1);
2426 cp = callback_args.header_line_buf + cp_off;
2429 /* Right-justify the packet number column. */
2430 /* if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2431 g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2433 g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2435 if (i != cf->cinfo.num_cols - 1)
2438 visible_col_count++;
2442 /* Now start out the main line buffer with the same length as the
2443 header line buffer. */
2444 callback_args.line_buf_len = callback_args.header_line_buf_len;
2445 callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2446 } /* if (print_summary) */
2448 /* Create the protocol tree, and make it visible, if we're printing
2449 the dissection or the hex data.
2450 XXX - do we need it if we're just printing the hex data? */
2452 callback_args.print_args->print_dissections != print_dissections_none ||
2453 callback_args.print_args->print_hex ||
2454 have_custom_cols(&cf->cinfo) || have_field_extractors();
2455 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2457 /* Iterate through the list of packets, printing the packets we were
2459 ret = process_specified_records(cf, &print_args->range, "Printing",
2460 "selected packets", TRUE, print_packet,
2461 &callback_args, show_progress_bar);
2462 epan_dissect_cleanup(&callback_args.edt);
2463 g_free(callback_args.header_line_buf);
2464 g_free(callback_args.line_buf);
2465 g_free(callback_args.col_widths);
2466 g_free(callback_args.visible_cols);
2471 /* Completed successfully. */
2475 /* Well, the user decided to abort the printing.
2477 XXX - note that what got generated before they did that
2478 will get printed if we're piping to a print program; we'd
2479 have to write to a file and then hand that to the print
2480 program to make it actually not print anything. */
2484 /* Error while printing.
2486 XXX - note that what got generated before they did that
2487 will get printed if we're piping to a print program; we'd
2488 have to write to a file and then hand that to the print
2489 program to make it actually not print anything. */
2490 destroy_print_stream(print_args->stream);
2491 return CF_PRINT_WRITE_ERROR;
2494 if (!print_finale(print_args->stream)) {
2495 destroy_print_stream(print_args->stream);
2496 return CF_PRINT_WRITE_ERROR;
2499 if (!destroy_print_stream(print_args->stream))
2500 return CF_PRINT_WRITE_ERROR;
2508 print_args_t *print_args;
2509 } write_packet_callback_args_t;
2512 write_pdml_packet(capture_file *cf, frame_data *fdata,
2513 struct wtap_pkthdr *phdr, const guint8 *pd,
2516 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2518 /* Create the protocol tree, but don't fill in the column information. */
2519 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2520 frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2522 /* Write out the information in that tree. */
2523 write_pdml_proto_tree(NULL, NULL, PF_NONE, &args->edt, &cf->cinfo, args->fh, FALSE);
2525 epan_dissect_reset(&args->edt);
2527 return !ferror(args->fh);
2531 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2533 write_packet_callback_args_t callback_args;
2537 fh = ws_fopen(print_args->file, "w");
2539 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2541 write_pdml_preamble(fh, cf->filename);
2544 return CF_PRINT_WRITE_ERROR;
2547 callback_args.fh = fh;
2548 callback_args.print_args = print_args;
2549 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2551 /* Iterate through the list of packets, printing the packets we were
2553 ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2554 "selected packets", TRUE,
2555 write_pdml_packet, &callback_args, TRUE);
2557 epan_dissect_cleanup(&callback_args.edt);
2562 /* Completed successfully. */
2566 /* Well, the user decided to abort the printing. */
2570 /* Error while printing. */
2572 return CF_PRINT_WRITE_ERROR;
2575 write_pdml_finale(fh);
2578 return CF_PRINT_WRITE_ERROR;
2581 /* XXX - check for an error */
2588 write_psml_packet(capture_file *cf, frame_data *fdata,
2589 struct wtap_pkthdr *phdr, const guint8 *pd,
2592 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2594 /* Fill in the column information */
2595 col_custom_prime_edt(&args->edt, &cf->cinfo);
2596 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2597 frame_tvbuff_new(&cf->provider, fdata, pd),
2599 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2601 /* Write out the column information. */
2602 write_psml_columns(&args->edt, args->fh, FALSE);
2604 epan_dissect_reset(&args->edt);
2606 return !ferror(args->fh);
2610 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2612 write_packet_callback_args_t callback_args;
2616 gboolean proto_tree_needed;
2618 fh = ws_fopen(print_args->file, "w");
2620 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2622 write_psml_preamble(&cf->cinfo, fh);
2625 return CF_PRINT_WRITE_ERROR;
2628 callback_args.fh = fh;
2629 callback_args.print_args = print_args;
2631 /* Fill in the column information, only create the protocol tree
2632 if having custom columns or field extractors. */
2633 proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2634 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2636 /* Iterate through the list of packets, printing the packets we were
2638 ret = process_specified_records(cf, &print_args->range, "Writing PSML",
2639 "selected packets", TRUE,
2640 write_psml_packet, &callback_args, TRUE);
2642 epan_dissect_cleanup(&callback_args.edt);
2647 /* Completed successfully. */
2651 /* Well, the user decided to abort the printing. */
2655 /* Error while printing. */
2657 return CF_PRINT_WRITE_ERROR;
2660 write_psml_finale(fh);
2663 return CF_PRINT_WRITE_ERROR;
2666 /* XXX - check for an error */
2673 write_csv_packet(capture_file *cf, frame_data *fdata,
2674 struct wtap_pkthdr *phdr, const guint8 *pd,
2677 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2679 /* Fill in the column information */
2680 col_custom_prime_edt(&args->edt, &cf->cinfo);
2681 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2682 frame_tvbuff_new(&cf->provider, fdata, pd),
2684 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2686 /* Write out the column information. */
2687 write_csv_columns(&args->edt, args->fh);
2689 epan_dissect_reset(&args->edt);
2691 return !ferror(args->fh);
2695 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2697 write_packet_callback_args_t callback_args;
2698 gboolean proto_tree_needed;
2702 fh = ws_fopen(print_args->file, "w");
2704 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2706 write_csv_column_titles(&cf->cinfo, fh);
2709 return CF_PRINT_WRITE_ERROR;
2712 callback_args.fh = fh;
2713 callback_args.print_args = print_args;
2715 /* only create the protocol tree if having custom columns or field extractors. */
2716 proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2717 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2719 /* Iterate through the list of packets, printing the packets we were
2721 ret = process_specified_records(cf, &print_args->range, "Writing CSV",
2722 "selected packets", TRUE,
2723 write_csv_packet, &callback_args, TRUE);
2725 epan_dissect_cleanup(&callback_args.edt);
2730 /* Completed successfully. */
2734 /* Well, the user decided to abort the printing. */
2738 /* Error while printing. */
2740 return CF_PRINT_WRITE_ERROR;
2743 /* XXX - check for an error */
2750 carrays_write_packet(capture_file *cf, frame_data *fdata,
2751 struct wtap_pkthdr *phdr,
2752 const guint8 *pd, void *argsp)
2754 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2756 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2757 frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2758 write_carrays_hex_data(fdata->num, args->fh, &args->edt);
2759 epan_dissect_reset(&args->edt);
2761 return !ferror(args->fh);
2765 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2767 write_packet_callback_args_t callback_args;
2771 fh = ws_fopen(print_args->file, "w");
2774 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2778 return CF_PRINT_WRITE_ERROR;
2781 callback_args.fh = fh;
2782 callback_args.print_args = print_args;
2783 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2785 /* Iterate through the list of packets, printing the packets we were
2787 ret = process_specified_records(cf, &print_args->range,
2789 "selected packets", TRUE,
2790 carrays_write_packet, &callback_args, TRUE);
2792 epan_dissect_cleanup(&callback_args.edt);
2796 /* Completed successfully. */
2799 /* Well, the user decided to abort the printing. */
2802 /* Error while printing. */
2804 return CF_PRINT_WRITE_ERROR;
2812 write_json_packet(capture_file *cf, frame_data *fdata,
2813 struct wtap_pkthdr *phdr, const guint8 *pd,
2816 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2818 /* Create the protocol tree, but don't fill in the column information. */
2819 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2820 frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2822 /* Write out the information in that tree. */
2823 write_json_proto_tree(NULL, args->print_args->print_dissections,
2824 args->print_args->print_hex, NULL, PF_NONE,
2825 &args->edt, &cf->cinfo, proto_node_group_children_by_unique, args->fh);
2827 epan_dissect_reset(&args->edt);
2829 return !ferror(args->fh);
2833 cf_write_json_packets(capture_file *cf, print_args_t *print_args)
2835 write_packet_callback_args_t callback_args;
2839 fh = ws_fopen(print_args->file, "w");
2841 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2843 write_json_preamble(fh);
2846 return CF_PRINT_WRITE_ERROR;
2849 callback_args.fh = fh;
2850 callback_args.print_args = print_args;
2851 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2853 /* Iterate through the list of packets, printing the packets we were
2855 ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2856 "selected packets", TRUE,
2857 write_json_packet, &callback_args, TRUE);
2859 epan_dissect_cleanup(&callback_args.edt);
2864 /* Completed successfully. */
2868 /* Well, the user decided to abort the printing. */
2872 /* Error while printing. */
2874 return CF_PRINT_WRITE_ERROR;
2877 write_json_finale(fh);
2880 return CF_PRINT_WRITE_ERROR;
2883 /* XXX - check for an error */
2890 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2891 search_direction dir)
2895 mdata.string = string;
2896 mdata.string_len = strlen(string);
2897 return find_packet(cf, match_protocol_tree, &mdata, dir);
2901 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree, match_data *mdata)
2903 mdata->frame_matched = FALSE;
2904 mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2905 mdata->string_len = strlen(mdata->string);
2907 /* Iterate through all the nodes looking for matching text */
2908 proto_tree_children_foreach(tree, match_subtree_text, mdata);
2909 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2913 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2915 match_data *mdata = (match_data *)criterion;
2918 /* Load the frame's data. */
2919 if (!cf_read_record(cf, fdata)) {
2920 /* Attempt to get the packet failed. */
2924 /* Construct the protocol tree, including the displayed text */
2925 epan_dissect_init(&edt, cf->epan, TRUE, TRUE);
2926 /* We don't need the column information */
2927 epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
2928 frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
2931 /* Iterate through all the nodes, seeing if they have text that matches. */
2933 mdata->frame_matched = FALSE;
2934 proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
2935 epan_dissect_cleanup(&edt);
2936 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2940 match_subtree_text(proto_node *node, gpointer data)
2942 match_data *mdata = (match_data *) data;
2943 const gchar *string = mdata->string;
2944 size_t string_len = mdata->string_len;
2945 capture_file *cf = mdata->cf;
2946 field_info *fi = PNODE_FINFO(node);
2947 gchar label_str[ITEM_LABEL_LENGTH];
2954 /* dissection with an invisible proto tree? */
2957 if (mdata->frame_matched) {
2958 /* We already had a match; don't bother doing any more work. */
2962 /* Don't match invisible entries. */
2963 if (PROTO_ITEM_IS_HIDDEN(node))
2966 /* was a free format label produced? */
2968 label_ptr = fi->rep->representation;
2970 /* no, make a generic label */
2971 label_ptr = label_str;
2972 proto_item_fill_label(fi, label_str);
2976 if (g_regex_match(cf->regex, label_ptr, (GRegexMatchFlags) 0, NULL)) {
2977 mdata->frame_matched = TRUE;
2982 /* Does that label match? */
2983 label_len = strlen(label_ptr);
2984 for (i = 0; i < label_len; i++) {
2985 c_char = label_ptr[i];
2987 c_char = g_ascii_toupper(c_char);
2988 if (c_char == string[c_match]) {
2990 if (c_match == string_len) {
2991 /* No need to look further; we have a match */
2992 mdata->frame_matched = TRUE;
3001 /* Recurse into the subtree, if it exists */
3002 if (node->first_child != NULL)
3003 proto_tree_children_foreach(node, match_subtree_text, mdata);
3007 cf_find_packet_summary_line(capture_file *cf, const char *string,
3008 search_direction dir)
3012 mdata.string = string;
3013 mdata.string_len = strlen(string);
3014 return find_packet(cf, match_summary_line, &mdata, dir);
3018 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
3020 match_data *mdata = (match_data *)criterion;
3021 const gchar *string = mdata->string;
3022 size_t string_len = mdata->string_len;
3024 const char *info_column;
3025 size_t info_column_len;
3026 match_result result = MR_NOTMATCHED;
3032 /* Load the frame's data. */
3033 if (!cf_read_record(cf, fdata)) {
3034 /* Attempt to get the packet failed. */
3038 /* Don't bother constructing the protocol tree */
3039 epan_dissect_init(&edt, cf->epan, FALSE, FALSE);
3040 /* Get the column information */
3041 epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3042 frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3045 /* Find the Info column */
3046 for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3047 if (cf->cinfo.columns[colx].fmt_matx[COL_INFO]) {
3048 /* Found it. See if we match. */
3049 info_column = edt.pi.cinfo->columns[colx].col_data;
3050 info_column_len = strlen(info_column);
3052 if (g_regex_match(cf->regex, info_column, (GRegexMatchFlags) 0, NULL)) {
3053 result = MR_MATCHED;
3057 for (i = 0; i < info_column_len; i++) {
3058 c_char = info_column[i];
3060 c_char = g_ascii_toupper(c_char);
3061 if (c_char == string[c_match]) {
3063 if (c_match == string_len) {
3064 result = MR_MATCHED;
3074 epan_dissect_cleanup(&edt);
3081 } cbs_t; /* "Counted byte string" */
3085 * The current match_* routines only support ASCII case insensitivity and don't
3086 * convert UTF-8 inputs to UTF-16 for matching.
3088 * We could modify them to use the GLib Unicode routines or the International
3089 * Components for Unicode library but it's not apparent that we could do so
3090 * without consuming a lot more CPU and memory or that searching would be
3091 * significantly better.
3095 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3096 search_direction dir)
3101 info.data_len = string_size;
3103 /* Regex, String or hex search? */
3105 /* Regular Expression search */
3106 return find_packet(cf, match_regex, NULL, dir);
3107 } else if (cf->string) {
3108 /* String search - what type of string? */
3109 switch (cf->scs_type) {
3111 case SCS_NARROW_AND_WIDE:
3112 return find_packet(cf, match_narrow_and_wide, &info, dir);
3115 return find_packet(cf, match_narrow, &info, dir);
3118 return find_packet(cf, match_wide, &info, dir);
3121 g_assert_not_reached();
3125 return find_packet(cf, match_binary, &info, dir);
3129 match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
3131 cbs_t *info = (cbs_t *)criterion;
3132 const guint8 *ascii_text = info->data;
3133 size_t textlen = info->data_len;
3134 match_result result;
3141 /* Load the frame's data. */
3142 if (!cf_read_record(cf, fdata)) {
3143 /* Attempt to get the packet failed. */
3147 result = MR_NOTMATCHED;
3148 buf_len = fdata->cap_len;
3149 pd = ws_buffer_start_ptr(&cf->buf);
3151 while (i < buf_len) {
3154 c_char = g_ascii_toupper(c_char);
3155 if (c_char != '\0') {
3156 if (c_char == ascii_text[c_match]) {
3158 if (c_match == textlen) {
3159 result = MR_MATCHED;
3160 cf->search_pos = i; /* Save the position of the last character
3161 for highlighting the field. */
3162 cf->search_len = (guint32)textlen;
3167 g_assert(i>=c_match);
3168 i -= (guint32)c_match;
3178 match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
3181 cbs_t *info = (cbs_t *)criterion;
3182 const guint8 *ascii_text = info->data;
3183 size_t textlen = info->data_len;
3184 match_result result;
3190 /* Load the frame's data. */
3191 if (!cf_read_record(cf, fdata)) {
3192 /* Attempt to get the packet failed. */
3196 result = MR_NOTMATCHED;
3197 buf_len = fdata->cap_len;
3198 pd = ws_buffer_start_ptr(&cf->buf);
3200 while (i < buf_len) {
3203 c_char = g_ascii_toupper(c_char);
3204 if (c_char == ascii_text[c_match]) {
3206 if (c_match == textlen) {
3207 result = MR_MATCHED;
3208 cf->search_pos = i; /* Save the position of the last character
3209 for highlighting the field. */
3210 cf->search_len = (guint32)textlen;
3215 g_assert(i>=c_match);
3216 i -= (guint32)c_match;
3226 match_wide(capture_file *cf, frame_data *fdata, void *criterion)
3228 cbs_t *info = (cbs_t *)criterion;
3229 const guint8 *ascii_text = info->data;
3230 size_t textlen = info->data_len;
3231 match_result result;
3238 /* Load the frame's data. */
3239 if (!cf_read_record(cf, fdata)) {
3240 /* Attempt to get the packet failed. */
3244 result = MR_NOTMATCHED;
3245 buf_len = fdata->cap_len;
3246 pd = ws_buffer_start_ptr(&cf->buf);
3248 while (i < buf_len) {
3251 c_char = g_ascii_toupper(c_char);
3252 if (c_char == ascii_text[c_match]) {
3254 if (c_match == textlen) {
3255 result = MR_MATCHED;
3256 cf->search_pos = i; /* Save the position of the last character
3257 for highlighting the field. */
3258 cf->search_len = (guint32)textlen;
3264 g_assert(i>=(c_match*2));
3265 i -= (guint32)c_match*2;
3274 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3276 cbs_t *info = (cbs_t *)criterion;
3277 const guint8 *binary_data = info->data;
3278 size_t datalen = info->data_len;
3279 match_result result;
3285 /* Load the frame's data. */
3286 if (!cf_read_record(cf, fdata)) {
3287 /* Attempt to get the packet failed. */
3291 result = MR_NOTMATCHED;
3292 buf_len = fdata->cap_len;
3293 pd = ws_buffer_start_ptr(&cf->buf);
3295 while (i < buf_len) {
3296 if (pd[i] == binary_data[c_match]) {
3298 if (c_match == datalen) {
3299 result = MR_MATCHED;
3300 cf->search_pos = i; /* Save the position of the last character
3301 for highlighting the field. */
3302 cf->search_len = (guint32)datalen;
3307 g_assert(i>=c_match);
3308 i -= (guint32)c_match;
3317 match_regex(capture_file *cf, frame_data *fdata, void *criterion _U_)
3319 match_result result = MR_NOTMATCHED;
3320 GMatchInfo *match_info = NULL;
3322 /* Load the frame's data. */
3323 if (!cf_read_record(cf, fdata)) {
3324 /* Attempt to get the packet failed. */
3328 if (g_regex_match_full(cf->regex, (const gchar *)ws_buffer_start_ptr(&cf->buf), fdata->cap_len,
3329 0, (GRegexMatchFlags) 0, &match_info, NULL))
3331 gint start_pos = 0, end_pos = 0;
3332 g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
3333 cf->search_pos = end_pos - 1;
3334 cf->search_len = end_pos - start_pos;
3335 result = MR_MATCHED;
3341 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3342 search_direction dir)
3344 return find_packet(cf, match_dfilter, sfcode, dir);
3348 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3349 search_direction dir)
3354 if (!dfilter_compile(filter, &sfcode, NULL)) {
3356 * XXX - this shouldn't happen, as the filter string is machine
3361 if (sfcode == NULL) {
3363 * XXX - this shouldn't happen, as the filter string is machine
3368 result = find_packet(cf, match_dfilter, sfcode, dir);
3369 dfilter_free(sfcode);
3374 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3376 dfilter_t *sfcode = (dfilter_t *)criterion;
3378 match_result result;
3380 /* Load the frame's data. */
3381 if (!cf_read_record(cf, fdata)) {
3382 /* Attempt to get the packet failed. */
3386 epan_dissect_init(&edt, cf->epan, TRUE, FALSE);
3387 epan_dissect_prime_with_dfilter(&edt, sfcode);
3388 epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3389 frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3391 result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3392 epan_dissect_cleanup(&edt);
3397 cf_find_packet_marked(capture_file *cf, search_direction dir)
3399 return find_packet(cf, match_marked, NULL, dir);
3403 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3405 return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3409 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3411 return find_packet(cf, match_time_reference, NULL, dir);
3415 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3417 return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3421 find_packet(capture_file *cf,
3422 match_result (*match_function)(capture_file *, frame_data *, void *),
3423 void *criterion, search_direction dir)
3425 frame_data *start_fd;
3428 frame_data *new_fd = NULL;
3429 progdlg_t *progbar = NULL;
3430 GTimer *prog_timer = g_timer_new();
3434 GTimeVal start_time;
3435 gchar status_str[100];
3437 match_result result;
3439 start_fd = cf->current_frame;
3440 if (start_fd != NULL) {
3441 /* Iterate through the list of packets, starting at the packet we've
3442 picked, calling a routine to run the filter on the packet, see if
3443 it matches, and stop if so. */
3445 framenum = start_fd->num;
3447 g_timer_start(prog_timer);
3448 /* Progress so far. */
3451 cf->stop_flag = FALSE;
3452 g_get_current_time(&start_time);
3454 title = cf->sfilter?cf->sfilter:"";
3456 /* Create the progress bar if necessary.
3457 We check on every iteration of the loop, so that it takes no
3458 longer than the standard time to create it (otherwise, for a
3459 large file, we might take considerably longer than that standard
3460 time in order to get to the next progress bar step). */
3461 if (progbar == NULL)
3462 progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3463 FALSE, &cf->stop_flag, &start_time, progbar_val);
3466 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
3467 * has elapsed. Calling update_progress_dlg and packets_bar_update will
3468 * likely trigger UI paint events, which might take a while depending on
3469 * the platform and display. Reset our timer *after* painting.
3471 if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
3472 /* let's not divide by zero. I should never be started
3473 * with count == 0, so let's assert that
3475 g_assert(cf->count > 0);
3477 progbar_val = (gfloat) count / cf->count;
3479 g_snprintf(status_str, sizeof(status_str),
3480 "%4u of %u packets", count, cf->count);
3481 update_progress_dlg(progbar, progbar_val, status_str);
3483 g_timer_start(prog_timer);
3486 if (cf->stop_flag) {
3487 /* Well, the user decided to abort the search. Go back to the
3488 frame where we started. */
3493 /* Go past the current frame. */
3494 if (dir == SD_BACKWARD) {
3495 /* Go on to the previous frame. */
3496 if (framenum == 1) {
3498 * XXX - other apps have a bit more of a detailed message
3499 * for this, and instead of offering "OK" and "Cancel",
3500 * they offer things such as "Continue" and "Cancel";
3501 * we need an API for popping up alert boxes with
3502 * {Verb} and "Cancel".
3505 if (prefs.gui_find_wrap)
3507 statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3508 framenum = cf->count; /* wrap around */
3512 statusbar_push_temporary_msg("Search reached the beginning.");
3513 framenum = start_fd->num; /* stay on previous packet */
3518 /* Go on to the next frame. */
3519 if (framenum == cf->count) {
3520 if (prefs.gui_find_wrap)
3522 statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3523 framenum = 1; /* wrap around */
3527 statusbar_push_temporary_msg("Search reached the end.");
3528 framenum = start_fd->num; /* stay on previous packet */
3533 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3537 /* Is this packet in the display? */
3538 if (fdata->flags.passed_dfilter) {
3539 /* Yes. Does it match the search criterion? */
3540 result = (*match_function)(cf, fdata, criterion);
3541 if (result == MR_ERROR) {
3542 /* Error; our caller has reported the error. Go back to the frame
3543 where we started. */
3546 } else if (result == MR_MATCHED) {
3547 /* Yes. Go to the new frame. */
3553 if (fdata == start_fd) {
3554 /* We're back to the frame we were on originally, and that frame
3555 doesn't match the search filter. The search failed. */
3560 /* We're done scanning the packets; destroy the progress bar if it
3562 if (progbar != NULL)
3563 destroy_progress_dlg(progbar);
3564 g_timer_destroy(prog_timer);
3567 if (new_fd != NULL) {
3568 /* Find and select */
3569 cf->search_in_progress = TRUE;
3570 found = packet_list_select_row_from_data(new_fd);
3571 cf->search_in_progress = FALSE;
3572 cf->search_pos = 0; /* Reset the position */
3573 cf->search_len = 0; /* Reset length */
3575 /* We didn't find a row corresponding to this frame.
3576 This means that the frame isn't being displayed currently,
3577 so we can't select it. */
3578 simple_message_box(ESD_TYPE_INFO, NULL,
3579 "The capture file is probably not fully dissected.",
3580 "End of capture exceeded.");
3583 return TRUE; /* success */
3585 return FALSE; /* failure */
3589 cf_goto_frame(capture_file *cf, guint fnumber)
3593 if (cf == NULL || cf->provider.frames == NULL) {
3594 /* we don't have a loaded capture file - fix for bugs 11810 & 11989 */
3595 statusbar_push_temporary_msg("There is no file loaded");
3596 return FALSE; /* we failed to go to that packet */
3599 fdata = frame_data_sequence_find(cf->provider.frames, fnumber);
3601 if (fdata == NULL) {
3602 /* we didn't find a packet with that packet number */
3603 statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3604 return FALSE; /* we failed to go to that packet */
3606 if (!fdata->flags.passed_dfilter) {
3607 /* that packet currently isn't displayed */
3608 /* XXX - add it to the set of displayed packets? */
3609 statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3610 return FALSE; /* we failed to go to that packet */
3613 if (!packet_list_select_row_from_data(fdata)) {
3614 /* We didn't find a row corresponding to this frame.
3615 This means that the frame isn't being displayed currently,
3616 so we can't select it. */
3617 simple_message_box(ESD_TYPE_INFO, NULL,
3618 "The capture file is probably not fully dissected.",
3619 "End of capture exceeded.");
3622 return TRUE; /* we got to that packet */
3626 * Go to frame specified by currently selected protocol tree item.
3629 cf_goto_framenum(capture_file *cf)
3631 header_field_info *hfinfo;
3634 if (cf->finfo_selected) {
3635 hfinfo = cf->finfo_selected->hfinfo;
3637 if (hfinfo->type == FT_FRAMENUM) {
3638 framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3640 return cf_goto_frame(cf, framenum);
3647 /* Select the packet on a given row. */
3649 cf_select_packet(capture_file *cf, int row)
3651 epan_dissect_t *old_edt;
3654 /* Get the frame data struct pointer for this frame */
3655 fdata = packet_list_get_row_data(row);
3657 if (fdata == NULL) {
3661 /* Get the data in that frame. */
3662 if (!cf_read_record (cf, fdata)) {
3666 /* Record that this frame is the current frame. */
3667 cf->current_frame = fdata;
3668 cf->current_row = row;
3671 /* Create the logical protocol tree. */
3672 /* We don't need the columns here. */
3673 cf->edt = epan_dissect_new(cf->epan, TRUE, TRUE);
3675 tap_build_interesting(cf->edt);
3676 epan_dissect_run(cf->edt, cf->cd_t, &cf->phdr,
3677 frame_tvbuff_new_buffer(&cf->provider, cf->current_frame, &cf->buf),
3678 cf->current_frame, NULL);
3680 dfilter_macro_build_ftv_cache(cf->edt->tree);
3682 cf_callback_invoke(cf_cb_packet_selected, cf);
3684 if (old_edt != NULL)
3685 epan_dissect_free(old_edt);
3689 /* Unselect the selected packet, if any. */
3691 cf_unselect_packet(capture_file *cf)
3693 epan_dissect_t *old_edt = cf->edt;
3697 /* No packet is selected. */
3698 cf->current_frame = NULL;
3699 cf->current_row = 0;
3701 cf_callback_invoke(cf_cb_packet_unselected, cf);
3703 /* No protocol tree means no selected field. */
3704 cf_unselect_field(cf);
3706 /* Destroy the epan_dissect_t for the unselected packet. */
3707 if (old_edt != NULL)
3708 epan_dissect_free(old_edt);
3711 /* Unset the selected protocol tree field, if any. */
3713 cf_unselect_field(capture_file *cf)
3715 cf->finfo_selected = NULL;
3717 cf_callback_invoke(cf_cb_field_unselected, cf);
3721 * Mark a particular frame.
3724 cf_mark_frame(capture_file *cf, frame_data *frame)
3726 if (! frame->flags.marked) {
3727 frame->flags.marked = TRUE;
3728 if (cf->count > cf->marked_count)
3734 * Unmark a particular frame.
3737 cf_unmark_frame(capture_file *cf, frame_data *frame)
3739 if (frame->flags.marked) {
3740 frame->flags.marked = FALSE;
3741 if (cf->marked_count > 0)
3747 * Ignore a particular frame.
3750 cf_ignore_frame(capture_file *cf, frame_data *frame)
3752 if (! frame->flags.ignored) {
3753 frame->flags.ignored = TRUE;
3754 if (cf->count > cf->ignored_count)
3755 cf->ignored_count++;
3760 * Un-ignore a particular frame.
3763 cf_unignore_frame(capture_file *cf, frame_data *frame)
3765 if (frame->flags.ignored) {
3766 frame->flags.ignored = FALSE;
3767 if (cf->ignored_count > 0)
3768 cf->ignored_count--;
3773 * Read the section comment.
3776 cf_read_section_comment(capture_file *cf)
3778 wtap_block_t shb_inf;
3782 /* XXX - support multiple SHBs */
3783 shb_inf = wtap_file_get_shb(cf->provider.wth);
3785 /* Get the first comment from the SHB. */
3786 /* XXX - support multiple comments */
3787 if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS)
3793 * Modify the section comment.
3796 cf_update_section_comment(capture_file *cf, gchar *comment)
3798 wtap_block_t shb_inf;
3802 /* XXX - support multiple SHBs */
3803 shb_inf = wtap_file_get_shb(cf->provider.wth);
3805 /* Get the first comment from the SHB. */
3806 /* XXX - support multiple comments */
3807 if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS) {
3808 /* There's no comment - add one. */
3809 wtap_block_add_string_option(shb_inf, OPT_COMMENT, comment, strlen(comment));
3811 /* See if the comment has changed or not */
3812 if (strcmp(shb_comment, comment) == 0) {
3817 /* The comment has changed, let's update it */
3818 wtap_block_set_nth_string_option_value(shb_inf, OPT_COMMENT, 0, comment, strlen(comment));
3820 /* Mark the file as having unsaved changes */
3821 cf->unsaved_changes = TRUE;
3825 * Get the comment on a packet (record).
3826 * If the comment has been edited, it returns the result of the edit,
3827 * otherwise it returns the comment from the file.
3830 cf_get_packet_comment(capture_file *cf, const frame_data *fd)
3834 /* fetch user comment */
3835 if (fd->flags.has_user_comment)
3836 return g_strdup(cap_file_provider_get_user_comment(&cf->provider, fd));
3838 /* fetch phdr comment */
3839 if (fd->flags.has_phdr_comment) {
3840 struct wtap_pkthdr phdr; /* Packet header */
3841 Buffer buf; /* Packet data */
3843 wtap_phdr_init(&phdr);
3844 ws_buffer_init(&buf, 1500);
3846 if (!cf_read_record_r(cf, fd, &phdr, &buf))
3847 { /* XXX, what we can do here? */ }
3849 comment = phdr.opt_comment;
3850 wtap_phdr_cleanup(&phdr);
3851 ws_buffer_free(&buf);
3858 * Update(replace) the comment on a capture from a frame
3861 cf_set_user_packet_comment(capture_file *cf, frame_data *fd, const gchar *new_comment)
3863 char *pkt_comment = cf_get_packet_comment(cf, fd);
3865 /* Check if the comment has changed */
3866 if (!g_strcmp0(pkt_comment, new_comment)) {
3867 g_free(pkt_comment);
3870 g_free(pkt_comment);
3873 cf->packet_comment_count--;
3876 cf->packet_comment_count++;
3878 cap_file_provider_set_user_comment(&cf->provider, fd, new_comment);
3880 expert_update_comment_count(cf->packet_comment_count);
3882 /* OK, we have unsaved changes. */
3883 cf->unsaved_changes = TRUE;
3888 * What types of comments does this capture file have?
3891 cf_comment_types(capture_file *cf)
3893 guint32 comment_types = 0;
3895 if (cf_read_section_comment(cf) != NULL)
3896 comment_types |= WTAP_COMMENT_PER_SECTION;
3897 if (cf->packet_comment_count != 0)
3898 comment_types |= WTAP_COMMENT_PER_PACKET;
3899 return comment_types;
3903 * Add a resolved address to this file's list of resolved addresses.
3906 cf_add_ip_name_from_string(capture_file *cf, const char *addr, const char *name)
3909 * XXX - support multiple resolved address lists, and add to the one
3910 * attached to this file?
3912 if (!add_ip_name_from_string(addr, name))
3915 /* OK, we have unsaved changes. */
3916 cf->unsaved_changes = TRUE;
3924 } save_callback_args_t;
3927 * Save a capture to a file, in a particular format, saving either
3928 * all packets, all currently-displayed packets, or all marked packets.
3930 * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3931 * up a message box for the failure.
3934 save_record(capture_file *cf, frame_data *fdata,
3935 struct wtap_pkthdr *phdr, const guint8 *pd,
3938 save_callback_args_t *args = (save_callback_args_t *)argsp;
3939 struct wtap_pkthdr hdr;
3942 const char *pkt_comment;
3944 if (fdata->flags.has_user_comment)
3945 pkt_comment = cap_file_provider_get_user_comment(&cf->provider, fdata);
3947 pkt_comment = phdr->opt_comment;
3949 /* init the wtap header for saving */
3950 /* TODO: reuse phdr */
3951 /* XXX - these are the only flags that correspond to data that we have
3952 in the frame_data structure and that matter on a per-packet basis.
3954 For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3955 and "on the wire" lengths, or it doesn't.
3957 For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3960 For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3961 from the packet flags. */
3962 hdr.rec_type = phdr->rec_type;
3963 hdr.presence_flags = 0;
3964 if (fdata->flags.has_ts)
3965 hdr.presence_flags |= WTAP_HAS_TS;
3966 if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID)
3967 hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3968 if (phdr->presence_flags & WTAP_HAS_PACK_FLAGS)
3969 hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
3971 hdr.caplen = phdr->caplen;
3972 hdr.len = phdr->len;
3973 hdr.pkt_encap = phdr->pkt_encap;
3975 hdr.interface_id = phdr->interface_id; /* identifier of the interface. */
3977 hdr.pack_flags = phdr->pack_flags;
3978 hdr.opt_comment = g_strdup(pkt_comment);
3979 hdr.has_comment_changed = fdata->flags.has_user_comment ? TRUE : FALSE;
3982 hdr.pseudo_header = phdr->pseudo_header;
3985 hdr.pack_flags = /* XXX - 0 for now (any value for "we don't have it"?) */
3987 /* and save the packet */
3988 if (!wtap_dump(args->pdh, &hdr, pd, &err, &err_info)) {
3989 cfile_write_failure_alert_box(NULL, args->fname, err, err_info, fdata->num,
3994 g_free(hdr.opt_comment);
3999 * Can this capture file be written out in any format using Wiretap
4000 * rather than by copying the raw data?
4003 cf_can_write_with_wiretap(capture_file *cf)
4005 /* We don't care whether we support the comments in this file or not;
4006 if we can't, we'll offer the user the option of discarding the
4008 return wtap_dump_can_write(cf->linktypes, 0);
4012 * Should we let the user do a save?
4016 * the file has unsaved changes, and we can save it in some
4017 * format through Wiretap
4021 * the file is a temporary file and has no unsaved changes (so
4022 * that "saving" it just means copying it).
4024 * XXX - we shouldn't allow files to be edited if they can't be saved,
4025 * so cf->unsaved_changes should be true only if the file can be saved.
4027 * We don't care whether we support the comments in this file or not;
4028 * if we can't, we'll offer the user the option of discarding the
4032 cf_can_save(capture_file *cf)
4034 if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
4035 /* Saved changes, and we can write it out with Wiretap. */
4039 if (cf->is_tempfile && !cf->unsaved_changes) {
4041 * Temporary file with no unsaved changes, so we can just do a
4047 /* Nothing to save. */
4052 * Should we let the user do a "save as"?
4056 * we can save it in some format through Wiretap
4060 * the file is a temporary file and has no unsaved changes (so
4061 * that "saving" it just means copying it).
4063 * XXX - we shouldn't allow files to be edited if they can't be saved,
4064 * so cf->unsaved_changes should be true only if the file can be saved.
4066 * We don't care whether we support the comments in this file or not;
4067 * if we can't, we'll offer the user the option of discarding the
4071 cf_can_save_as(capture_file *cf)
4073 if (wtap_dump_can_write(cf->linktypes, 0)) {
4074 /* We can write it out with Wiretap. */
4078 if (cf->is_tempfile && !cf->unsaved_changes) {
4080 * Temporary file with no unsaved changes, so we can just do a
4086 /* Nothing to save. */
4091 * Does this file have unsaved data?
4094 cf_has_unsaved_data(capture_file *cf)
4097 * If this is a temporary file, or a file with unsaved changes, it
4100 return (cf->is_tempfile && cf->count>0) || cf->unsaved_changes;
4104 * Quick scan to find packet offsets.
4106 static cf_read_status_t
4107 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile)
4109 const struct wtap_pkthdr *phdr;
4114 progdlg_t *progbar = NULL;
4115 GTimer *prog_timer = g_timer_new();
4118 GTimeVal start_time;
4119 gchar status_str[100];
4124 /* Close the old handle. */
4125 wtap_close(cf->provider.wth);
4127 /* Open the new file. */
4128 /* XXX: this will go through all open_routines for a matching one. But right
4129 now rescan_file() is only used when a file is being saved to a different
4130 format than the original, and the user is not given a choice of which
4131 reader to use (only which format to save it in), so doing this makes
4133 cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4134 if (cf->provider.wth == NULL) {
4135 cfile_open_failure_alert_box(fname, err, err_info);
4136 return CF_READ_ERROR;
4139 /* We're scanning a file whose contents should be the same as what
4140 we had before, so we don't discard dissection state etc.. */
4143 /* Set the file name because we need it to set the follow stream filter.
4144 XXX - is that still true? We need it for other reasons, though,
4146 cf->filename = g_strdup(fname);
4148 /* Indicate whether it's a permanent or temporary file. */
4149 cf->is_tempfile = is_tempfile;
4151 /* No user changes yet. */
4152 cf->unsaved_changes = FALSE;
4154 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
4155 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4157 cf->snap = wtap_snapshot_length(cf->provider.wth);
4159 name_ptr = g_filename_display_basename(cf->filename);
4161 cf_callback_invoke(cf_cb_file_rescan_started, cf);
4163 /* Record whether the file is compressed.
4164 XXX - do we know this at open time? */
4165 cf->iscompressed = wtap_iscompressed(cf->provider.wth);
4167 /* Find the size of the file. */
4168 size = wtap_file_size(cf->provider.wth, NULL);
4170 g_timer_start(prog_timer);
4172 cf->stop_flag = FALSE;
4173 g_get_current_time(&start_time);
4176 phdr = wtap_phdr(cf->provider.wth);
4177 while ((wtap_read(cf->provider.wth, &err, &err_info, &data_offset))) {
4179 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4180 fdata->file_off = data_offset;
4183 cf->f_datalen = wtap_read_so_far(cf->provider.wth);
4185 /* Create the progress bar if necessary. */
4186 if (progress_is_slow(progbar, prog_timer, size, cf->f_datalen)) {
4187 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4188 progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4189 TRUE, &cf->stop_flag, &start_time, progbar_val);
4193 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
4194 * has elapsed. Calling update_progress_dlg and packets_bar_update will
4195 * likely trigger UI paint events, which might take a while depending on
4196 * the platform and display. Reset our timer *after* painting.
4198 if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
4199 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4200 /* update the packet bar content on the first run or frequently on very large files */
4201 update_progress_dlg(progbar, progbar_val, status_str);
4202 compute_elapsed(cf, &start_time);
4203 packets_bar_update();
4204 g_timer_start(prog_timer);
4208 if (cf->stop_flag) {
4209 /* Well, the user decided to abort the rescan. Sadly, as this
4210 isn't a reread, recovering is difficult, so we'll just
4211 close the current capture. */
4215 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4216 it's not already there.
4217 XXX - yes, this is O(N), so if every packet had a different
4218 link-layer encapsulation type, it'd be O(N^2) to read the file, but
4219 there are probably going to be a small number of encapsulation types
4221 cf_add_encapsulation_type(cf, phdr->pkt_encap);
4224 /* Free the display name */
4227 /* We're done reading the file; destroy the progress bar if it was created. */
4228 if (progbar != NULL)
4229 destroy_progress_dlg(progbar);
4230 g_timer_destroy(prog_timer);
4232 /* We're done reading sequentially through the file. */
4233 cf->state = FILE_READ_DONE;
4235 /* Close the sequential I/O side, to free up memory it requires. */
4236 wtap_sequential_close(cf->provider.wth);
4238 /* compute the time it took to load the file */
4239 compute_elapsed(cf, &start_time);
4241 /* Set the file encapsulation type now; we don't know what it is until
4242 we've looked at all the packets, as we don't know until then whether
4243 there's more than one type (and thus whether it's
4244 WTAP_ENCAP_PER_PACKET). */
4245 cf->lnk_t = wtap_file_encap(cf->provider.wth);
4247 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4249 if (cf->stop_flag) {
4250 /* Our caller will give up at this point. */
4251 return CF_READ_ABORTED;
4255 /* Put up a message box noting that the read failed somewhere along
4256 the line. Don't throw out the stuff we managed to read, though,
4258 cfile_read_failure_alert_box(NULL, err, err_info);
4259 return CF_READ_ERROR;
4265 cf_save_records(capture_file *cf, const char *fname, guint save_format,
4266 gboolean compressed, gboolean discard_comments,
4267 gboolean dont_reopen)
4270 gchar *fname_new = NULL;
4273 addrinfo_lists_t *addr_lists;
4277 gchar *display_basename;
4284 save_callback_args_t callback_args;
4285 gboolean needs_reload = FALSE;
4287 cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4289 addr_lists = get_addrinfo_list();
4291 if (save_format == cf->cd_t && compressed == cf->iscompressed
4292 && !discard_comments && !cf->unsaved_changes
4293 && (wtap_addrinfo_list_empty(addr_lists) || !wtap_dump_has_name_resolution(save_format))) {
4294 /* We're saving in the format it's already in, and we're not discarding
4295 comments, and there are no changes we have in memory that aren't saved
4296 to the file, and we have no name resolution information to write or
4297 the file format we're saving in doesn't support writing name
4298 resolution information, so we can just move or copy the raw data. */
4300 if (cf->is_tempfile) {
4301 /* The file being saved is a temporary file from a live
4302 capture, so it doesn't need to stay around under that name;
4303 first, try renaming the capture buffer file to the new name.
4304 This acts as a "safe save", in that, if the file already
4305 exists, the existing file will be removed only if the rename
4308 Sadly, on Windows, as we have the current capture file
4309 open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4310 (to cause the rename to remove an existing target), as
4311 done by ws_stdio_rename() (ws_rename() is #defined to
4312 be ws_stdio_rename() on Windows) will fail.
4314 According to the MSDN documentation for CreateFile(), if,
4315 when we open a capture file, we were to directly do a CreateFile(),
4316 opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4317 convert it to a file descriptor with _open_osfhandle(),
4318 that would allow the file to be renamed out from under us.
4320 However, that doesn't work in practice. Perhaps the problem
4321 is that the process doing the rename is the process that
4322 has the file open. */
4324 if (ws_rename(cf->filename, fname) == 0) {
4325 /* That succeeded - there's no need to copy the source file. */
4326 how_to_save = SAVE_WITH_MOVE;
4328 if (errno == EXDEV) {
4329 /* They're on different file systems, so we have to copy the
4331 how_to_save = SAVE_WITH_COPY;
4333 /* The rename failed, but not because they're on different
4334 file systems - put up an error message. (Or should we
4335 just punt and try to copy? The only reason why I'd
4336 expect the rename to fail and the copy to succeed would
4337 be if we didn't have permission to remove the file from
4338 the temporary directory, and that might be fixable - but
4339 is it worth requiring the user to go off and fix it?) */
4340 cf_rename_failure_alert_box(fname, errno);
4345 /* Windows - copy the file to its new location. */
4346 how_to_save = SAVE_WITH_COPY;
4349 /* It's a permanent file, so we should copy it, and not remove the
4351 how_to_save = SAVE_WITH_COPY;
4354 if (how_to_save == SAVE_WITH_COPY) {
4355 /* Copy the file, if we haven't moved it. If we're overwriting
4356 an existing file, we do it with a "safe save", by writing
4357 to a new file and, if the write succeeds, renaming the
4358 new file on top of the old file. */
4359 if (file_exists(fname)) {
4360 fname_new = g_strdup_printf("%s~", fname);
4361 if (!copy_file_binary_mode(cf->filename, fname_new))
4364 if (!copy_file_binary_mode(cf->filename, fname))
4369 /* Either we're saving in a different format or we're saving changes,
4370 such as added, modified, or removed comments, that haven't yet
4371 been written to the underlying file; we can't do that by copying
4372 or moving the capture file, we have to do it by writing the packets
4375 GArray *shb_hdrs = NULL;
4376 wtapng_iface_descriptions_t *idb_inf = NULL;
4377 GArray *nrb_hdrs = NULL;
4380 /* XXX: what free's this shb_hdr? */
4381 shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4382 idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4383 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4385 /* Determine what file encapsulation type we should use. */
4386 encap = wtap_dump_file_encap_type(cf->linktypes);
4388 if (file_exists(fname)) {
4389 /* We're overwriting an existing file; write out to a new file,
4390 and, if that succeeds, rename the new file on top of the
4391 old file. That makes this a "safe save", so that we don't
4392 lose the old file if we have a problem writing out the new
4393 file. (If the existing file is the current capture file,
4394 we *HAVE* to do that, otherwise we're overwriting the file
4395 from which we're reading the packets that we're writing!) */
4396 fname_new = g_strdup_printf("%s~", fname);
4397 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4398 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4400 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4401 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4407 cfile_dump_open_failure_alert_box(fname, err, save_format);
4411 /* Add address resolution */
4412 wtap_dump_set_addrinfo_list(pdh, addr_lists);
4414 /* Iterate through the list of packets, processing all the packets. */
4415 callback_args.pdh = pdh;
4416 callback_args.fname = fname;
4417 callback_args.file_type = save_format;
4418 switch (process_specified_records(cf, NULL, "Saving", "packets",
4419 TRUE, save_record, &callback_args, TRUE)) {
4422 /* Completed successfully. */
4426 /* The user decided to abort the saving.
4427 If we're writing to a temporary file, remove it.
4428 XXX - should we do so even if we're not writing to a
4430 wtap_dump_close(pdh, &err);
4431 if (fname_new != NULL)
4432 ws_unlink(fname_new);
4433 cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4434 return CF_WRITE_ABORTED;
4437 /* Error while saving.
4438 If we're writing to a temporary file, remove it. */
4439 if (fname_new != NULL)
4440 ws_unlink(fname_new);
4441 wtap_dump_close(pdh, &err);
4445 needs_reload = wtap_dump_get_needs_reload(pdh);
4447 if (!wtap_dump_close(pdh, &err)) {
4448 cfile_close_failure_alert_box(fname, err);
4452 how_to_save = SAVE_WITH_WTAP;
4455 if (fname_new != NULL) {
4456 /* We wrote out to fname_new, and should rename it on top of
4457 fname. fname_new is now closed, so that should be possible even
4458 on Windows. However, on Windows, we first need to close whatever
4459 file descriptors we have open for fname. */
4461 wtap_fdclose(cf->provider.wth);
4463 /* Now do the rename. */
4464 if (ws_rename(fname_new, fname) == -1) {
4465 /* Well, the rename failed. */
4466 cf_rename_failure_alert_box(fname, errno);
4468 /* Attempt to reopen the random file descriptor using the
4469 current file's filename. (At this point, the sequential
4470 file descriptor is closed.) */
4471 if (!wtap_fdreopen(cf->provider.wth, cf->filename, &err)) {
4472 /* Oh, well, we're screwed. */
4473 display_basename = g_filename_display_basename(cf->filename);
4474 simple_error_message_box(
4475 file_open_error_message(err, FALSE), display_basename);
4476 g_free(display_basename);
4483 /* If this was a temporary file, and we didn't do the save by doing
4484 a move, so the tempoary file is still around under its old name,
4486 if (cf->is_tempfile && how_to_save != SAVE_WITH_MOVE) {
4487 /* If this fails, there's not much we can do, so just ignore errors. */
4488 ws_unlink(cf->filename);
4491 cf_callback_invoke(cf_cb_file_save_finished, NULL);
4492 cf->unsaved_changes = FALSE;
4495 switch (how_to_save) {
4497 case SAVE_WITH_MOVE:
4498 /* We just moved the file, so the wtap structure refers to the
4499 new file, and all the information other than the filename
4500 and the "is temporary" status applies to the new file; just
4502 g_free(cf->filename);
4503 cf->filename = g_strdup(fname);
4504 cf->is_tempfile = FALSE;
4505 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4508 case SAVE_WITH_COPY:
4509 /* We just copied the file, so all the information other than
4510 the wtap structure, the filename, and the "is temporary"
4511 status applies to the new file; just update that. */
4512 wtap_close(cf->provider.wth);
4513 /* Although we're just "copying" and then opening the copy, it will
4514 try all open_routine readers to open the copy, so we need to
4515 reset the cfile's open_type. */
4516 cf->open_type = WTAP_TYPE_AUTO;
4517 cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4518 if (cf->provider.wth == NULL) {
4519 cfile_open_failure_alert_box(fname, err, err_info);
4522 g_free(cf->filename);
4523 cf->filename = g_strdup(fname);
4524 cf->is_tempfile = FALSE;
4526 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4529 case SAVE_WITH_WTAP:
4530 /* Open and read the file we saved to.
4532 XXX - this is somewhat of a waste; we already have the
4533 packets, all this gets us is updated file type information
4534 (which we could just stuff into "cf"), and having the new
4535 file be the one we have opened and from which we're reading
4536 the data, and it means we have to spend time opening and
4537 reading the file, which could be a significant amount of
4538 time if the file is large.
4540 If the capture-file-writing code were to return the
4541 seek offset of each packet it writes, we could save that
4542 in the frame_data structure for the frame, and just open
4543 the file without reading it again...
4545 ...as long as, for gzipped files, the process of writing
4546 out the file *also* generates the information needed to
4547 support fast random access to the compressed file. */
4548 /* rescan_file will cause us to try all open_routines, so
4549 reset cfile's open_type */
4550 cf->open_type = WTAP_TYPE_AUTO;
4551 /* There are cases when SAVE_WITH_WTAP can result in new packets
4552 being written to the file, e.g ERF records
4553 In that case, we need to reload the whole file */
4555 if (cf_open(cf, fname, WTAP_TYPE_AUTO, FALSE, &err) == CF_OK) {
4556 if (cf_read(cf, TRUE) != CF_READ_OK) {
4557 /* The rescan failed; just close the file. Either
4558 a dialog was popped up for the failure, so the
4559 user knows what happened, or they stopped the
4560 rescan, in which case they know what happened. */
4561 /* XXX: This is inconsistent with normal open/reload behaviour. */
4567 if (rescan_file(cf, fname, FALSE) != CF_READ_OK) {
4568 /* The rescan failed; just close the file. Either
4569 a dialog was popped up for the failure, so the
4570 user knows what happened, or they stopped the
4571 rescan, in which case they know what happened. */
4578 /* If we were told to discard the comments, do so. */
4579 if (discard_comments) {
4580 /* Remove SHB comment, if any. */
4581 wtap_write_shb_comment(cf->provider.wth, NULL);
4583 /* remove all user comments */
4584 for (framenum = 1; framenum <= cf->count; framenum++) {
4585 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4587 fdata->flags.has_phdr_comment = FALSE;
4588 fdata->flags.has_user_comment = FALSE;
4591 if (cf->provider.frames_user_comments) {
4592 g_tree_destroy(cf->provider.frames_user_comments);
4593 cf->provider.frames_user_comments = NULL;
4596 cf->packet_comment_count = 0;
4602 if (fname_new != NULL) {
4603 /* We were trying to write to a temporary file; get rid of it if it
4604 exists. (We don't care whether this fails, as, if it fails,
4605 there's not much we can do about it. I guess if it failed for
4606 a reason other than "it doesn't exist", we could report an
4607 error, so the user knows there's a junk file that they might
4608 want to clean up.) */
4609 ws_unlink(fname_new);
4612 cf_callback_invoke(cf_cb_file_save_failed, NULL);
4613 return CF_WRITE_ERROR;
4617 cf_export_specified_packets(capture_file *cf, const char *fname,
4618 packet_range_t *range, guint save_format,
4619 gboolean compressed)
4621 gchar *fname_new = NULL;
4624 save_callback_args_t callback_args;
4625 GArray *shb_hdrs = NULL;
4626 wtapng_iface_descriptions_t *idb_inf = NULL;
4627 GArray *nrb_hdrs = NULL;
4630 cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4632 packet_range_process_init(range);
4634 /* We're writing out specified packets from the specified capture
4635 file to another file. Even if all captured packets are to be
4636 written, don't special-case the operation - read each packet
4637 and then write it out if it's one of the specified ones. */
4639 /* XXX: what free's this shb_hdr? */
4640 shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4641 idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4642 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4644 /* Determine what file encapsulation type we should use. */
4645 encap = wtap_dump_file_encap_type(cf->linktypes);
4647 if (file_exists(fname)) {
4648 /* We're overwriting an existing file; write out to a new file,
4649 and, if that succeeds, rename the new file on top of the
4650 old file. That makes this a "safe save", so that we don't
4651 lose the old file if we have a problem writing out the new
4652 file. (If the existing file is the current capture file,
4653 we *HAVE* to do that, otherwise we're overwriting the file
4654 from which we're reading the packets that we're writing!) */
4655 fname_new = g_strdup_printf("%s~", fname);
4656 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4657 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4659 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4660 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4666 cfile_dump_open_failure_alert_box(fname, err, save_format);
4670 /* Add address resolution */
4671 wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4673 /* Iterate through the list of packets, processing the packets we were
4676 XXX - we've already called "packet_range_process_init(range)", but
4677 "process_specified_records()" will do it again. Fortunately,
4678 that's harmless in this case, as we haven't done anything to
4679 "range" since we initialized it. */
4680 callback_args.pdh = pdh;
4681 callback_args.fname = fname;
4682 callback_args.file_type = save_format;
4683 switch (process_specified_records(cf, range, "Writing", "specified records",
4684 TRUE, save_record, &callback_args, TRUE)) {
4687 /* Completed successfully. */
4691 /* The user decided to abort the saving.
4692 If we're writing to a temporary file, remove it.
4693 XXX - should we do so even if we're not writing to a
4695 wtap_dump_close(pdh, &err);
4696 if (fname_new != NULL)
4697 ws_unlink(fname_new);
4698 cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4699 return CF_WRITE_ABORTED;
4703 /* Error while saving.
4704 If we're writing to a temporary file, remove it. */
4705 if (fname_new != NULL)
4706 ws_unlink(fname_new);
4707 wtap_dump_close(pdh, &err);
4711 if (!wtap_dump_close(pdh, &err)) {
4712 cfile_close_failure_alert_box(fname, err);
4716 if (fname_new != NULL) {
4717 /* We wrote out to fname_new, and should rename it on top of
4718 fname; fname is now closed, so that should be possible even
4719 on Windows. Do the rename. */
4720 if (ws_rename(fname_new, fname) == -1) {
4721 /* Well, the rename failed. */
4722 cf_rename_failure_alert_box(fname, errno);
4727 cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4731 if (fname_new != NULL) {
4732 /* We were trying to write to a temporary file; get rid of it if it
4733 exists. (We don't care whether this fails, as, if it fails,
4734 there's not much we can do about it. I guess if it failed for
4735 a reason other than "it doesn't exist", we could report an
4736 error, so the user knows there's a junk file that they might
4737 want to clean up.) */
4738 ws_unlink(fname_new);
4741 cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4742 return CF_WRITE_ERROR;
4746 * XXX - whether we mention the source pathname, the target pathname,
4747 * or both depends on the error and on what we find if we look for
4748 * one or both of them.
4751 cf_rename_failure_alert_box(const char *filename, int err)
4753 gchar *display_basename;
4755 display_basename = g_filename_display_basename(filename);
4759 /* XXX - should check whether the source exists and, if not,
4760 report it as the problem and, if so, report the destination
4762 simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4767 /* XXX - if we're doing a rename after a safe save, we should
4768 probably say something else. */
4769 simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4774 /* XXX - this should probably mention both the source and destination
4776 simple_error_message_box("The file \"%s\" could not be moved: %s.",
4777 display_basename, wtap_strerror(err));
4780 g_free(display_basename);
4783 /* Reload the current capture file. */
4785 cf_reload(capture_file *cf) {
4787 gboolean is_tempfile;
4790 /* If the file could be opened, "cf_open()" calls "cf_close()"
4791 to get rid of state for the old capture file before filling in state
4792 for the new capture file. "cf_close()" will remove the file if
4793 it's a temporary file; we don't want that to happen (for one thing,
4794 it'd prevent subsequent reopens from working). Remember whether it's
4795 a temporary file, mark it as not being a temporary file, and then
4796 reopen it as the type of file it was.
4798 Also, "cf_close()" will free "cf->filename", so we must make
4799 a copy of it first. */
4800 filename = g_strdup(cf->filename);
4801 is_tempfile = cf->is_tempfile;
4802 cf->is_tempfile = FALSE;
4803 if (cf_open(cf, filename, cf->open_type, is_tempfile, &err) == CF_OK) {
4804 switch (cf_read(cf, TRUE)) {
4808 /* Just because we got an error, that doesn't mean we were unable
4809 to read any of the file; we handle what we could get from the
4813 case CF_READ_ABORTED:
4814 /* The user bailed out of re-reading the capture file; the
4815 capture file has been closed - just free the capture file name
4816 string and return (without changing the last containing
4822 /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
4823 Instead, the file was left open, so we should restore "cf->is_tempfile"
4826 XXX - change the menu? Presumably "cf_open()" will do that;
4827 make sure it does! */
4828 cf->is_tempfile = is_tempfile;
4830 /* "cf_open()" made a copy of the file name we handed it, so
4831 we should free up our copy. */
4841 * indent-tabs-mode: nil
4844 * ex: set shiftwidth=2 tabstop=8 expandtab:
4845 * :indentSize=2:tabSize=8:noTabs=true: