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 /* Find the widths for each of the columns - maximum of the
2376 width of the title and the width of the data - and construct
2377 a buffer with a line containing the column titles. */
2378 callback_args.num_visible_cols = num_visible_col;
2379 callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2380 callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2381 cp = &callback_args.header_line_buf[0];
2383 visible_col_count = 0;
2384 for (i = 0; i < cf->cinfo.num_cols; i++) {
2386 clp = g_list_nth(prefs.col_list, i);
2387 if (clp == NULL) /* Sanity check, Invalid column requested */
2390 cfmt = (fmt_data *) clp->data;
2391 if (cfmt->visible == FALSE)
2394 /* Save the order of visible columns */
2395 callback_args.visible_cols[visible_col_count] = i;
2397 /* Don't pad the last column. */
2398 if (i == last_visible_col)
2399 callback_args.col_widths[visible_col_count] = 0;
2401 callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.columns[i].col_title);
2402 data_width = get_column_char_width(get_column_format(i));
2403 if (data_width > callback_args.col_widths[visible_col_count])
2404 callback_args.col_widths[visible_col_count] = data_width;
2407 /* Find the length of the string for this column. */
2408 column_len = (int) strlen(cf->cinfo.columns[i].col_title);
2409 if (callback_args.col_widths[i] > column_len)
2410 column_len = callback_args.col_widths[visible_col_count];
2412 /* Make sure there's room in the line buffer for the column; if not,
2413 double its length. */
2414 line_len += column_len + 1; /* "+1" for space */
2415 if (line_len > callback_args.header_line_buf_len) {
2416 cp_off = (int) (cp - callback_args.header_line_buf);
2417 callback_args.header_line_buf_len = 2 * line_len;
2418 callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2419 callback_args.header_line_buf_len + 1);
2420 cp = callback_args.header_line_buf + cp_off;
2423 /* Right-justify the packet number column. */
2424 /* if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2425 g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2427 g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2429 if (i != cf->cinfo.num_cols - 1)
2432 visible_col_count++;
2436 /* Now start out the main line buffer with the same length as the
2437 header line buffer. */
2438 callback_args.line_buf_len = callback_args.header_line_buf_len;
2439 callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2440 } /* if (print_summary) */
2442 /* Create the protocol tree, and make it visible, if we're printing
2443 the dissection or the hex data.
2444 XXX - do we need it if we're just printing the hex data? */
2446 callback_args.print_args->print_dissections != print_dissections_none ||
2447 callback_args.print_args->print_hex ||
2448 have_custom_cols(&cf->cinfo) || have_field_extractors();
2449 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2451 /* Iterate through the list of packets, printing the packets we were
2453 ret = process_specified_records(cf, &print_args->range, "Printing",
2454 "selected packets", TRUE, print_packet,
2455 &callback_args, show_progress_bar);
2456 epan_dissect_cleanup(&callback_args.edt);
2457 g_free(callback_args.header_line_buf);
2458 g_free(callback_args.line_buf);
2459 g_free(callback_args.col_widths);
2460 g_free(callback_args.visible_cols);
2465 /* Completed successfully. */
2469 /* Well, the user decided to abort the printing.
2471 XXX - note that what got generated before they did that
2472 will get printed if we're piping to a print program; we'd
2473 have to write to a file and then hand that to the print
2474 program to make it actually not print anything. */
2478 /* Error while printing.
2480 XXX - note that what got generated before they did that
2481 will get printed if we're piping to a print program; we'd
2482 have to write to a file and then hand that to the print
2483 program to make it actually not print anything. */
2484 destroy_print_stream(print_args->stream);
2485 return CF_PRINT_WRITE_ERROR;
2488 if (!print_finale(print_args->stream)) {
2489 destroy_print_stream(print_args->stream);
2490 return CF_PRINT_WRITE_ERROR;
2493 if (!destroy_print_stream(print_args->stream))
2494 return CF_PRINT_WRITE_ERROR;
2502 print_args_t *print_args;
2503 } write_packet_callback_args_t;
2506 write_pdml_packet(capture_file *cf, frame_data *fdata,
2507 struct wtap_pkthdr *phdr, const guint8 *pd,
2510 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2512 /* Create the protocol tree, but don't fill in the column information. */
2513 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2514 frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2516 /* Write out the information in that tree. */
2517 write_pdml_proto_tree(NULL, NULL, PF_NONE, &args->edt, args->fh, FALSE);
2519 epan_dissect_reset(&args->edt);
2521 return !ferror(args->fh);
2525 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2527 write_packet_callback_args_t callback_args;
2531 fh = ws_fopen(print_args->file, "w");
2533 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2535 write_pdml_preamble(fh, cf->filename);
2538 return CF_PRINT_WRITE_ERROR;
2541 callback_args.fh = fh;
2542 callback_args.print_args = print_args;
2543 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2545 /* Iterate through the list of packets, printing the packets we were
2547 ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2548 "selected packets", TRUE,
2549 write_pdml_packet, &callback_args, TRUE);
2551 epan_dissect_cleanup(&callback_args.edt);
2556 /* Completed successfully. */
2560 /* Well, the user decided to abort the printing. */
2564 /* Error while printing. */
2566 return CF_PRINT_WRITE_ERROR;
2569 write_pdml_finale(fh);
2572 return CF_PRINT_WRITE_ERROR;
2575 /* XXX - check for an error */
2582 write_psml_packet(capture_file *cf, frame_data *fdata,
2583 struct wtap_pkthdr *phdr, const guint8 *pd,
2586 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2588 /* Fill in the column information */
2589 col_custom_prime_edt(&args->edt, &cf->cinfo);
2590 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2591 frame_tvbuff_new(&cf->provider, fdata, pd),
2593 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2595 /* Write out the column information. */
2596 write_psml_columns(&args->edt, args->fh, FALSE);
2598 epan_dissect_reset(&args->edt);
2600 return !ferror(args->fh);
2604 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2606 write_packet_callback_args_t callback_args;
2610 gboolean proto_tree_needed;
2612 fh = ws_fopen(print_args->file, "w");
2614 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2616 write_psml_preamble(&cf->cinfo, fh);
2619 return CF_PRINT_WRITE_ERROR;
2622 callback_args.fh = fh;
2623 callback_args.print_args = print_args;
2625 /* Fill in the column information, only create the protocol tree
2626 if having custom columns or field extractors. */
2627 proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2628 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2630 /* Iterate through the list of packets, printing the packets we were
2632 ret = process_specified_records(cf, &print_args->range, "Writing PSML",
2633 "selected packets", TRUE,
2634 write_psml_packet, &callback_args, TRUE);
2636 epan_dissect_cleanup(&callback_args.edt);
2641 /* Completed successfully. */
2645 /* Well, the user decided to abort the printing. */
2649 /* Error while printing. */
2651 return CF_PRINT_WRITE_ERROR;
2654 write_psml_finale(fh);
2657 return CF_PRINT_WRITE_ERROR;
2660 /* XXX - check for an error */
2667 write_csv_packet(capture_file *cf, frame_data *fdata,
2668 struct wtap_pkthdr *phdr, const guint8 *pd,
2671 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2673 /* Fill in the column information */
2674 col_custom_prime_edt(&args->edt, &cf->cinfo);
2675 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2676 frame_tvbuff_new(&cf->provider, fdata, pd),
2678 epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2680 /* Write out the column information. */
2681 write_csv_columns(&args->edt, args->fh);
2683 epan_dissect_reset(&args->edt);
2685 return !ferror(args->fh);
2689 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2691 write_packet_callback_args_t callback_args;
2692 gboolean proto_tree_needed;
2696 fh = ws_fopen(print_args->file, "w");
2698 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2700 write_csv_column_titles(&cf->cinfo, fh);
2703 return CF_PRINT_WRITE_ERROR;
2706 callback_args.fh = fh;
2707 callback_args.print_args = print_args;
2709 /* only create the protocol tree if having custom columns or field extractors. */
2710 proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2711 epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2713 /* Iterate through the list of packets, printing the packets we were
2715 ret = process_specified_records(cf, &print_args->range, "Writing CSV",
2716 "selected packets", TRUE,
2717 write_csv_packet, &callback_args, TRUE);
2719 epan_dissect_cleanup(&callback_args.edt);
2724 /* Completed successfully. */
2728 /* Well, the user decided to abort the printing. */
2732 /* Error while printing. */
2734 return CF_PRINT_WRITE_ERROR;
2737 /* XXX - check for an error */
2744 carrays_write_packet(capture_file *cf, frame_data *fdata,
2745 struct wtap_pkthdr *phdr,
2746 const guint8 *pd, void *argsp)
2748 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2750 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2751 frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2752 write_carrays_hex_data(fdata->num, args->fh, &args->edt);
2753 epan_dissect_reset(&args->edt);
2755 return !ferror(args->fh);
2759 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2761 write_packet_callback_args_t callback_args;
2765 fh = ws_fopen(print_args->file, "w");
2768 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2772 return CF_PRINT_WRITE_ERROR;
2775 callback_args.fh = fh;
2776 callback_args.print_args = print_args;
2777 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2779 /* Iterate through the list of packets, printing the packets we were
2781 ret = process_specified_records(cf, &print_args->range,
2783 "selected packets", TRUE,
2784 carrays_write_packet, &callback_args, TRUE);
2786 epan_dissect_cleanup(&callback_args.edt);
2790 /* Completed successfully. */
2793 /* Well, the user decided to abort the printing. */
2796 /* Error while printing. */
2798 return CF_PRINT_WRITE_ERROR;
2806 write_json_packet(capture_file *cf, frame_data *fdata,
2807 struct wtap_pkthdr *phdr, const guint8 *pd,
2810 write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2812 /* Create the protocol tree, but don't fill in the column information. */
2813 epan_dissect_run(&args->edt, cf->cd_t, phdr,
2814 frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2816 /* Write out the information in that tree. */
2817 write_json_proto_tree(NULL, args->print_args->print_dissections,
2818 args->print_args->print_hex, NULL, PF_NONE,
2819 &args->edt, proto_node_group_children_by_unique, args->fh);
2821 epan_dissect_reset(&args->edt);
2823 return !ferror(args->fh);
2827 cf_write_json_packets(capture_file *cf, print_args_t *print_args)
2829 write_packet_callback_args_t callback_args;
2833 fh = ws_fopen(print_args->file, "w");
2835 return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2837 write_json_preamble(fh);
2840 return CF_PRINT_WRITE_ERROR;
2843 callback_args.fh = fh;
2844 callback_args.print_args = print_args;
2845 epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2847 /* Iterate through the list of packets, printing the packets we were
2849 ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2850 "selected packets", TRUE,
2851 write_json_packet, &callback_args, TRUE);
2853 epan_dissect_cleanup(&callback_args.edt);
2858 /* Completed successfully. */
2862 /* Well, the user decided to abort the printing. */
2866 /* Error while printing. */
2868 return CF_PRINT_WRITE_ERROR;
2871 write_json_finale(fh);
2874 return CF_PRINT_WRITE_ERROR;
2877 /* XXX - check for an error */
2884 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2885 search_direction dir)
2889 mdata.string = string;
2890 mdata.string_len = strlen(string);
2891 return find_packet(cf, match_protocol_tree, &mdata, dir);
2895 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree, match_data *mdata)
2897 mdata->frame_matched = FALSE;
2898 mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2899 mdata->string_len = strlen(mdata->string);
2901 /* Iterate through all the nodes looking for matching text */
2902 proto_tree_children_foreach(tree, match_subtree_text, mdata);
2903 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2907 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2909 match_data *mdata = (match_data *)criterion;
2912 /* Load the frame's data. */
2913 if (!cf_read_record(cf, fdata)) {
2914 /* Attempt to get the packet failed. */
2918 /* Construct the protocol tree, including the displayed text */
2919 epan_dissect_init(&edt, cf->epan, TRUE, TRUE);
2920 /* We don't need the column information */
2921 epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
2922 frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
2925 /* Iterate through all the nodes, seeing if they have text that matches. */
2927 mdata->frame_matched = FALSE;
2928 proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
2929 epan_dissect_cleanup(&edt);
2930 return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2934 match_subtree_text(proto_node *node, gpointer data)
2936 match_data *mdata = (match_data *) data;
2937 const gchar *string = mdata->string;
2938 size_t string_len = mdata->string_len;
2939 capture_file *cf = mdata->cf;
2940 field_info *fi = PNODE_FINFO(node);
2941 gchar label_str[ITEM_LABEL_LENGTH];
2948 /* dissection with an invisible proto tree? */
2951 if (mdata->frame_matched) {
2952 /* We already had a match; don't bother doing any more work. */
2956 /* Don't match invisible entries. */
2957 if (PROTO_ITEM_IS_HIDDEN(node))
2960 /* was a free format label produced? */
2962 label_ptr = fi->rep->representation;
2964 /* no, make a generic label */
2965 label_ptr = label_str;
2966 proto_item_fill_label(fi, label_str);
2970 if (g_regex_match(cf->regex, label_ptr, (GRegexMatchFlags) 0, NULL)) {
2971 mdata->frame_matched = TRUE;
2976 /* Does that label match? */
2977 label_len = strlen(label_ptr);
2978 for (i = 0; i < label_len; i++) {
2979 c_char = label_ptr[i];
2981 c_char = g_ascii_toupper(c_char);
2982 if (c_char == string[c_match]) {
2984 if (c_match == string_len) {
2985 /* No need to look further; we have a match */
2986 mdata->frame_matched = TRUE;
2995 /* Recurse into the subtree, if it exists */
2996 if (node->first_child != NULL)
2997 proto_tree_children_foreach(node, match_subtree_text, mdata);
3001 cf_find_packet_summary_line(capture_file *cf, const char *string,
3002 search_direction dir)
3006 mdata.string = string;
3007 mdata.string_len = strlen(string);
3008 return find_packet(cf, match_summary_line, &mdata, dir);
3012 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
3014 match_data *mdata = (match_data *)criterion;
3015 const gchar *string = mdata->string;
3016 size_t string_len = mdata->string_len;
3018 const char *info_column;
3019 size_t info_column_len;
3020 match_result result = MR_NOTMATCHED;
3026 /* Load the frame's data. */
3027 if (!cf_read_record(cf, fdata)) {
3028 /* Attempt to get the packet failed. */
3032 /* Don't bother constructing the protocol tree */
3033 epan_dissect_init(&edt, cf->epan, FALSE, FALSE);
3034 /* Get the column information */
3035 epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3036 frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3039 /* Find the Info column */
3040 for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3041 if (cf->cinfo.columns[colx].fmt_matx[COL_INFO]) {
3042 /* Found it. See if we match. */
3043 info_column = edt.pi.cinfo->columns[colx].col_data;
3044 info_column_len = strlen(info_column);
3046 if (g_regex_match(cf->regex, info_column, (GRegexMatchFlags) 0, NULL)) {
3047 result = MR_MATCHED;
3051 for (i = 0; i < info_column_len; i++) {
3052 c_char = info_column[i];
3054 c_char = g_ascii_toupper(c_char);
3055 if (c_char == string[c_match]) {
3057 if (c_match == string_len) {
3058 result = MR_MATCHED;
3068 epan_dissect_cleanup(&edt);
3075 } cbs_t; /* "Counted byte string" */
3079 * The current match_* routines only support ASCII case insensitivity and don't
3080 * convert UTF-8 inputs to UTF-16 for matching.
3082 * We could modify them to use the GLib Unicode routines or the International
3083 * Components for Unicode library but it's not apparent that we could do so
3084 * without consuming a lot more CPU and memory or that searching would be
3085 * significantly better.
3089 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3090 search_direction dir)
3095 info.data_len = string_size;
3097 /* Regex, String or hex search? */
3099 /* Regular Expression search */
3100 return find_packet(cf, match_regex, NULL, dir);
3101 } else if (cf->string) {
3102 /* String search - what type of string? */
3103 switch (cf->scs_type) {
3105 case SCS_NARROW_AND_WIDE:
3106 return find_packet(cf, match_narrow_and_wide, &info, dir);
3109 return find_packet(cf, match_narrow, &info, dir);
3112 return find_packet(cf, match_wide, &info, dir);
3115 g_assert_not_reached();
3119 return find_packet(cf, match_binary, &info, dir);
3123 match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
3125 cbs_t *info = (cbs_t *)criterion;
3126 const guint8 *ascii_text = info->data;
3127 size_t textlen = info->data_len;
3128 match_result result;
3135 /* Load the frame's data. */
3136 if (!cf_read_record(cf, fdata)) {
3137 /* Attempt to get the packet failed. */
3141 result = MR_NOTMATCHED;
3142 buf_len = fdata->cap_len;
3143 pd = ws_buffer_start_ptr(&cf->buf);
3145 while (i < buf_len) {
3148 c_char = g_ascii_toupper(c_char);
3149 if (c_char != '\0') {
3150 if (c_char == ascii_text[c_match]) {
3152 if (c_match == textlen) {
3153 result = MR_MATCHED;
3154 cf->search_pos = i; /* Save the position of the last character
3155 for highlighting the field. */
3156 cf->search_len = (guint32)textlen;
3161 g_assert(i>=c_match);
3162 i -= (guint32)c_match;
3172 match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
3175 cbs_t *info = (cbs_t *)criterion;
3176 const guint8 *ascii_text = info->data;
3177 size_t textlen = info->data_len;
3178 match_result result;
3184 /* Load the frame's data. */
3185 if (!cf_read_record(cf, fdata)) {
3186 /* Attempt to get the packet failed. */
3190 result = MR_NOTMATCHED;
3191 buf_len = fdata->cap_len;
3192 pd = ws_buffer_start_ptr(&cf->buf);
3194 while (i < buf_len) {
3197 c_char = g_ascii_toupper(c_char);
3198 if (c_char == ascii_text[c_match]) {
3200 if (c_match == textlen) {
3201 result = MR_MATCHED;
3202 cf->search_pos = i; /* Save the position of the last character
3203 for highlighting the field. */
3204 cf->search_len = (guint32)textlen;
3209 g_assert(i>=c_match);
3210 i -= (guint32)c_match;
3220 match_wide(capture_file *cf, frame_data *fdata, void *criterion)
3222 cbs_t *info = (cbs_t *)criterion;
3223 const guint8 *ascii_text = info->data;
3224 size_t textlen = info->data_len;
3225 match_result result;
3232 /* Load the frame's data. */
3233 if (!cf_read_record(cf, fdata)) {
3234 /* Attempt to get the packet failed. */
3238 result = MR_NOTMATCHED;
3239 buf_len = fdata->cap_len;
3240 pd = ws_buffer_start_ptr(&cf->buf);
3242 while (i < buf_len) {
3245 c_char = g_ascii_toupper(c_char);
3246 if (c_char == ascii_text[c_match]) {
3248 if (c_match == textlen) {
3249 result = MR_MATCHED;
3250 cf->search_pos = i; /* Save the position of the last character
3251 for highlighting the field. */
3252 cf->search_len = (guint32)textlen;
3258 g_assert(i>=(c_match*2));
3259 i -= (guint32)c_match*2;
3268 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3270 cbs_t *info = (cbs_t *)criterion;
3271 const guint8 *binary_data = info->data;
3272 size_t datalen = info->data_len;
3273 match_result result;
3279 /* Load the frame's data. */
3280 if (!cf_read_record(cf, fdata)) {
3281 /* Attempt to get the packet failed. */
3285 result = MR_NOTMATCHED;
3286 buf_len = fdata->cap_len;
3287 pd = ws_buffer_start_ptr(&cf->buf);
3289 while (i < buf_len) {
3290 if (pd[i] == binary_data[c_match]) {
3292 if (c_match == datalen) {
3293 result = MR_MATCHED;
3294 cf->search_pos = i; /* Save the position of the last character
3295 for highlighting the field. */
3296 cf->search_len = (guint32)datalen;
3301 g_assert(i>=c_match);
3302 i -= (guint32)c_match;
3311 match_regex(capture_file *cf, frame_data *fdata, void *criterion _U_)
3313 match_result result = MR_NOTMATCHED;
3314 GMatchInfo *match_info = NULL;
3316 /* Load the frame's data. */
3317 if (!cf_read_record(cf, fdata)) {
3318 /* Attempt to get the packet failed. */
3322 if (g_regex_match_full(cf->regex, (const gchar *)ws_buffer_start_ptr(&cf->buf), fdata->cap_len,
3323 0, (GRegexMatchFlags) 0, &match_info, NULL))
3325 gint start_pos = 0, end_pos = 0;
3326 g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
3327 cf->search_pos = end_pos - 1;
3328 cf->search_len = end_pos - start_pos;
3329 result = MR_MATCHED;
3335 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3336 search_direction dir)
3338 return find_packet(cf, match_dfilter, sfcode, dir);
3342 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3343 search_direction dir)
3348 if (!dfilter_compile(filter, &sfcode, NULL)) {
3350 * XXX - this shouldn't happen, as the filter string is machine
3355 if (sfcode == NULL) {
3357 * XXX - this shouldn't happen, as the filter string is machine
3362 result = find_packet(cf, match_dfilter, sfcode, dir);
3363 dfilter_free(sfcode);
3368 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3370 dfilter_t *sfcode = (dfilter_t *)criterion;
3372 match_result result;
3374 /* Load the frame's data. */
3375 if (!cf_read_record(cf, fdata)) {
3376 /* Attempt to get the packet failed. */
3380 epan_dissect_init(&edt, cf->epan, TRUE, FALSE);
3381 epan_dissect_prime_with_dfilter(&edt, sfcode);
3382 epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3383 frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3385 result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3386 epan_dissect_cleanup(&edt);
3391 cf_find_packet_marked(capture_file *cf, search_direction dir)
3393 return find_packet(cf, match_marked, NULL, dir);
3397 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3399 return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3403 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3405 return find_packet(cf, match_time_reference, NULL, dir);
3409 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3411 return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3415 find_packet(capture_file *cf,
3416 match_result (*match_function)(capture_file *, frame_data *, void *),
3417 void *criterion, search_direction dir)
3419 frame_data *start_fd;
3422 frame_data *new_fd = NULL;
3423 progdlg_t *progbar = NULL;
3424 GTimer *prog_timer = g_timer_new();
3428 GTimeVal start_time;
3429 gchar status_str[100];
3431 match_result result;
3433 start_fd = cf->current_frame;
3434 if (start_fd != NULL) {
3435 /* Iterate through the list of packets, starting at the packet we've
3436 picked, calling a routine to run the filter on the packet, see if
3437 it matches, and stop if so. */
3439 framenum = start_fd->num;
3441 g_timer_start(prog_timer);
3442 /* Progress so far. */
3445 cf->stop_flag = FALSE;
3446 g_get_current_time(&start_time);
3448 title = cf->sfilter?cf->sfilter:"";
3450 /* Create the progress bar if necessary.
3451 We check on every iteration of the loop, so that it takes no
3452 longer than the standard time to create it (otherwise, for a
3453 large file, we might take considerably longer than that standard
3454 time in order to get to the next progress bar step). */
3455 if (progbar == NULL)
3456 progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3457 FALSE, &cf->stop_flag, &start_time, progbar_val);
3460 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
3461 * has elapsed. Calling update_progress_dlg and packets_bar_update will
3462 * likely trigger UI paint events, which might take a while depending on
3463 * the platform and display. Reset our timer *after* painting.
3465 if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
3466 /* let's not divide by zero. I should never be started
3467 * with count == 0, so let's assert that
3469 g_assert(cf->count > 0);
3471 progbar_val = (gfloat) count / cf->count;
3473 g_snprintf(status_str, sizeof(status_str),
3474 "%4u of %u packets", count, cf->count);
3475 update_progress_dlg(progbar, progbar_val, status_str);
3477 g_timer_start(prog_timer);
3480 if (cf->stop_flag) {
3481 /* Well, the user decided to abort the search. Go back to the
3482 frame where we started. */
3487 /* Go past the current frame. */
3488 if (dir == SD_BACKWARD) {
3489 /* Go on to the previous frame. */
3490 if (framenum == 1) {
3492 * XXX - other apps have a bit more of a detailed message
3493 * for this, and instead of offering "OK" and "Cancel",
3494 * they offer things such as "Continue" and "Cancel";
3495 * we need an API for popping up alert boxes with
3496 * {Verb} and "Cancel".
3499 if (prefs.gui_find_wrap)
3501 statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3502 framenum = cf->count; /* wrap around */
3506 statusbar_push_temporary_msg("Search reached the beginning.");
3507 framenum = start_fd->num; /* stay on previous packet */
3512 /* Go on to the next frame. */
3513 if (framenum == cf->count) {
3514 if (prefs.gui_find_wrap)
3516 statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3517 framenum = 1; /* wrap around */
3521 statusbar_push_temporary_msg("Search reached the end.");
3522 framenum = start_fd->num; /* stay on previous packet */
3527 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3531 /* Is this packet in the display? */
3532 if (fdata->flags.passed_dfilter) {
3533 /* Yes. Does it match the search criterion? */
3534 result = (*match_function)(cf, fdata, criterion);
3535 if (result == MR_ERROR) {
3536 /* Error; our caller has reported the error. Go back to the frame
3537 where we started. */
3540 } else if (result == MR_MATCHED) {
3541 /* Yes. Go to the new frame. */
3547 if (fdata == start_fd) {
3548 /* We're back to the frame we were on originally, and that frame
3549 doesn't match the search filter. The search failed. */
3554 /* We're done scanning the packets; destroy the progress bar if it
3556 if (progbar != NULL)
3557 destroy_progress_dlg(progbar);
3558 g_timer_destroy(prog_timer);
3561 if (new_fd != NULL) {
3562 /* Find and select */
3563 cf->search_in_progress = TRUE;
3564 found = packet_list_select_row_from_data(new_fd);
3565 cf->search_in_progress = FALSE;
3566 cf->search_pos = 0; /* Reset the position */
3567 cf->search_len = 0; /* Reset length */
3569 /* We didn't find a row corresponding to this frame.
3570 This means that the frame isn't being displayed currently,
3571 so we can't select it. */
3572 simple_message_box(ESD_TYPE_INFO, NULL,
3573 "The capture file is probably not fully dissected.",
3574 "End of capture exceeded.");
3577 return TRUE; /* success */
3579 return FALSE; /* failure */
3583 cf_goto_frame(capture_file *cf, guint fnumber)
3587 if (cf == NULL || cf->provider.frames == NULL) {
3588 /* we don't have a loaded capture file - fix for bugs 11810 & 11989 */
3589 statusbar_push_temporary_msg("There is no file loaded");
3590 return FALSE; /* we failed to go to that packet */
3593 fdata = frame_data_sequence_find(cf->provider.frames, fnumber);
3595 if (fdata == NULL) {
3596 /* we didn't find a packet with that packet number */
3597 statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3598 return FALSE; /* we failed to go to that packet */
3600 if (!fdata->flags.passed_dfilter) {
3601 /* that packet currently isn't displayed */
3602 /* XXX - add it to the set of displayed packets? */
3603 statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3604 return FALSE; /* we failed to go to that packet */
3607 if (!packet_list_select_row_from_data(fdata)) {
3608 /* We didn't find a row corresponding to this frame.
3609 This means that the frame isn't being displayed currently,
3610 so we can't select it. */
3611 simple_message_box(ESD_TYPE_INFO, NULL,
3612 "The capture file is probably not fully dissected.",
3613 "End of capture exceeded.");
3616 return TRUE; /* we got to that packet */
3620 * Go to frame specified by currently selected protocol tree item.
3623 cf_goto_framenum(capture_file *cf)
3625 header_field_info *hfinfo;
3628 if (cf->finfo_selected) {
3629 hfinfo = cf->finfo_selected->hfinfo;
3631 if (hfinfo->type == FT_FRAMENUM) {
3632 framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3634 return cf_goto_frame(cf, framenum);
3641 /* Select the packet on a given row. */
3643 cf_select_packet(capture_file *cf, int row)
3645 epan_dissect_t *old_edt;
3648 /* Get the frame data struct pointer for this frame */
3649 fdata = packet_list_get_row_data(row);
3651 if (fdata == NULL) {
3655 /* Get the data in that frame. */
3656 if (!cf_read_record (cf, fdata)) {
3660 /* Record that this frame is the current frame. */
3661 cf->current_frame = fdata;
3662 cf->current_row = row;
3665 /* Create the logical protocol tree. */
3666 /* We don't need the columns here. */
3667 cf->edt = epan_dissect_new(cf->epan, TRUE, TRUE);
3669 tap_build_interesting(cf->edt);
3670 epan_dissect_run(cf->edt, cf->cd_t, &cf->phdr,
3671 frame_tvbuff_new_buffer(&cf->provider, cf->current_frame, &cf->buf),
3672 cf->current_frame, NULL);
3674 dfilter_macro_build_ftv_cache(cf->edt->tree);
3676 cf_callback_invoke(cf_cb_packet_selected, cf);
3678 if (old_edt != NULL)
3679 epan_dissect_free(old_edt);
3683 /* Unselect the selected packet, if any. */
3685 cf_unselect_packet(capture_file *cf)
3687 epan_dissect_t *old_edt = cf->edt;
3691 /* No packet is selected. */
3692 cf->current_frame = NULL;
3693 cf->current_row = 0;
3695 cf_callback_invoke(cf_cb_packet_unselected, cf);
3697 /* No protocol tree means no selected field. */
3698 cf_unselect_field(cf);
3700 /* Destroy the epan_dissect_t for the unselected packet. */
3701 if (old_edt != NULL)
3702 epan_dissect_free(old_edt);
3705 /* Unset the selected protocol tree field, if any. */
3707 cf_unselect_field(capture_file *cf)
3709 cf->finfo_selected = NULL;
3711 cf_callback_invoke(cf_cb_field_unselected, cf);
3715 * Mark a particular frame.
3718 cf_mark_frame(capture_file *cf, frame_data *frame)
3720 if (! frame->flags.marked) {
3721 frame->flags.marked = TRUE;
3722 if (cf->count > cf->marked_count)
3728 * Unmark a particular frame.
3731 cf_unmark_frame(capture_file *cf, frame_data *frame)
3733 if (frame->flags.marked) {
3734 frame->flags.marked = FALSE;
3735 if (cf->marked_count > 0)
3741 * Ignore a particular frame.
3744 cf_ignore_frame(capture_file *cf, frame_data *frame)
3746 if (! frame->flags.ignored) {
3747 frame->flags.ignored = TRUE;
3748 if (cf->count > cf->ignored_count)
3749 cf->ignored_count++;
3754 * Un-ignore a particular frame.
3757 cf_unignore_frame(capture_file *cf, frame_data *frame)
3759 if (frame->flags.ignored) {
3760 frame->flags.ignored = FALSE;
3761 if (cf->ignored_count > 0)
3762 cf->ignored_count--;
3767 * Read the section comment.
3770 cf_read_section_comment(capture_file *cf)
3772 wtap_block_t shb_inf;
3776 /* XXX - support multiple SHBs */
3777 shb_inf = wtap_file_get_shb(cf->provider.wth);
3779 /* Get the first comment from the SHB. */
3780 /* XXX - support multiple comments */
3781 if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS)
3787 * Modify the section comment.
3790 cf_update_section_comment(capture_file *cf, gchar *comment)
3792 wtap_block_t shb_inf;
3796 /* XXX - support multiple SHBs */
3797 shb_inf = wtap_file_get_shb(cf->provider.wth);
3799 /* Get the first comment from the SHB. */
3800 /* XXX - support multiple comments */
3801 if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS) {
3802 /* There's no comment - add one. */
3803 wtap_block_add_string_option(shb_inf, OPT_COMMENT, comment, strlen(comment));
3805 /* See if the comment has changed or not */
3806 if (strcmp(shb_comment, comment) == 0) {
3811 /* The comment has changed, let's update it */
3812 wtap_block_set_nth_string_option_value(shb_inf, OPT_COMMENT, 0, comment, strlen(comment));
3814 /* Mark the file as having unsaved changes */
3815 cf->unsaved_changes = TRUE;
3819 * Get the comment on a packet (record).
3820 * If the comment has been edited, it returns the result of the edit,
3821 * otherwise it returns the comment from the file.
3824 cf_get_packet_comment(capture_file *cf, const frame_data *fd)
3828 /* fetch user comment */
3829 if (fd->flags.has_user_comment)
3830 return g_strdup(cap_file_provider_get_user_comment(&cf->provider, fd));
3832 /* fetch phdr comment */
3833 if (fd->flags.has_phdr_comment) {
3834 struct wtap_pkthdr phdr; /* Packet header */
3835 Buffer buf; /* Packet data */
3837 wtap_phdr_init(&phdr);
3838 ws_buffer_init(&buf, 1500);
3840 if (!cf_read_record_r(cf, fd, &phdr, &buf))
3841 { /* XXX, what we can do here? */ }
3843 comment = phdr.opt_comment;
3844 wtap_phdr_cleanup(&phdr);
3845 ws_buffer_free(&buf);
3852 * Update(replace) the comment on a capture from a frame
3855 cf_set_user_packet_comment(capture_file *cf, frame_data *fd, const gchar *new_comment)
3857 char *pkt_comment = cf_get_packet_comment(cf, fd);
3859 /* Check if the comment has changed */
3860 if (!g_strcmp0(pkt_comment, new_comment)) {
3861 g_free(pkt_comment);
3864 g_free(pkt_comment);
3867 cf->packet_comment_count--;
3870 cf->packet_comment_count++;
3872 cap_file_provider_set_user_comment(&cf->provider, fd, new_comment);
3874 expert_update_comment_count(cf->packet_comment_count);
3876 /* OK, we have unsaved changes. */
3877 cf->unsaved_changes = TRUE;
3882 * What types of comments does this capture file have?
3885 cf_comment_types(capture_file *cf)
3887 guint32 comment_types = 0;
3889 if (cf_read_section_comment(cf) != NULL)
3890 comment_types |= WTAP_COMMENT_PER_SECTION;
3891 if (cf->packet_comment_count != 0)
3892 comment_types |= WTAP_COMMENT_PER_PACKET;
3893 return comment_types;
3897 * Add a resolved address to this file's list of resolved addresses.
3900 cf_add_ip_name_from_string(capture_file *cf, const char *addr, const char *name)
3903 * XXX - support multiple resolved address lists, and add to the one
3904 * attached to this file?
3906 if (!add_ip_name_from_string(addr, name))
3909 /* OK, we have unsaved changes. */
3910 cf->unsaved_changes = TRUE;
3918 } save_callback_args_t;
3921 * Save a capture to a file, in a particular format, saving either
3922 * all packets, all currently-displayed packets, or all marked packets.
3924 * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3925 * up a message box for the failure.
3928 save_record(capture_file *cf, frame_data *fdata,
3929 struct wtap_pkthdr *phdr, const guint8 *pd,
3932 save_callback_args_t *args = (save_callback_args_t *)argsp;
3933 struct wtap_pkthdr hdr;
3936 const char *pkt_comment;
3938 if (fdata->flags.has_user_comment)
3939 pkt_comment = cap_file_provider_get_user_comment(&cf->provider, fdata);
3941 pkt_comment = phdr->opt_comment;
3943 /* init the wtap header for saving */
3944 /* TODO: reuse phdr */
3945 /* XXX - these are the only flags that correspond to data that we have
3946 in the frame_data structure and that matter on a per-packet basis.
3948 For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3949 and "on the wire" lengths, or it doesn't.
3951 For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3954 For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3955 from the packet flags. */
3956 hdr.rec_type = phdr->rec_type;
3957 hdr.presence_flags = 0;
3958 if (fdata->flags.has_ts)
3959 hdr.presence_flags |= WTAP_HAS_TS;
3960 if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID)
3961 hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3962 if (phdr->presence_flags & WTAP_HAS_PACK_FLAGS)
3963 hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
3965 hdr.caplen = phdr->caplen;
3966 hdr.len = phdr->len;
3967 hdr.pkt_encap = phdr->pkt_encap;
3969 hdr.interface_id = phdr->interface_id; /* identifier of the interface. */
3971 hdr.pack_flags = phdr->pack_flags;
3972 hdr.opt_comment = g_strdup(pkt_comment);
3973 hdr.has_comment_changed = fdata->flags.has_user_comment ? TRUE : FALSE;
3976 hdr.pseudo_header = phdr->pseudo_header;
3979 hdr.pack_flags = /* XXX - 0 for now (any value for "we don't have it"?) */
3981 /* and save the packet */
3982 if (!wtap_dump(args->pdh, &hdr, pd, &err, &err_info)) {
3983 cfile_write_failure_alert_box(NULL, args->fname, err, err_info, fdata->num,
3988 g_free(hdr.opt_comment);
3993 * Can this capture file be written out in any format using Wiretap
3994 * rather than by copying the raw data?
3997 cf_can_write_with_wiretap(capture_file *cf)
3999 /* We don't care whether we support the comments in this file or not;
4000 if we can't, we'll offer the user the option of discarding the
4002 return wtap_dump_can_write(cf->linktypes, 0);
4006 * Should we let the user do a save?
4010 * the file has unsaved changes, and we can save it in some
4011 * format through Wiretap
4015 * the file is a temporary file and has no unsaved changes (so
4016 * that "saving" it just means copying it).
4018 * XXX - we shouldn't allow files to be edited if they can't be saved,
4019 * so cf->unsaved_changes should be true only if the file can be saved.
4021 * We don't care whether we support the comments in this file or not;
4022 * if we can't, we'll offer the user the option of discarding the
4026 cf_can_save(capture_file *cf)
4028 if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
4029 /* Saved changes, and we can write it out with Wiretap. */
4033 if (cf->is_tempfile && !cf->unsaved_changes) {
4035 * Temporary file with no unsaved changes, so we can just do a
4041 /* Nothing to save. */
4046 * Should we let the user do a "save as"?
4050 * we can save it in some format through Wiretap
4054 * the file is a temporary file and has no unsaved changes (so
4055 * that "saving" it just means copying it).
4057 * XXX - we shouldn't allow files to be edited if they can't be saved,
4058 * so cf->unsaved_changes should be true only if the file can be saved.
4060 * We don't care whether we support the comments in this file or not;
4061 * if we can't, we'll offer the user the option of discarding the
4065 cf_can_save_as(capture_file *cf)
4067 if (wtap_dump_can_write(cf->linktypes, 0)) {
4068 /* We can write it out with Wiretap. */
4072 if (cf->is_tempfile && !cf->unsaved_changes) {
4074 * Temporary file with no unsaved changes, so we can just do a
4080 /* Nothing to save. */
4085 * Does this file have unsaved data?
4088 cf_has_unsaved_data(capture_file *cf)
4091 * If this is a temporary file, or a file with unsaved changes, it
4094 return (cf->is_tempfile && cf->count>0) || cf->unsaved_changes;
4098 * Quick scan to find packet offsets.
4100 static cf_read_status_t
4101 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile)
4103 const struct wtap_pkthdr *phdr;
4108 progdlg_t *progbar = NULL;
4109 GTimer *prog_timer = g_timer_new();
4112 GTimeVal start_time;
4113 gchar status_str[100];
4118 /* Close the old handle. */
4119 wtap_close(cf->provider.wth);
4121 /* Open the new file. */
4122 /* XXX: this will go through all open_routines for a matching one. But right
4123 now rescan_file() is only used when a file is being saved to a different
4124 format than the original, and the user is not given a choice of which
4125 reader to use (only which format to save it in), so doing this makes
4127 cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4128 if (cf->provider.wth == NULL) {
4129 cfile_open_failure_alert_box(fname, err, err_info);
4130 return CF_READ_ERROR;
4133 /* We're scanning a file whose contents should be the same as what
4134 we had before, so we don't discard dissection state etc.. */
4137 /* Set the file name because we need it to set the follow stream filter.
4138 XXX - is that still true? We need it for other reasons, though,
4140 cf->filename = g_strdup(fname);
4142 /* Indicate whether it's a permanent or temporary file. */
4143 cf->is_tempfile = is_tempfile;
4145 /* No user changes yet. */
4146 cf->unsaved_changes = FALSE;
4148 cf->cd_t = wtap_file_type_subtype(cf->provider.wth);
4149 cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4151 cf->snap = wtap_snapshot_length(cf->provider.wth);
4153 name_ptr = g_filename_display_basename(cf->filename);
4155 cf_callback_invoke(cf_cb_file_rescan_started, cf);
4157 /* Record whether the file is compressed.
4158 XXX - do we know this at open time? */
4159 cf->iscompressed = wtap_iscompressed(cf->provider.wth);
4161 /* Find the size of the file. */
4162 size = wtap_file_size(cf->provider.wth, NULL);
4164 g_timer_start(prog_timer);
4166 cf->stop_flag = FALSE;
4167 g_get_current_time(&start_time);
4170 phdr = wtap_phdr(cf->provider.wth);
4171 while ((wtap_read(cf->provider.wth, &err, &err_info, &data_offset))) {
4173 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4174 fdata->file_off = data_offset;
4177 cf->f_datalen = wtap_read_so_far(cf->provider.wth);
4179 /* Create the progress bar if necessary. */
4180 if (progress_is_slow(progbar, prog_timer, size, cf->f_datalen)) {
4181 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4182 progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4183 TRUE, &cf->stop_flag, &start_time, progbar_val);
4187 * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
4188 * has elapsed. Calling update_progress_dlg and packets_bar_update will
4189 * likely trigger UI paint events, which might take a while depending on
4190 * the platform and display. Reset our timer *after* painting.
4192 if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
4193 progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4194 /* update the packet bar content on the first run or frequently on very large files */
4195 update_progress_dlg(progbar, progbar_val, status_str);
4196 compute_elapsed(cf, &start_time);
4197 packets_bar_update();
4198 g_timer_start(prog_timer);
4202 if (cf->stop_flag) {
4203 /* Well, the user decided to abort the rescan. Sadly, as this
4204 isn't a reread, recovering is difficult, so we'll just
4205 close the current capture. */
4209 /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4210 it's not already there.
4211 XXX - yes, this is O(N), so if every packet had a different
4212 link-layer encapsulation type, it'd be O(N^2) to read the file, but
4213 there are probably going to be a small number of encapsulation types
4215 cf_add_encapsulation_type(cf, phdr->pkt_encap);
4218 /* Free the display name */
4221 /* We're done reading the file; destroy the progress bar if it was created. */
4222 if (progbar != NULL)
4223 destroy_progress_dlg(progbar);
4224 g_timer_destroy(prog_timer);
4226 /* We're done reading sequentially through the file. */
4227 cf->state = FILE_READ_DONE;
4229 /* Close the sequential I/O side, to free up memory it requires. */
4230 wtap_sequential_close(cf->provider.wth);
4232 /* compute the time it took to load the file */
4233 compute_elapsed(cf, &start_time);
4235 /* Set the file encapsulation type now; we don't know what it is until
4236 we've looked at all the packets, as we don't know until then whether
4237 there's more than one type (and thus whether it's
4238 WTAP_ENCAP_PER_PACKET). */
4239 cf->lnk_t = wtap_file_encap(cf->provider.wth);
4241 cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4243 if (cf->stop_flag) {
4244 /* Our caller will give up at this point. */
4245 return CF_READ_ABORTED;
4249 /* Put up a message box noting that the read failed somewhere along
4250 the line. Don't throw out the stuff we managed to read, though,
4252 cfile_read_failure_alert_box(NULL, err, err_info);
4253 return CF_READ_ERROR;
4259 cf_save_records(capture_file *cf, const char *fname, guint save_format,
4260 gboolean compressed, gboolean discard_comments,
4261 gboolean dont_reopen)
4264 gchar *fname_new = NULL;
4267 addrinfo_lists_t *addr_lists;
4271 gchar *display_basename;
4278 save_callback_args_t callback_args;
4279 gboolean needs_reload = FALSE;
4281 cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4283 addr_lists = get_addrinfo_list();
4285 if (save_format == cf->cd_t && compressed == cf->iscompressed
4286 && !discard_comments && !cf->unsaved_changes
4287 && !(addr_lists && wtap_dump_has_name_resolution(save_format))) {
4288 /* We're saving in the format it's already in, and we're
4289 not discarding comments, and there are no changes we have
4290 in memory that aren't saved to the file, and we have no name
4291 resolution blocks to write, so we can just move or copy the raw data. */
4293 if (cf->is_tempfile) {
4294 /* The file being saved is a temporary file from a live
4295 capture, so it doesn't need to stay around under that name;
4296 first, try renaming the capture buffer file to the new name.
4297 This acts as a "safe save", in that, if the file already
4298 exists, the existing file will be removed only if the rename
4301 Sadly, on Windows, as we have the current capture file
4302 open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4303 (to cause the rename to remove an existing target), as
4304 done by ws_stdio_rename() (ws_rename() is #defined to
4305 be ws_stdio_rename() on Windows) will fail.
4307 According to the MSDN documentation for CreateFile(), if,
4308 when we open a capture file, we were to directly do a CreateFile(),
4309 opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4310 convert it to a file descriptor with _open_osfhandle(),
4311 that would allow the file to be renamed out from under us.
4313 However, that doesn't work in practice. Perhaps the problem
4314 is that the process doing the rename is the process that
4315 has the file open. */
4317 if (ws_rename(cf->filename, fname) == 0) {
4318 /* That succeeded - there's no need to copy the source file. */
4319 how_to_save = SAVE_WITH_MOVE;
4321 if (errno == EXDEV) {
4322 /* They're on different file systems, so we have to copy the
4324 how_to_save = SAVE_WITH_COPY;
4326 /* The rename failed, but not because they're on different
4327 file systems - put up an error message. (Or should we
4328 just punt and try to copy? The only reason why I'd
4329 expect the rename to fail and the copy to succeed would
4330 be if we didn't have permission to remove the file from
4331 the temporary directory, and that might be fixable - but
4332 is it worth requiring the user to go off and fix it?) */
4333 cf_rename_failure_alert_box(fname, errno);
4338 /* Windows - copy the file to its new location. */
4339 how_to_save = SAVE_WITH_COPY;
4342 /* It's a permanent file, so we should copy it, and not remove the
4344 how_to_save = SAVE_WITH_COPY;
4347 if (how_to_save == SAVE_WITH_COPY) {
4348 /* Copy the file, if we haven't moved it. If we're overwriting
4349 an existing file, we do it with a "safe save", by writing
4350 to a new file and, if the write succeeds, renaming the
4351 new file on top of the old file. */
4352 if (file_exists(fname)) {
4353 fname_new = g_strdup_printf("%s~", fname);
4354 if (!copy_file_binary_mode(cf->filename, fname_new))
4357 if (!copy_file_binary_mode(cf->filename, fname))
4362 /* Either we're saving in a different format or we're saving changes,
4363 such as added, modified, or removed comments, that haven't yet
4364 been written to the underlying file; we can't do that by copying
4365 or moving the capture file, we have to do it by writing the packets
4368 GArray *shb_hdrs = NULL;
4369 wtapng_iface_descriptions_t *idb_inf = NULL;
4370 GArray *nrb_hdrs = NULL;
4373 /* XXX: what free's this shb_hdr? */
4374 shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4375 idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4376 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4378 /* Determine what file encapsulation type we should use. */
4379 encap = wtap_dump_file_encap_type(cf->linktypes);
4381 if (file_exists(fname)) {
4382 /* We're overwriting an existing file; write out to a new file,
4383 and, if that succeeds, rename the new file on top of the
4384 old file. That makes this a "safe save", so that we don't
4385 lose the old file if we have a problem writing out the new
4386 file. (If the existing file is the current capture file,
4387 we *HAVE* to do that, otherwise we're overwriting the file
4388 from which we're reading the packets that we're writing!) */
4389 fname_new = g_strdup_printf("%s~", fname);
4390 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4391 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4393 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4394 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4400 cfile_dump_open_failure_alert_box(fname, err, save_format);
4404 /* Add address resolution */
4405 wtap_dump_set_addrinfo_list(pdh, addr_lists);
4407 /* Iterate through the list of packets, processing all the packets. */
4408 callback_args.pdh = pdh;
4409 callback_args.fname = fname;
4410 callback_args.file_type = save_format;
4411 switch (process_specified_records(cf, NULL, "Saving", "packets",
4412 TRUE, save_record, &callback_args, TRUE)) {
4415 /* Completed successfully. */
4419 /* The user decided to abort the saving.
4420 If we're writing to a temporary file, remove it.
4421 XXX - should we do so even if we're not writing to a
4423 wtap_dump_close(pdh, &err);
4424 if (fname_new != NULL)
4425 ws_unlink(fname_new);
4426 cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4427 return CF_WRITE_ABORTED;
4430 /* Error while saving.
4431 If we're writing to a temporary file, remove it. */
4432 if (fname_new != NULL)
4433 ws_unlink(fname_new);
4434 wtap_dump_close(pdh, &err);
4438 needs_reload = wtap_dump_get_needs_reload(pdh);
4440 if (!wtap_dump_close(pdh, &err)) {
4441 cfile_close_failure_alert_box(fname, err);
4445 how_to_save = SAVE_WITH_WTAP;
4448 if (fname_new != NULL) {
4449 /* We wrote out to fname_new, and should rename it on top of
4450 fname. fname_new is now closed, so that should be possible even
4451 on Windows. However, on Windows, we first need to close whatever
4452 file descriptors we have open for fname. */
4454 wtap_fdclose(cf->provider.wth);
4456 /* Now do the rename. */
4457 if (ws_rename(fname_new, fname) == -1) {
4458 /* Well, the rename failed. */
4459 cf_rename_failure_alert_box(fname, errno);
4461 /* Attempt to reopen the random file descriptor using the
4462 current file's filename. (At this point, the sequential
4463 file descriptor is closed.) */
4464 if (!wtap_fdreopen(cf->provider.wth, cf->filename, &err)) {
4465 /* Oh, well, we're screwed. */
4466 display_basename = g_filename_display_basename(cf->filename);
4467 simple_error_message_box(
4468 file_open_error_message(err, FALSE), display_basename);
4469 g_free(display_basename);
4476 /* If this was a temporary file, and we didn't do the save by doing
4477 a move, so the tempoary file is still around under its old name,
4479 if (cf->is_tempfile) {
4480 /* If this fails, there's not much we can do, so just ignore errors. */
4481 ws_unlink(cf->filename);
4484 cf_callback_invoke(cf_cb_file_save_finished, NULL);
4485 cf->unsaved_changes = FALSE;
4488 switch (how_to_save) {
4490 case SAVE_WITH_MOVE:
4491 /* We just moved the file, so the wtap structure refers to the
4492 new file, and all the information other than the filename
4493 and the "is temporary" status applies to the new file; just
4495 g_free(cf->filename);
4496 cf->filename = g_strdup(fname);
4497 cf->is_tempfile = FALSE;
4498 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4501 case SAVE_WITH_COPY:
4502 /* We just copied the file, so all the information other than
4503 the wtap structure, the filename, and the "is temporary"
4504 status applies to the new file; just update that. */
4505 wtap_close(cf->provider.wth);
4506 /* Although we're just "copying" and then opening the copy, it will
4507 try all open_routine readers to open the copy, so we need to
4508 reset the cfile's open_type. */
4509 cf->open_type = WTAP_TYPE_AUTO;
4510 cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4511 if (cf->provider.wth == NULL) {
4512 cfile_open_failure_alert_box(fname, err, err_info);
4515 g_free(cf->filename);
4516 cf->filename = g_strdup(fname);
4517 cf->is_tempfile = FALSE;
4519 cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4522 case SAVE_WITH_WTAP:
4523 /* Open and read the file we saved to.
4525 XXX - this is somewhat of a waste; we already have the
4526 packets, all this gets us is updated file type information
4527 (which we could just stuff into "cf"), and having the new
4528 file be the one we have opened and from which we're reading
4529 the data, and it means we have to spend time opening and
4530 reading the file, which could be a significant amount of
4531 time if the file is large.
4533 If the capture-file-writing code were to return the
4534 seek offset of each packet it writes, we could save that
4535 in the frame_data structure for the frame, and just open
4536 the file without reading it again...
4538 ...as long as, for gzipped files, the process of writing
4539 out the file *also* generates the information needed to
4540 support fast random access to the compressed file. */
4541 /* rescan_file will cause us to try all open_routines, so
4542 reset cfile's open_type */
4543 cf->open_type = WTAP_TYPE_AUTO;
4544 /* There are cases when SAVE_WITH_WTAP can result in new packets
4545 being written to the file, e.g ERF records
4546 In that case, we need to reload the whole file */
4548 if (cf_open(cf, fname, WTAP_TYPE_AUTO, FALSE, &err) == CF_OK) {
4549 if (cf_read(cf, TRUE) != CF_READ_OK) {
4550 /* The rescan failed; just close the file. Either
4551 a dialog was popped up for the failure, so the
4552 user knows what happened, or they stopped the
4553 rescan, in which case they know what happened. */
4554 /* XXX: This is inconsistent with normal open/reload behaviour. */
4560 if (rescan_file(cf, fname, FALSE) != CF_READ_OK) {
4561 /* The rescan failed; just close the file. Either
4562 a dialog was popped up for the failure, so the
4563 user knows what happened, or they stopped the
4564 rescan, in which case they know what happened. */
4571 /* If we were told to discard the comments, do so. */
4572 if (discard_comments) {
4573 /* Remove SHB comment, if any. */
4574 wtap_write_shb_comment(cf->provider.wth, NULL);
4576 /* remove all user comments */
4577 for (framenum = 1; framenum <= cf->count; framenum++) {
4578 fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4580 fdata->flags.has_phdr_comment = FALSE;
4581 fdata->flags.has_user_comment = FALSE;
4584 if (cf->provider.frames_user_comments) {
4585 g_tree_destroy(cf->provider.frames_user_comments);
4586 cf->provider.frames_user_comments = NULL;
4589 cf->packet_comment_count = 0;
4595 if (fname_new != NULL) {
4596 /* We were trying to write to a temporary file; get rid of it if it
4597 exists. (We don't care whether this fails, as, if it fails,
4598 there's not much we can do about it. I guess if it failed for
4599 a reason other than "it doesn't exist", we could report an
4600 error, so the user knows there's a junk file that they might
4601 want to clean up.) */
4602 ws_unlink(fname_new);
4605 cf_callback_invoke(cf_cb_file_save_failed, NULL);
4606 return CF_WRITE_ERROR;
4610 cf_export_specified_packets(capture_file *cf, const char *fname,
4611 packet_range_t *range, guint save_format,
4612 gboolean compressed)
4614 gchar *fname_new = NULL;
4617 save_callback_args_t callback_args;
4618 GArray *shb_hdrs = NULL;
4619 wtapng_iface_descriptions_t *idb_inf = NULL;
4620 GArray *nrb_hdrs = NULL;
4623 cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4625 packet_range_process_init(range);
4627 /* We're writing out specified packets from the specified capture
4628 file to another file. Even if all captured packets are to be
4629 written, don't special-case the operation - read each packet
4630 and then write it out if it's one of the specified ones. */
4632 /* XXX: what free's this shb_hdr? */
4633 shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4634 idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4635 nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4637 /* Determine what file encapsulation type we should use. */
4638 encap = wtap_dump_file_encap_type(cf->linktypes);
4640 if (file_exists(fname)) {
4641 /* We're overwriting an existing file; write out to a new file,
4642 and, if that succeeds, rename the new file on top of the
4643 old file. That makes this a "safe save", so that we don't
4644 lose the old file if we have a problem writing out the new
4645 file. (If the existing file is the current capture file,
4646 we *HAVE* to do that, otherwise we're overwriting the file
4647 from which we're reading the packets that we're writing!) */
4648 fname_new = g_strdup_printf("%s~", fname);
4649 pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4650 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4652 pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4653 compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4659 cfile_dump_open_failure_alert_box(fname, err, save_format);
4663 /* Add address resolution */
4664 wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4666 /* Iterate through the list of packets, processing the packets we were
4669 XXX - we've already called "packet_range_process_init(range)", but
4670 "process_specified_records()" will do it again. Fortunately,
4671 that's harmless in this case, as we haven't done anything to
4672 "range" since we initialized it. */
4673 callback_args.pdh = pdh;
4674 callback_args.fname = fname;
4675 callback_args.file_type = save_format;
4676 switch (process_specified_records(cf, range, "Writing", "specified records",
4677 TRUE, save_record, &callback_args, TRUE)) {
4680 /* Completed successfully. */
4684 /* The user decided to abort the saving.
4685 If we're writing to a temporary file, remove it.
4686 XXX - should we do so even if we're not writing to a
4688 wtap_dump_close(pdh, &err);
4689 if (fname_new != NULL)
4690 ws_unlink(fname_new);
4691 cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4692 return CF_WRITE_ABORTED;
4696 /* Error while saving.
4697 If we're writing to a temporary file, remove it. */
4698 if (fname_new != NULL)
4699 ws_unlink(fname_new);
4700 wtap_dump_close(pdh, &err);
4704 if (!wtap_dump_close(pdh, &err)) {
4705 cfile_close_failure_alert_box(fname, err);
4709 if (fname_new != NULL) {
4710 /* We wrote out to fname_new, and should rename it on top of
4711 fname; fname is now closed, so that should be possible even
4712 on Windows. Do the rename. */
4713 if (ws_rename(fname_new, fname) == -1) {
4714 /* Well, the rename failed. */
4715 cf_rename_failure_alert_box(fname, errno);
4720 cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4724 if (fname_new != NULL) {
4725 /* We were trying to write to a temporary file; get rid of it if it
4726 exists. (We don't care whether this fails, as, if it fails,
4727 there's not much we can do about it. I guess if it failed for
4728 a reason other than "it doesn't exist", we could report an
4729 error, so the user knows there's a junk file that they might
4730 want to clean up.) */
4731 ws_unlink(fname_new);
4734 cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4735 return CF_WRITE_ERROR;
4739 * XXX - whether we mention the source pathname, the target pathname,
4740 * or both depends on the error and on what we find if we look for
4741 * one or both of them.
4744 cf_rename_failure_alert_box(const char *filename, int err)
4746 gchar *display_basename;
4748 display_basename = g_filename_display_basename(filename);
4752 /* XXX - should check whether the source exists and, if not,
4753 report it as the problem and, if so, report the destination
4755 simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4760 /* XXX - if we're doing a rename after a safe save, we should
4761 probably say something else. */
4762 simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4767 /* XXX - this should probably mention both the source and destination
4769 simple_error_message_box("The file \"%s\" could not be moved: %s.",
4770 display_basename, wtap_strerror(err));
4773 g_free(display_basename);
4776 /* Reload the current capture file. */
4778 cf_reload(capture_file *cf) {
4780 gboolean is_tempfile;
4783 /* If the file could be opened, "cf_open()" calls "cf_close()"
4784 to get rid of state for the old capture file before filling in state
4785 for the new capture file. "cf_close()" will remove the file if
4786 it's a temporary file; we don't want that to happen (for one thing,
4787 it'd prevent subsequent reopens from working). Remember whether it's
4788 a temporary file, mark it as not being a temporary file, and then
4789 reopen it as the type of file it was.
4791 Also, "cf_close()" will free "cf->filename", so we must make
4792 a copy of it first. */
4793 filename = g_strdup(cf->filename);
4794 is_tempfile = cf->is_tempfile;
4795 cf->is_tempfile = FALSE;
4796 if (cf_open(cf, filename, cf->open_type, is_tempfile, &err) == CF_OK) {
4797 switch (cf_read(cf, TRUE)) {
4801 /* Just because we got an error, that doesn't mean we were unable
4802 to read any of the file; we handle what we could get from the
4806 case CF_READ_ABORTED:
4807 /* The user bailed out of re-reading the capture file; the
4808 capture file has been closed - just free the capture file name
4809 string and return (without changing the last containing
4815 /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
4816 Instead, the file was left open, so we should restore "cf->is_tempfile"
4819 XXX - change the menu? Presumably "cf_open()" will do that;
4820 make sure it does! */
4821 cf->is_tempfile = is_tempfile;
4823 /* "cf_open()" made a copy of the file name we handed it, so
4824 we should free up our copy. */
4834 * indent-tabs-mode: nil
4837 * ex: set shiftwidth=2 tabstop=8 expandtab:
4838 * :indentSize=2:tabSize=8:noTabs=true: