Qt: About dialog updates.
[metze/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * Wireshark - Network traffic analyzer
5  * By Gerald Combs <gerald@wireshark.org>
6  * Copyright 1998 Gerald Combs
7  *
8  * SPDX-License-Identifier: GPL-2.0+
9  */
10
11 #include <config.h>
12
13 #include <time.h>
14
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <string.h>
18 #include <ctype.h>
19 #include <errno.h>
20
21 #include <wsutil/tempfile.h>
22 #include <wsutil/file_util.h>
23 #include <wsutil/filesystem.h>
24 #include <version_info.h>
25
26 #include <wiretap/merge.h>
27
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>
37 #include <epan/tap.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>
44
45 #include "cfile.h"
46 #include "file.h"
47 #include "fileset.h"
48 #include "frame_tvbuff.h"
49
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"
55
56 /* Needed for addrinfo */
57 #ifdef HAVE_SYS_TYPES_H
58 # include <sys/types.h>
59 #endif
60
61 #ifdef HAVE_SYS_SOCKET_H
62 #include <sys/socket.h>
63 #endif
64
65 #ifdef HAVE_NETINET_IN_H
66 # include <netinet/in.h>
67 #endif
68
69 #ifdef _WIN32
70 # include <winsock2.h>
71 # include <ws2tcpip.h>
72 #endif
73
74 #ifdef HAVE_LIBPCAP
75 gboolean auto_scroll_live; /* GTK+ only? */
76 #endif
77
78 static int read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
79     column_info *cinfo, gint64 offset);
80
81 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);
82
83 typedef enum {
84   MR_NOTMATCHED,
85   MR_MATCHED,
86   MR_ERROR
87 } match_result;
88 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
89     void *criterion);
90 static void match_subtree_text(proto_node *node, gpointer data);
91 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
92     void *criterion);
93 static match_result match_narrow_and_wide(capture_file *cf, frame_data *fdata,
94     void *criterion);
95 static match_result match_narrow(capture_file *cf, frame_data *fdata,
96     void *criterion);
97 static match_result match_wide(capture_file *cf, frame_data *fdata,
98     void *criterion);
99 static match_result match_binary(capture_file *cf, frame_data *fdata,
100     void *criterion);
101 static match_result match_regex(capture_file *cf, frame_data *fdata,
102     void *criterion);
103 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
104     void *criterion);
105 static match_result match_marked(capture_file *cf, frame_data *fdata,
106     void *criterion);
107 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
108     void *criterion);
109 static gboolean find_packet(capture_file *cf,
110     match_result (*match_function)(capture_file *, frame_data *, void *),
111     void *criterion, search_direction dir);
112
113 static void cf_rename_failure_alert_box(const char *filename, int err);
114 static void ref_time_packets(capture_file *cf);
115
116 /* Seconds spent processing packets between pushing UI updates. */
117 #define PROGBAR_UPDATE_INTERVAL 0.150
118
119 /* Show the progress bar after this many seconds. */
120 #define PROGBAR_SHOW_DELAY 0.5
121
122 /*
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.
126  */
127 typedef struct {
128   cf_callback_t cb_fct;
129   gpointer      user_data;
130 } cf_callback_data_t;
131
132 static GList *cf_callbacks = NULL;
133
134 static void
135 cf_callback_invoke(int event, gpointer data)
136 {
137   cf_callback_data_t *cb;
138   GList              *cb_item = cf_callbacks;
139
140   /* there should be at least one interested */
141   g_assert(cb_item != NULL);
142
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);
147   }
148 }
149
150
151 void
152 cf_callback_add(cf_callback_t func, gpointer user_data)
153 {
154   cf_callback_data_t *cb;
155
156   cb = g_new(cf_callback_data_t,1);
157   cb->cb_fct = func;
158   cb->user_data = user_data;
159
160   cf_callbacks = g_list_prepend(cf_callbacks, cb);
161 }
162
163 void
164 cf_callback_remove(cf_callback_t func, gpointer user_data)
165 {
166   cf_callback_data_t *cb;
167   GList              *cb_item = cf_callbacks;
168
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);
173       g_free(cb);
174       return;
175     }
176     cb_item = g_list_next(cb_item);
177   }
178
179   g_assert_not_reached();
180 }
181
182 void
183 cf_timestamp_auto_precision(capture_file *cf)
184 {
185   int i;
186
187   /* don't try to get the file's precision if none is opened */
188   if (cf->state == FILE_CLOSED) {
189     return;
190   }
191
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);
197     }
198   }
199 }
200
201 gulong
202 cf_get_computed_elapsed(capture_file *cf)
203 {
204   return cf->computed_elapsed;
205 }
206
207 /*
208  * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
209  * replace this
210  */
211 static void compute_elapsed(capture_file *cf, GTimeVal *start_time)
212 {
213   gdouble  delta_time;
214   GTimeVal time_now;
215
216   g_get_current_time(&time_now);
217
218   delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
219     time_now.tv_usec - start_time->tv_usec;
220
221   cf->computed_elapsed = (gulong) (delta_time / 1000); /* ms */
222 }
223
224 static const nstime_t *
225 ws_get_frame_ts(struct packet_provider_data *prov, guint32 frame_num)
226 {
227   if (prov->prev_dis && prov->prev_dis->num == frame_num)
228     return &prov->prev_dis->abs_ts;
229
230   if (prov->prev_cap && prov->prev_cap->num == frame_num)
231     return &prov->prev_cap->abs_ts;
232
233   if (prov->frames) {
234     frame_data *fd = frame_data_sequence_find(prov->frames, frame_num);
235
236     return (fd) ? &fd->abs_ts : NULL;
237   }
238
239   return NULL;
240 }
241
242 static epan_t *
243 ws_epan_new(capture_file *cf)
244 {
245   static const struct packet_provider_funcs funcs = {
246     ws_get_frame_ts,
247     cap_file_provider_get_interface_name,
248     cap_file_provider_get_interface_description,
249     cap_file_provider_get_user_comment
250   };
251
252   return epan_new(&cf->provider, &funcs);
253 }
254
255 cf_status_t
256 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
257 {
258   wtap  *wth;
259   gchar *err_info;
260
261   wth = wtap_open_offline(fname, type, err, &err_info, TRUE);
262   if (wth == NULL)
263     goto fail;
264
265   /* The open succeeded.  Close whatever capture file we had open,
266      and fill in the information for this file. */
267   cf_close(cf);
268
269   /* Initialize the packet header. */
270   wtap_phdr_init(&cf->phdr);
271
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);
275
276   /* Create new epan session for dissection.
277    * (The old one was freed in cf_close().)
278    */
279   cf->epan = ws_epan_new(cf);
280
281   /* We're about to start reading the file. */
282   cf->state = FILE_READ_IN_PROGRESS;
283
284   cf->provider.wth = wth;
285   cf->f_datalen = 0;
286
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,
289      in any case. */
290   cf->filename = g_strdup(fname);
291
292   /* Indicate whether it's a permanent or temporary file. */
293   cf->is_tempfile = is_tempfile;
294
295   /* No user changes yet. */
296   cf->unsaved_changes = FALSE;
297
298   cf->computed_elapsed = 0;
299
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);
303   cf->count     = 0;
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;
310   cf->drops     = 0;
311   cf->snap      = wtap_snapshot_length(cf->provider.wth);
312
313   /* Allocate a frame_data_sequence for the frames in this file */
314   cf->provider.frames = new_frame_data_sequence();
315
316   nstime_set_zero(&cf->elapsed_time);
317   cf->provider.ref = NULL;
318   cf->provider.prev_dis = NULL;
319   cf->provider.prev_cap = NULL;
320   cf->cum_bytes = 0;
321
322   packet_list_queue_draw();
323   cf_callback_invoke(cf_cb_file_opened, cf);
324
325   if (cf->cd_t == WTAP_FILE_TYPE_SUBTYPE_BER) {
326     /* tell the BER dissector the file name */
327     ber_set_filename(cf->filename);
328   }
329
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);
332
333   return CF_OK;
334
335 fail:
336   cfile_open_failure_alert_box(fname, *err, err_info);
337   return CF_ERROR;
338 }
339
340 /*
341  * Add an encapsulation type to cf->linktypes.
342  */
343 static void
344 cf_add_encapsulation_type(capture_file *cf, int encap)
345 {
346   guint i;
347
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 */
351   }
352   /* It's not already there - add it. */
353   g_array_append_val(cf->linktypes, encap);
354 }
355
356 /* Reset everything to a pristine state */
357 void
358 cf_close(capture_file *cf)
359 {
360   cf->stop_flag = FALSE;
361   if (cf->state == FILE_CLOSED)
362     return; /* Nothing to do */
363
364   /* Die if we're in the middle of reading a file. */
365   g_assert(cf->state != FILE_READ_IN_PROGRESS);
366
367   cf_callback_invoke(cf_cb_file_closing, cf);
368
369   /* close things, if not already closed before */
370   color_filters_cleanup();
371
372   if (cf->provider.wth) {
373     wtap_close(cf->provider.wth);
374     cf->provider.wth = NULL;
375   }
376   /* We have no file open... */
377   if (cf->filename != NULL) {
378     /* If it's a temporary file, remove it. */
379     if (cf->is_tempfile)
380       ws_unlink(cf->filename);
381     g_free(cf->filename);
382     cf->filename = NULL;
383   }
384   /* ...which means we have no changes to that file to save. */
385   cf->unsaved_changes = FALSE;
386
387   /* no open_routine type */
388   cf->open_type = WTAP_TYPE_AUTO;
389
390   /* Clean up the packet header. */
391   wtap_phdr_cleanup(&cf->phdr);
392
393   /* Free up the packet buffer. */
394   ws_buffer_free(&cf->buf);
395
396   dfilter_free(cf->rfcode);
397   cf->rfcode = NULL;
398   if (cf->provider.frames != NULL) {
399     free_frame_data_sequence(cf->provider.frames);
400     cf->provider.frames = NULL;
401   }
402   if (cf->provider.frames_user_comments) {
403     g_tree_destroy(cf->provider.frames_user_comments);
404     cf->provider.frames_user_comments = NULL;
405   }
406   cf_unselect_packet(cf);   /* nothing to select */
407   cf->first_displayed = 0;
408   cf->last_displayed = 0;
409
410   /* No frames, no frame selected, no field in that frame selected. */
411   cf->count = 0;
412   cf->current_frame = 0;
413   cf->current_row = 0;
414   cf->finfo_selected = NULL;
415
416   /* No frame link-layer types, either. */
417   if (cf->linktypes != NULL) {
418     g_array_free(cf->linktypes, TRUE);
419     cf->linktypes = NULL;
420   }
421
422   /* Clear the packet list. */
423   packet_list_freeze();
424   packet_list_clear();
425   packet_list_thaw();
426
427   cf->f_datalen = 0;
428   nstime_set_zero(&cf->elapsed_time);
429
430   reset_tap_listeners();
431
432   epan_free(cf->epan);
433   cf->epan = NULL;
434
435   /* We have no file open. */
436   cf->state = FILE_CLOSED;
437
438   cf_callback_invoke(cf_cb_file_closed, cf);
439 }
440
441 /*
442  * TRUE if the progress dialog doesn't exist and it looks like we'll
443  * take > 2s to load, FALSE otherwise.
444  */
445 static inline gboolean
446 progress_is_slow(progdlg_t *progdlg, GTimer *prog_timer, gint64 size, gint64 pos)
447 {
448   double elapsed;
449
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. */
454     return TRUE;
455   }
456   return FALSE;
457 }
458
459 static float
460 calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
461 {
462   float progbar_val;
463
464   progbar_val = (gfloat) file_pos / (gfloat) size;
465   if (progbar_val > 1.0) {
466
467     /*  The file probably grew while we were reading it.
468      *  Update file size, and try again.
469      */
470     size = wtap_file_size(cf->provider.wth, NULL);
471
472     if (size >= 0)
473       progbar_val = (gfloat) file_pos / (gfloat) size;
474
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.
479      */
480     if (progbar_val > 1.0f)
481       progbar_val = 1.0f;
482   }
483
484   g_snprintf(status_str, status_size,
485              "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
486              file_pos / 1024, size / 1024);
487
488   return progbar_val;
489 }
490
491 cf_read_status_t
492 cf_read(capture_file *cf, gboolean reloading)
493 {
494   int                  err = 0;
495   gchar               *err_info = NULL;
496   gchar               *name_ptr;
497   progdlg_t           *volatile progbar = NULL;
498   GTimer              *prog_timer = g_timer_new();
499   GTimeVal             start_time;
500   epan_dissect_t       edt;
501   dfilter_t           *dfcode;
502   volatile gboolean    create_proto_tree;
503   guint                tap_flags;
504   gboolean             compiled;
505   volatile gboolean    is_read_aborted = FALSE;
506
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.
510    */
511   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
512   g_assert(!cf->dfilter || (compiled && dfcode));
513
514   /* Get the union of the flags for all tap listeners. */
515   tap_flags = union_of_tap_listener_flags();
516
517   /*
518    * Determine whether we need to create a protocol tree.
519    * We do if:
520    *
521    *    we're going to apply a display filter;
522    *
523    *    one of the tap listeners is going to apply a filter;
524    *
525    *    one of the tap listeners requires a protocol tree;
526    *
527    *    a postdissector wants field values or protocols on
528    *    the first pass.
529    */
530   create_proto_tree =
531     (dfcode != NULL || have_filtering_tap_listeners() ||
532      (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
533
534   reset_tap_listeners();
535
536   name_ptr = g_filename_display_basename(cf->filename);
537
538   if (reloading)
539     cf_callback_invoke(cf_cb_file_reload_started, cf);
540   else
541     cf_callback_invoke(cf_cb_file_read_started, cf);
542
543   /* Record whether the file is compressed.
544      XXX - do we know this at open time? */
545   cf->iscompressed = wtap_iscompressed(cf->provider.wth);
546
547   /* The packet list window will be empty until the file is completly loaded */
548   packet_list_freeze();
549
550   cf->stop_flag = FALSE;
551   g_get_current_time(&start_time);
552
553   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
554
555   TRY {
556     int     count             = 0;
557
558     gint64  size;
559     gint64  file_pos;
560     gint64  data_offset;
561
562     float   progbar_val;
563     gchar   status_str[100];
564
565     column_info *cinfo;
566
567     /* If any tap listeners require the columns, construct them. */
568     cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
569
570     /* Find the size of the file. */
571     size = wtap_file_size(cf->provider.wth, NULL);
572
573     g_timer_start(prog_timer);
574
575     while ((wtap_read(cf->provider.wth, &err, &err_info, &data_offset))) {
576       if (size >= 0) {
577         count++;
578         file_pos = wtap_read_so_far(cf->provider.wth);
579
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));
583           if (reloading)
584             progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
585                 TRUE, &cf->stop_flag, &start_time, progbar_val);
586           else
587             progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
588                 TRUE, &cf->stop_flag, &start_time, progbar_val);
589         }
590
591         /*
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.
597          */
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);
605         }
606       }
607
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;
613         break;
614       }
615       if (cf->stop_flag) {
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
618            packets.
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. */
622         break;
623       }
624       read_packet(cf, dfcode, &edt, cinfo, data_offset);
625     }
626   }
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.");
632 #if 0
633     /* Could we close the current capture and free up memory from that? */
634 #else
635     /* we have to terminate, as we cannot recover from the memory error */
636     exit(1);
637 #endif
638   }
639   ENDTRY;
640
641   /* Free the display name */
642   g_free(name_ptr);
643
644   /* Cleanup and release all dfilter resources */
645   dfilter_free(dfcode);
646
647   epan_dissect_cleanup(&edt);
648
649   /* We're done reading the file; destroy the progress bar if it was created. */
650   if (progbar != NULL)
651     destroy_progress_dlg(progbar);
652   g_timer_destroy(prog_timer);
653
654   /* We're done reading sequentially through the file. */
655   cf->state = FILE_READ_DONE;
656
657   /* Close the sequential I/O side, to free up memory it requires. */
658   wtap_sequential_close(cf->provider.wth);
659
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();
663
664   /* compute the time it took to load the file */
665   compute_elapsed(cf, &start_time);
666
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);
672
673   cf->current_frame = frame_data_sequence_find(cf->provider.frames, cf->first_displayed);
674   cf->current_row = 0;
675
676   packet_list_thaw();
677   if (reloading)
678     cf_callback_invoke(cf_cb_file_reload_finished, cf);
679   else
680     cf_callback_invoke(cf_cb_file_read_finished, cf);
681
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();
686   }
687
688   if (is_read_aborted) {
689     /*
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.
693      */
694     cf_close(cf);
695     return CF_READ_ABORTED;
696   }
697
698   if (cf->stop_flag) {
699     simple_message_box(ESD_TYPE_WARN, NULL,
700                   "The remaining packets in the file were discarded.\n"
701                   "\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;
706   }
707
708   if (err != 0) {
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,
711        if any. */
712     cfile_read_failure_alert_box(NULL, err, err_info);
713     return CF_READ_ERROR;
714   } else
715     return CF_READ_OK;
716 }
717
718 #ifdef HAVE_LIBPCAP
719 cf_read_status_t
720 cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
721 {
722   gchar            *err_info;
723   volatile int      newly_displayed_packets = 0;
724   dfilter_t        *dfcode;
725   epan_dissect_t    edt;
726   gboolean          create_proto_tree;
727   guint             tap_flags;
728   gboolean          compiled;
729
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.
733    */
734   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
735   g_assert(!cf->dfilter || (compiled && dfcode));
736
737   /* Get the union of the flags for all tap listeners. */
738   tap_flags = union_of_tap_listener_flags();
739
740   /*
741    * Determine whether we need to create a protocol tree.
742    * We do if:
743    *
744    *    we're going to apply a display filter;
745    *
746    *    one of the tap listeners is going to apply a filter;
747    *
748    *    one of the tap listeners requires a protocol tree;
749    *
750    *    a postdissector wants field values or protocols on
751    *    the first pass.
752    */
753   create_proto_tree =
754     (dfcode != NULL || have_filtering_tap_listeners() ||
755      (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
756
757   *err = 0;
758
759   packet_list_check_end();
760   /* Don't freeze/thaw the list when doing live capture */
761   /*packet_list_freeze();*/
762
763   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
764
765   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
766
767   TRY {
768     gint64 data_offset = 0;
769     column_info *cinfo;
770
771     /* If any tap listeners require the columns, construct them. */
772     cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
773
774     while (to_read != 0) {
775       wtap_cleareof(cf->provider.wth);
776       if (!wtap_read(cf->provider.wth, err, &err_info, &data_offset)) {
777         break;
778       }
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. */
783         break;
784       }
785       if (read_packet(cf, dfcode, &edt, (column_info *) cinfo, data_offset) != -1) {
786         newly_displayed_packets++;
787       }
788       to_read--;
789     }
790   }
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.");
796 #if 0
797     /* Could we close the current capture and free up memory from that? */
798     return CF_READ_ABORTED;
799 #else
800     /* we have to terminate, as we cannot recover from the memory error */
801     exit(1);
802 #endif
803   }
804   ENDTRY;
805
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);
809
810   /* Cleanup and release all dfilter resources */
811   dfilter_free(dfcode);
812
813   epan_dissect_cleanup(&edt);
814
815   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
816     cf->count, cf->state, *err);*/
817
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.
822    */
823   if (!cf->current_frame)
824     packet_list_select_first_row();
825
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();
830
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
836        and exit. */
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);
844       g_free(err_info);
845     } else {
846       g_warning("Error \"%s\" while reading \"%s\"",
847                 wtap_strerror(*err), cf->filename);
848     }
849     return CF_READ_ERROR;
850   } else
851     return CF_READ_OK;
852 }
853
854 void
855 cf_fake_continue_tail(capture_file *cf) {
856   cf->state = FILE_READ_DONE;
857 }
858
859 cf_read_status_t
860 cf_finish_tail(capture_file *cf, int *err)
861 {
862   gchar     *err_info;
863   gint64     data_offset;
864   dfilter_t *dfcode;
865   column_info *cinfo;
866   epan_dissect_t edt;
867   gboolean   create_proto_tree;
868   guint      tap_flags;
869   gboolean   compiled;
870
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.
874    */
875   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
876   g_assert(!cf->dfilter || (compiled && dfcode));
877
878   /* Get the union of the flags for all tap listeners. */
879   tap_flags = union_of_tap_listener_flags();
880
881   /* If any tap listeners require the columns, construct them. */
882   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
883
884   /*
885    * Determine whether we need to create a protocol tree.
886    * We do if:
887    *
888    *    we're going to apply a display filter;
889    *
890    *    one of the tap listeners is going to apply a filter;
891    *
892    *    one of the tap listeners requires a protocol tree;
893    *
894    *    a postdissector wants field values or protocols on
895    *    the first pass.
896    */
897   create_proto_tree =
898     (dfcode != NULL || have_filtering_tap_listeners() ||
899      (tap_flags & TL_REQUIRES_PROTO_TREE) || postdissectors_want_hfids());
900
901   if (cf->provider.wth == NULL) {
902     cf_close(cf);
903     return CF_READ_ERROR;
904   }
905
906   packet_list_check_end();
907   /* Don't freeze/thaw the list when doing live capture */
908   /*packet_list_freeze();*/
909
910   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
911
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. */
917       break;
918     }
919     read_packet(cf, dfcode, &edt, cinfo, data_offset);
920   }
921
922   /* Cleanup and release all dfilter resources */
923   dfilter_free(dfcode);
924
925   epan_dissect_cleanup(&edt);
926
927   /* Don't freeze/thaw the list when doing live capture */
928   /*packet_list_thaw();*/
929
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. */
936     cf_close(cf);
937     return CF_READ_ABORTED;
938   }
939
940   if (auto_scroll_live && cf->count != 0)
941     packet_list_moveto_end();
942
943   /* We're done reading sequentially through the file. */
944   cf->state = FILE_READ_DONE;
945
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);
949
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();
953
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);
957
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);
961
962   if (*err != 0) {
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);
968       g_free(err_info);
969     } else {
970       g_warning("Error \"%s\" while reading \"%s\"",
971                 wtap_strerror(*err), cf->filename);
972     }
973     return CF_READ_ERROR;
974   } else {
975     return CF_READ_OK;
976   }
977 }
978 #endif /* HAVE_LIBPCAP */
979
980 gchar *
981 cf_get_display_name(capture_file *cf)
982 {
983   gchar *displayname;
984
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. */
988     if (cf->filename) {
989       displayname = g_filename_display_basename(cf->filename);
990     } else {
991       displayname=g_strdup("(No file)");
992     }
993   } else {
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. */
997     if (cf->source) {
998       displayname = g_strdup(cf->source);
999     } else {
1000       displayname = g_strdup("(Untitled)");
1001     }
1002   }
1003   return displayname;
1004 }
1005
1006 void cf_set_tempfile_source(capture_file *cf, gchar *source) {
1007   if (cf->source) {
1008     g_free(cf->source);
1009   }
1010
1011   if (source) {
1012     cf->source = g_strdup(source);
1013   } else {
1014     cf->source = g_strdup("");
1015   }
1016 }
1017
1018 const gchar *cf_get_tempfile_source(capture_file *cf) {
1019   if (!cf->source) {
1020     return "";
1021   }
1022
1023   return cf->source;
1024 }
1025
1026 /* XXX - use a macro instead? */
1027 int
1028 cf_get_packet_count(capture_file *cf)
1029 {
1030   return cf->count;
1031 }
1032
1033 /* XXX - use a macro instead? */
1034 gboolean
1035 cf_is_tempfile(capture_file *cf)
1036 {
1037   return cf->is_tempfile;
1038 }
1039
1040 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
1041 {
1042   cf->is_tempfile = is_tempfile;
1043 }
1044
1045
1046 /* XXX - use a macro instead? */
1047 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
1048 {
1049   cf->drops_known = drops_known;
1050 }
1051
1052 /* XXX - use a macro instead? */
1053 void cf_set_drops(capture_file *cf, guint32 drops)
1054 {
1055   cf->drops = drops;
1056 }
1057
1058 /* XXX - use a macro instead? */
1059 gboolean cf_get_drops_known(capture_file *cf)
1060 {
1061   return cf->drops_known;
1062 }
1063
1064 /* XXX - use a macro instead? */
1065 guint32 cf_get_drops(capture_file *cf)
1066 {
1067   return cf->drops;
1068 }
1069
1070 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1071 {
1072   cf->rfcode = rfcode;
1073 }
1074
1075 static int
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)
1079 {
1080   gint            row               = -1;
1081
1082   frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1083                                 &cf->provider.ref, cf->provider.prev_dis);
1084   cf->provider.prev_cap = fdata;
1085
1086   if (dfcode != NULL) {
1087       epan_dissect_prime_with_dfilter(edt, dfcode);
1088   }
1089 #if 0
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;
1096   }
1097 #endif
1098
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);
1103   }
1104
1105   /* Dissect the frame. */
1106   epan_dissect_run_with_taps(edt, cf->cd_t, phdr,
1107                              frame_tvbuff_new(&cf->provider, fdata, buf),
1108                              fdata, cinfo);
1109
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;
1113
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
1117        * as depended upon.
1118        */
1119       g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->provider.frames);
1120     }
1121   } else
1122     fdata->flags.passed_dfilter = 1;
1123
1124   if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1125     cf->displayed_count++;
1126
1127   if (add_to_packet_list) {
1128     /* We fill the needed columns from new_packet_list */
1129       row = packet_list_append(cinfo, fdata);
1130   }
1131
1132   if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1133   {
1134     frame_data_set_after_dissect(fdata, &cf->cum_bytes);
1135     cf->provider.prev_dis = fdata;
1136
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;
1140
1141     /* This is the last frame we've seen so far. */
1142     cf->last_displayed = fdata->num;
1143   }
1144
1145   epan_dissect_reset(edt);
1146   return row;
1147 }
1148
1149 /* read in a new packet */
1150 /* returns the row of the new packet in the packet list or -1 if not displayed */
1151 static int
1152 read_packet(capture_file *cf, dfilter_t *dfcode, epan_dissect_t *edt,
1153             column_info *cinfo, gint64 offset)
1154 {
1155   struct wtap_pkthdr *phdr = wtap_phdr(cf->provider.wth);
1156   const guint8 *buf = wtap_buf_ptr(cf->provider.wth);
1157   frame_data    fdlocal;
1158   guint32       framenum;
1159   frame_data   *fdata;
1160   gboolean      passed = TRUE;
1161   int           row = -1;
1162
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
1168      in a file. */
1169   cf_add_encapsulation_type(cf, phdr->pkt_encap);
1170
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;
1174
1175   frame_data_init(&fdlocal, framenum, phdr, offset, cf->cum_bytes);
1176
1177   if (cf->rfcode) {
1178     epan_dissect_t rf_edt;
1179
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),
1184                      &fdlocal, NULL);
1185     passed = dfilter_apply_edt(cf->rfcode, &rf_edt);
1186     epan_dissect_cleanup(&rf_edt);
1187   }
1188
1189   if (passed) {
1190     /* This does a shallow copy of fdlocal, which is good enough. */
1191     fdata = frame_data_sequence_add(cf->provider.frames, &fdlocal);
1192
1193     cf->count++;
1194     if (phdr->opt_comment != NULL)
1195       cf->packet_comment_count++;
1196     cf->f_datalen = offset + fdlocal.cap_len;
1197
1198     if (!cf->redissecting) {
1199       row = add_packet_to_packet_list(fdata, cf, edt, dfcode,
1200                                       cinfo, phdr, buf, TRUE);
1201     }
1202   }
1203
1204   return row;
1205 }
1206
1207
1208 typedef struct _callback_data_t {
1209   gpointer         pd_window;
1210   gint64           f_len;
1211   GTimeVal         start_time;
1212   progdlg_t       *progbar;
1213   GTimer          *prog_timer;
1214   gboolean         stop_flag;
1215 } callback_data_t;
1216
1217
1218 static gboolean
1219 merge_callback(merge_event event, int num _U_,
1220                const merge_in_file_t in_files[], const guint in_file_count,
1221                void *data)
1222 {
1223   guint i;
1224   callback_data_t *cb_data = (callback_data_t*) data;
1225
1226   g_assert(cb_data != NULL);
1227
1228   switch (event) {
1229
1230     case MERGE_EVENT_INPUT_FILES_OPENED:
1231       /* do nothing */
1232       break;
1233
1234     case MERGE_EVENT_FRAME_TYPE_SELECTED:
1235       /* do nothing */
1236       break;
1237
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;
1242
1243       cb_data->prog_timer = g_timer_new();
1244       g_timer_start(cb_data->prog_timer);
1245
1246       g_get_current_time(&cb_data->start_time);
1247       break;
1248
1249     case MERGE_EVENT_PACKET_WAS_READ:
1250       {
1251         gint64 data_offset = 0;
1252
1253         /* Get the sum of the data offsets in all of the files. */
1254         data_offset = 0;
1255         for (i = 0; i < in_file_count; i++)
1256           data_offset += in_files[i].data_offset;
1257
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);
1266         }
1267
1268         /*
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.
1274          */
1275         if (g_timer_elapsed(cb_data->prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
1276             float  progbar_val;
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);
1281
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
1286                  value at 1.0. */
1287               progbar_val = 1.0f;
1288             }
1289
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);
1296             }
1297             g_timer_start(cb_data->prog_timer);
1298         }
1299       }
1300       break;
1301
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);
1307       break;
1308   }
1309
1310   return cb_data->stop_flag;
1311 }
1312
1313
1314
1315 cf_status_t
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)
1319 {
1320   int                        err      = 0;
1321   gchar                     *err_info = NULL;
1322   guint                      err_fileno;
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);
1327
1328   /* prepare our callback routine */
1329   cb_data->pd_window = pd_window;
1330   cb.callback_func = merge_callback;
1331   cb.data = cb_data;
1332
1333   cf_callback_invoke(cf_cb_file_merge_started, NULL);
1334
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);
1342
1343   g_free(cb.data);
1344
1345   switch (status) {
1346     case MERGE_OK:
1347       break;
1348
1349     case MERGE_USER_ABORTED:
1350       /* this isn't really an error, though we will return CF_ERROR later */
1351       break;
1352
1353     case MERGE_ERR_CANT_OPEN_INFILE:
1354       cfile_open_failure_alert_box(in_filenames[err_fileno], err, err_info);
1355       break;
1356
1357     case MERGE_ERR_CANT_OPEN_OUTFILE:
1358       cfile_dump_open_failure_alert_box(*out_filenamep, err, file_type);
1359       break;
1360
1361     case MERGE_ERR_CANT_READ_INFILE:
1362       cfile_read_failure_alert_box(in_filenames[err_fileno], err, err_info);
1363       break;
1364
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]);
1368       break;
1369
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);
1374        break;
1375
1376     case MERGE_ERR_CANT_CLOSE_OUTFILE:
1377         cfile_close_failure_alert_box(*out_filenamep, err);
1378         break;
1379
1380     default:
1381       simple_error_message_box("Unknown merge_files error %d", status);
1382       break;
1383   }
1384
1385   cf_callback_invoke(cf_cb_file_merge_finished, NULL);
1386
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
1390        have to. */
1391     return CF_ERROR;
1392   } else
1393     return CF_OK;
1394 }
1395
1396 cf_status_t
1397 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1398 {
1399   const char *filter_new = dftext ? dftext : "";
1400   const char *filter_old = cf->dfilter ? cf->dfilter : "";
1401   dfilter_t  *dfcode;
1402   gchar      *err_msg;
1403   GTimeVal    start_time;
1404
1405   /* if new filter equals old one, do nothing unless told to do so */
1406   if (!force && strcmp(filter_new, filter_old) == 0) {
1407     return CF_OK;
1408   }
1409
1410   dfcode=NULL;
1411
1412   if (dftext == NULL) {
1413     /* The new filter is an empty filter (i.e., display all packets).
1414      * so leave dfcode==NULL
1415      */
1416   } else {
1417     /*
1418      * We have a filter; make a copy of it (as we'll be saving it),
1419      * and try to compile it.
1420      */
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",
1427           dftext, err_msg);
1428       g_free(err_msg);
1429       g_free(dftext);
1430       return CF_ERROR;
1431     }
1432
1433     /* Was it empty? */
1434     if (dfcode == NULL) {
1435       /* Yes - free the filter text, and set it to null. */
1436       g_free(dftext);
1437       dftext = NULL;
1438     }
1439   }
1440
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);
1445
1446
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);
1452     } else {
1453       rescan_packets(cf, "Filtering", dftext, FALSE);
1454     }
1455   }
1456
1457   /* Cleanup and release all dfilter resources */
1458   dfilter_free(dfcode);
1459
1460   return CF_OK;
1461 }
1462
1463 void
1464 cf_reftime_packets(capture_file *cf)
1465 {
1466   ref_time_packets(cf);
1467 }
1468
1469 void
1470 cf_redissect_packets(capture_file *cf)
1471 {
1472   if (cf->state != FILE_CLOSED) {
1473     rescan_packets(cf, "Reprocessing", "all packets", TRUE);
1474   }
1475 }
1476
1477 gboolean
1478 cf_read_record_r(capture_file *cf, const frame_data *fdata,
1479                  struct wtap_pkthdr *phdr, Buffer *buf)
1480 {
1481   int    err;
1482   gchar *err_info;
1483
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);
1486     return FALSE;
1487   }
1488   return TRUE;
1489 }
1490
1491 gboolean
1492 cf_read_record(capture_file *cf, frame_data *fdata)
1493 {
1494   return cf_read_record_r(cf, fdata, &cf->phdr, &cf->buf);
1495 }
1496
1497 /* Rescan the list of packets, reconstructing the CList.
1498
1499    "action" describes why we're doing this; it's used in the progress
1500    dialog box.
1501
1502    "action_item" describes what we're doing; it's used in the progress
1503    dialog box.
1504
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). */
1509 static void
1510 rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
1511 {
1512   /* Rescan packets new packet list */
1513   guint32     framenum;
1514   frame_data *fdata;
1515   progdlg_t  *progbar = NULL;
1516   GTimer     *prog_timer = g_timer_new();
1517   int         count;
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;
1521   float       progbar_val;
1522   GTimeVal    start_time;
1523   gchar       status_str[100];
1524   epan_dissect_t  edt;
1525   dfilter_t  *dfcode;
1526   column_info *cinfo;
1527   gboolean    create_proto_tree;
1528   guint       tap_flags;
1529   gboolean    add_to_packet_list = FALSE;
1530   gboolean    compiled;
1531   guint32     frames_count;
1532
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.
1536    */
1537   compiled = dfilter_compile(cf->dfilter, &dfcode, NULL);
1538   g_assert(!cf->dfilter || (compiled && dfcode));
1539
1540   /* Get the union of the flags for all tap listeners. */
1541   tap_flags = union_of_tap_listener_flags();
1542
1543   /* If any tap listeners require the columns, construct them. */
1544   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
1545
1546   /*
1547    * Determine whether we need to create a protocol tree.
1548    * We do if:
1549    *
1550    *    we're going to apply a display filter;
1551    *
1552    *    one of the tap listeners is going to apply a filter;
1553    *
1554    *    one of the tap listeners requires a protocol tree;
1555    *
1556    *    we're redissecting and a postdissector wants field
1557    *    values or protocols on the first pass.
1558    */
1559   create_proto_tree =
1560     (dfcode != NULL || have_filtering_tap_listeners() ||
1561      (tap_flags & TL_REQUIRES_PROTO_TREE) ||
1562      (redissect && postdissectors_want_hfids()));
1563
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
1568      start? */
1569   selected_frame = cf->current_frame;
1570
1571   /* Mark frame num as not found */
1572   selected_frame_num = -1;
1573
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();
1577
1578   if (redissect) {
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. */
1583
1584     /* We might receive new packets while redissecting, and we don't
1585        want to dissect those before their time. */
1586     cf->redissecting = TRUE;
1587
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);
1595     }
1596     cf->epan = ws_epan_new(cf);
1597     cf->cinfo.epan = cf->epan;
1598
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;
1603     }
1604
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;
1609   }
1610
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;
1614
1615   /* We currently don't display any packets */
1616   cf->displayed_count = 0;
1617
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;
1624   cf->cum_bytes = 0;
1625
1626   cf_callback_invoke(cf_cb_file_rescan_started, cf);
1627
1628   g_timer_start(prog_timer);
1629   /* Count of packets at which we've looked. */
1630   count = 0;
1631   /* Progress so far. */
1632   progbar_val = 0.0f;
1633
1634   cf->stop_flag = FALSE;
1635   g_get_current_time(&start_time);
1636
1637   /* no previous row yet */
1638   prev_frame_num = -1;
1639   prev_frame = NULL;
1640
1641   preceding_frame_num = -1;
1642   preceding_frame = NULL;
1643   following_frame_num = -1;
1644   following_frame = NULL;
1645
1646   selected_frame_seen = FALSE;
1647
1648   frames_count = cf->count;
1649
1650   epan_dissect_init(&edt, cf->epan, create_proto_tree, FALSE);
1651
1652   for (framenum = 1; framenum <= frames_count; framenum++) {
1653     fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1654
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,
1662                                             &cf->stop_flag,
1663                                             &start_time,
1664                                             progbar_val);
1665
1666     /*
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.
1671      */
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
1675        */
1676       g_assert(cf->count > 0);
1677       progbar_val = (gfloat) count / frames_count;
1678
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);
1683       }
1684
1685       g_timer_start(prog_timer);
1686     }
1687
1688     if (cf->stop_flag) {
1689       /* Well, the user decided to abort the filtering.  Just stop.
1690
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.
1698
1699          I'm not sure what Network Monitor does, but it doesn't appear
1700          to give you an unfiltered display if you cancel. */
1701       break;
1702     }
1703
1704     count++;
1705
1706     if (redissect) {
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;
1713     }
1714
1715     /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1716     fdata->flags.dependent_of_displayed = 0;
1717
1718     if (!cf_read_record(cf, fdata))
1719       break; /* error reading the frame */
1720
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;
1727     }
1728
1729     add_packet_to_packet_list(fdata, cf, &edt, dfcode,
1730                                     cinfo, &cf->phdr,
1731                                     ws_buffer_start_ptr(&cf->buf),
1732                                     add_to_packet_list);
1733
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
1737        frame. */
1738     if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1739       following_frame_num = fdata->num;
1740       following_frame = fdata;
1741     }
1742     if (fdata == selected_frame) {
1743       selected_frame_seen = TRUE;
1744       if (fdata->flags.passed_dfilter)
1745           selected_frame_num = fdata->num;
1746     }
1747
1748     /* Remember this frame - it'll be the previous frame
1749        on the next pass through the loop. */
1750     prev_frame_num = fdata->num;
1751     prev_frame = fdata;
1752   }
1753
1754   epan_dissect_cleanup(&edt);
1755
1756   /* We are done redissecting the packet list. */
1757   cf->redissecting = FALSE;
1758
1759   if (redissect) {
1760       frames_count = cf->count;
1761     /* Clear out what remains of the visited flags and per-frame data
1762        pointers.
1763
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);
1773     }
1774   }
1775
1776   /* We're done filtering the packets; destroy the progress bar if it
1777      was created. */
1778   if (progbar != NULL)
1779     destroy_progress_dlg(progbar);
1780   g_timer_destroy(prog_timer);
1781
1782   /* Unfreeze the packet list. */
1783   if (!add_to_packet_list)
1784     packet_list_recreate_visible_rows();
1785
1786   /* Compute the time it took to filter the file */
1787   compute_elapsed(cf, &start_time);
1788
1789   packet_list_thaw();
1790
1791   cf_callback_invoke(cf_cb_file_rescan_finished, cf);
1792
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;
1799     } else {
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
1811            frame. */
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
1817            frame. */
1818         selected_frame_num = following_frame_num;
1819         selected_frame = following_frame;
1820       } else {
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;
1825       }
1826     }
1827   }
1828
1829   if (selected_frame_num == -1) {
1830     /* There are no frames displayed at all. */
1831     cf_unselect_packet(cf);
1832   } else {
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();
1840     }else{
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.");
1848       }
1849     }
1850   }
1851
1852   /* Cleanup and release all dfilter resources */
1853   dfilter_free(dfcode);
1854 }
1855
1856
1857 /*
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?
1861  */
1862 static void
1863 ref_time_packets(capture_file *cf)
1864 {
1865   guint32     framenum;
1866   frame_data *fdata;
1867   nstime_t rel_ts;
1868
1869   cf->provider.ref = NULL;
1870   cf->provider.prev_dis = NULL;
1871   cf->cum_bytes = 0;
1872
1873   for (framenum = 1; framenum <= cf->count; framenum++) {
1874     fdata = frame_data_sequence_find(cf->provider.frames, framenum);
1875
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;
1878
1879     /*
1880      *Timestamps
1881      */
1882
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;
1892
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
1896      packet. */
1897     if (cf->provider.prev_dis == NULL) {
1898         cf->provider.prev_dis = fdata;
1899     }
1900
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);
1904
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;
1911     }
1912
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;
1918     }
1919
1920     /*
1921      * Byte counts
1922      */
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;
1931         } else {
1932             /* increase cum_bytes with this packets length */
1933             cf->cum_bytes += fdata->pkt_len;
1934         }
1935     }
1936   }
1937 }
1938
1939 typedef enum {
1940   PSP_FINISHED,
1941   PSP_STOPPED,
1942   PSP_FAILED
1943 } psp_return_t;
1944
1945 static psp_return_t
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)
1952 {
1953   guint32          framenum;
1954   frame_data      *fdata;
1955   Buffer           buf;
1956   psp_return_t     ret     = PSP_FINISHED;
1957
1958   progdlg_t       *progbar = NULL;
1959   GTimer          *prog_timer = g_timer_new();
1960   int              progbar_count;
1961   float            progbar_val;
1962   GTimeVal         progbar_start_time;
1963   gchar            progbar_status_str[100];
1964   range_process_e  process_this;
1965   struct wtap_pkthdr phdr;
1966
1967   wtap_phdr_init(&phdr);
1968   ws_buffer_init(&buf, 1500);
1969
1970   g_timer_start(prog_timer);
1971   /* Count of packets at which we've looked. */
1972   progbar_count = 0;
1973   /* Progress so far. */
1974   progbar_val = 0.0f;
1975
1976   cf->stop_flag = FALSE;
1977   g_get_current_time(&progbar_start_time);
1978
1979   if (range != NULL)
1980     packet_range_process_init(range);
1981
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);
1986
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,
1994                                             terminate_is_stop,
1995                                             &cf->stop_flag,
1996                                             &progbar_start_time,
1997                                             progbar_val);
1998
1999     /*
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.
2004      */
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
2008        */
2009       g_assert(cf->count > 0);
2010       progbar_val = (gfloat) progbar_count / cf->count;
2011
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);
2015
2016       g_timer_start(prog_timer);
2017     }
2018
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. */
2023       ret = PSP_STOPPED;
2024       break;
2025     }
2026
2027     progbar_count++;
2028
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 */
2034         continue;
2035       } else if (process_this == range_processing_finished) {
2036         /* all interesting packets processed, stop the loop */
2037         break;
2038       }
2039     }
2040
2041     /* Get the packet */
2042     if (!cf_read_record_r(cf, fdata, &phdr, &buf)) {
2043       /* Attempt to get the packet failed. */
2044       ret = PSP_FAILED;
2045       break;
2046     }
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. */
2050       ret = PSP_FAILED;
2051       break;
2052     }
2053   }
2054
2055   /* We're done printing the packets; destroy the progress bar if
2056      it was created. */
2057   if (progbar != NULL)
2058     destroy_progress_dlg(progbar);
2059   g_timer_destroy(prog_timer);
2060
2061   wtap_phdr_cleanup(&phdr);
2062   ws_buffer_free(&buf);
2063
2064   return ret;
2065 }
2066
2067 typedef struct {
2068   epan_dissect_t edt;
2069   column_info *cinfo;
2070 } retap_callback_args_t;
2071
2072 static gboolean
2073 retap_packet(capture_file *cf, frame_data *fdata,
2074              struct wtap_pkthdr *phdr, const guint8 *pd,
2075              void *argsp)
2076 {
2077   retap_callback_args_t *args = (retap_callback_args_t *)argsp;
2078
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);
2083
2084   return TRUE;
2085 }
2086
2087 cf_read_status_t
2088 cf_retap_packets(capture_file *cf)
2089 {
2090   packet_range_t        range;
2091   retap_callback_args_t callback_args;
2092   gboolean              create_proto_tree;
2093   guint                 tap_flags;
2094   psp_return_t          ret;
2095
2096   /* Presumably the user closed the capture file. */
2097   if (cf == NULL) {
2098     return CF_READ_ABORTED;
2099   }
2100
2101   cf_callback_invoke(cf_cb_file_retap_started, cf);
2102
2103   /* Get the union of the flags for all tap listeners. */
2104   tap_flags = union_of_tap_listener_flags();
2105
2106   /* If any tap listeners require the columns, construct them. */
2107   callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
2108
2109   /*
2110    * Determine whether we need to create a protocol tree.
2111    * We do if:
2112    *
2113    *    one of the tap listeners is going to apply a filter;
2114    *
2115    *    one of the tap listeners requires a protocol tree.
2116    */
2117   create_proto_tree =
2118     (have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
2119
2120   /* Reset the tap listeners. */
2121   reset_tap_listeners();
2122
2123   epan_dissect_init(&callback_args.edt, cf->epan, create_proto_tree, FALSE);
2124
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);
2129
2130   ret = process_specified_records(cf, &range, "Recalculating statistics on",
2131                                   "all packets", TRUE, retap_packet,
2132                                   &callback_args, TRUE);
2133
2134   epan_dissect_cleanup(&callback_args.edt);
2135
2136   cf_callback_invoke(cf_cb_file_retap_finished, cf);
2137
2138   switch (ret) {
2139   case PSP_FINISHED:
2140     /* Completed successfully. */
2141     return CF_READ_OK;
2142
2143   case PSP_STOPPED:
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;
2147
2148   case PSP_FAILED:
2149     /* Error while retapping. */
2150     return CF_READ_ERROR;
2151   }
2152
2153   g_assert_not_reached();
2154   return CF_READ_OK;
2155 }
2156
2157 typedef struct {
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;
2164   char         *line_buf;
2165   int           line_buf_len;
2166   gint         *col_widths;
2167   int           num_visible_cols;
2168   gint         *visible_cols;
2169   epan_dissect_t edt;
2170 } print_callback_args_t;
2171
2172 static gboolean
2173 print_packet(capture_file *cf, frame_data *fdata,
2174              struct wtap_pkthdr *phdr, const guint8 *pd,
2175              void *argsp)
2176 {
2177   print_callback_args_t *args = (print_callback_args_t *)argsp;
2178   int             i;
2179   char           *cp;
2180   int             line_len;
2181   int             column_len;
2182   int             cp_off;
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;
2186
2187   /* Fill in the column information if we're printing the summary
2188      information. */
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),
2193                      fdata, &cf->cinfo);
2194     epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2195   } else
2196     epan_dissect_run(&args->edt, cf->cd_t, phdr,
2197                      frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2198
2199   if (args->print_formfeed) {
2200     if (!new_page(args->print_args->stream))
2201       goto fail;
2202   } else {
2203       if (args->print_separator) {
2204         if (!print_line(args->print_args->stream, 0, ""))
2205           goto fail;
2206       }
2207   }
2208
2209   /*
2210    * We generate bookmarks, if the output format supports them.
2211    * The name is "__frameN__".
2212    */
2213   g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2214
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))
2220         goto fail;
2221       args->print_header_line = FALSE;  /* we might not need to print any more */
2222     }
2223     cp = &args->line_buf[0];
2224     line_len = 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];
2231
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;
2240       }
2241
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);
2245       else
2246         g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], col_item->col_data);
2247       cp += column_len;
2248       if (i != args->num_visible_cols - 1)
2249         *cp++ = ' ';
2250     }
2251     *cp = '\0';
2252
2253     /*
2254      * Generate a bookmark, using the summary line as the title.
2255      */
2256     if (!print_bookmark(args->print_args->stream, bookmark_name,
2257                         args->line_buf))
2258       goto fail;
2259
2260     if (!print_line(args->print_args->stream, 0, args->line_buf))
2261       goto fail;
2262   } else {
2263     /*
2264      * Generate a bookmark, using "Frame N" as the title, as we're not
2265      * printing the summary line.
2266      */
2267     g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2268     if (!print_bookmark(args->print_args->stream, bookmark_name,
2269                         bookmark_title))
2270       goto fail;
2271   } /* if (print_summary) */
2272
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, ""))
2277         goto fail;
2278     }
2279
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))
2284       goto fail;
2285
2286     /* Print a blank line if we print anything after this (aka more than one packet). */
2287     args->print_separator = TRUE;
2288
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;
2292   }
2293
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, ""))
2297         goto fail;
2298     }
2299     /* Print the full packet data as hex. */
2300     if (!print_hex_data(args->print_args->stream, &args->edt))
2301       goto fail;
2302
2303     /* Print a blank line if we print anything after this (aka more than one packet). */
2304     args->print_separator = TRUE;
2305
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) */
2310
2311   epan_dissect_reset(&args->edt);
2312
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;
2316   }
2317
2318   return TRUE;
2319
2320 fail:
2321   epan_dissect_reset(&args->edt);
2322   return FALSE;
2323 }
2324
2325 cf_print_status_t
2326 cf_print_packets(capture_file *cf, print_args_t *print_args,
2327                  gboolean show_progress_bar)
2328 {
2329   print_callback_args_t callback_args;
2330   gint          data_width;
2331   char         *cp;
2332   int           i, cp_off, column_len, line_len;
2333   int           num_visible_col = 0, last_visible_col = 0, visible_col_count;
2334   psp_return_t  ret;
2335   GList        *clp;
2336   fmt_data     *cfmt;
2337   gboolean      proto_tree_needed;
2338
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;
2350
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;
2354   }
2355
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);
2360
2361     /* Find the number of visible columns and the last visible column */
2362     for (i = 0; i < prefs.num_cols; i++) {
2363
2364         clp = g_list_nth(prefs.col_list, i);
2365         if (clp == NULL) /* Sanity check, Invalid column requested */
2366             continue;
2367
2368         cfmt = (fmt_data *) clp->data;
2369         if (cfmt->visible) {
2370             num_visible_col++;
2371             last_visible_col = i;
2372         }
2373     }
2374
2375     /* if num_visible_col is 0, we are done */
2376     if (num_visible_col == 0) {
2377       g_free(callback_args.header_line_buf);
2378       return CF_PRINT_OK;
2379     }
2380
2381     /* Find the widths for each of the columns - maximum of the
2382        width of the title and the width of the data - and construct
2383        a buffer with a line containing the column titles. */
2384     callback_args.num_visible_cols = num_visible_col;
2385     callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2386     callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2387     cp = &callback_args.header_line_buf[0];
2388     line_len = 0;
2389     visible_col_count = 0;
2390     for (i = 0; i < cf->cinfo.num_cols; i++) {
2391
2392       clp = g_list_nth(prefs.col_list, i);
2393       if (clp == NULL) /* Sanity check, Invalid column requested */
2394           continue;
2395
2396       cfmt = (fmt_data *) clp->data;
2397       if (cfmt->visible == FALSE)
2398           continue;
2399
2400       /* Save the order of visible columns */
2401       callback_args.visible_cols[visible_col_count] = i;
2402
2403       /* Don't pad the last column. */
2404       if (i == last_visible_col)
2405         callback_args.col_widths[visible_col_count] = 0;
2406       else {
2407         callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.columns[i].col_title);
2408         data_width = get_column_char_width(get_column_format(i));
2409         if (data_width > callback_args.col_widths[visible_col_count])
2410           callback_args.col_widths[visible_col_count] = data_width;
2411       }
2412
2413       /* Find the length of the string for this column. */
2414       column_len = (int) strlen(cf->cinfo.columns[i].col_title);
2415       if (callback_args.col_widths[visible_col_count] > column_len)
2416         column_len = callback_args.col_widths[visible_col_count];
2417
2418       /* Make sure there's room in the line buffer for the column; if not,
2419          double its length. */
2420       line_len += column_len + 1;   /* "+1" for space */
2421       if (line_len > callback_args.header_line_buf_len) {
2422         cp_off = (int) (cp - callback_args.header_line_buf);
2423         callback_args.header_line_buf_len = 2 * line_len;
2424         callback_args.header_line_buf = (char *)g_realloc(callback_args.header_line_buf,
2425                                                   callback_args.header_line_buf_len + 1);
2426         cp = callback_args.header_line_buf + cp_off;
2427       }
2428
2429       /* Right-justify the packet number column. */
2430 /*      if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2431         g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2432       else*/
2433       g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.columns[i].col_title);
2434       cp += column_len;
2435       if (i != cf->cinfo.num_cols - 1)
2436         *cp++ = ' ';
2437
2438       visible_col_count++;
2439     }
2440     *cp = '\0';
2441
2442     /* Now start out the main line buffer with the same length as the
2443        header line buffer. */
2444     callback_args.line_buf_len = callback_args.header_line_buf_len;
2445     callback_args.line_buf = (char *)g_malloc(callback_args.line_buf_len + 1);
2446   } /* if (print_summary) */
2447
2448   /* Create the protocol tree, and make it visible, if we're printing
2449      the dissection or the hex data.
2450      XXX - do we need it if we're just printing the hex data? */
2451   proto_tree_needed =
2452       callback_args.print_args->print_dissections != print_dissections_none ||
2453       callback_args.print_args->print_hex ||
2454       have_custom_cols(&cf->cinfo) || have_field_extractors();
2455   epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2456
2457   /* Iterate through the list of packets, printing the packets we were
2458      told to print. */
2459   ret = process_specified_records(cf, &print_args->range, "Printing",
2460                                   "selected packets", TRUE, print_packet,
2461                                   &callback_args, show_progress_bar);
2462   epan_dissect_cleanup(&callback_args.edt);
2463   g_free(callback_args.header_line_buf);
2464   g_free(callback_args.line_buf);
2465   g_free(callback_args.col_widths);
2466   g_free(callback_args.visible_cols);
2467
2468   switch (ret) {
2469
2470   case PSP_FINISHED:
2471     /* Completed successfully. */
2472     break;
2473
2474   case PSP_STOPPED:
2475     /* Well, the user decided to abort the printing.
2476
2477        XXX - note that what got generated before they did that
2478        will get printed if we're piping to a print program; we'd
2479        have to write to a file and then hand that to the print
2480        program to make it actually not print anything. */
2481     break;
2482
2483   case PSP_FAILED:
2484     /* Error while printing.
2485
2486        XXX - note that what got generated before they did that
2487        will get printed if we're piping to a print program; we'd
2488        have to write to a file and then hand that to the print
2489        program to make it actually not print anything. */
2490     destroy_print_stream(print_args->stream);
2491     return CF_PRINT_WRITE_ERROR;
2492   }
2493
2494   if (!print_finale(print_args->stream)) {
2495     destroy_print_stream(print_args->stream);
2496     return CF_PRINT_WRITE_ERROR;
2497   }
2498
2499   if (!destroy_print_stream(print_args->stream))
2500     return CF_PRINT_WRITE_ERROR;
2501
2502   return CF_PRINT_OK;
2503 }
2504
2505 typedef struct {
2506   FILE *fh;
2507   epan_dissect_t edt;
2508   print_args_t *print_args;
2509 } write_packet_callback_args_t;
2510
2511 static gboolean
2512 write_pdml_packet(capture_file *cf, frame_data *fdata,
2513                   struct wtap_pkthdr *phdr, const guint8 *pd,
2514           void *argsp)
2515 {
2516   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2517
2518   /* Create the protocol tree, but don't fill in the column information. */
2519   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2520                    frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2521
2522   /* Write out the information in that tree. */
2523   write_pdml_proto_tree(NULL, NULL, PF_NONE, &args->edt, &cf->cinfo, args->fh, FALSE);
2524
2525   epan_dissect_reset(&args->edt);
2526
2527   return !ferror(args->fh);
2528 }
2529
2530 cf_print_status_t
2531 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2532 {
2533   write_packet_callback_args_t callback_args;
2534   FILE         *fh;
2535   psp_return_t  ret;
2536
2537   fh = ws_fopen(print_args->file, "w");
2538   if (fh == NULL)
2539     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2540
2541   write_pdml_preamble(fh, cf->filename);
2542   if (ferror(fh)) {
2543     fclose(fh);
2544     return CF_PRINT_WRITE_ERROR;
2545   }
2546
2547   callback_args.fh = fh;
2548   callback_args.print_args = print_args;
2549   epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2550
2551   /* Iterate through the list of packets, printing the packets we were
2552      told to print. */
2553   ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2554                                   "selected packets", TRUE,
2555                                   write_pdml_packet, &callback_args, TRUE);
2556
2557   epan_dissect_cleanup(&callback_args.edt);
2558
2559   switch (ret) {
2560
2561   case PSP_FINISHED:
2562     /* Completed successfully. */
2563     break;
2564
2565   case PSP_STOPPED:
2566     /* Well, the user decided to abort the printing. */
2567     break;
2568
2569   case PSP_FAILED:
2570     /* Error while printing. */
2571     fclose(fh);
2572     return CF_PRINT_WRITE_ERROR;
2573   }
2574
2575   write_pdml_finale(fh);
2576   if (ferror(fh)) {
2577     fclose(fh);
2578     return CF_PRINT_WRITE_ERROR;
2579   }
2580
2581   /* XXX - check for an error */
2582   fclose(fh);
2583
2584   return CF_PRINT_OK;
2585 }
2586
2587 static gboolean
2588 write_psml_packet(capture_file *cf, frame_data *fdata,
2589                   struct wtap_pkthdr *phdr, const guint8 *pd,
2590           void *argsp)
2591 {
2592   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2593
2594   /* Fill in the column information */
2595   col_custom_prime_edt(&args->edt, &cf->cinfo);
2596   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2597                    frame_tvbuff_new(&cf->provider, fdata, pd),
2598                    fdata, &cf->cinfo);
2599   epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2600
2601   /* Write out the column information. */
2602   write_psml_columns(&args->edt, args->fh, FALSE);
2603
2604   epan_dissect_reset(&args->edt);
2605
2606   return !ferror(args->fh);
2607 }
2608
2609 cf_print_status_t
2610 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2611 {
2612   write_packet_callback_args_t callback_args;
2613   FILE         *fh;
2614   psp_return_t  ret;
2615
2616   gboolean proto_tree_needed;
2617
2618   fh = ws_fopen(print_args->file, "w");
2619   if (fh == NULL)
2620     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2621
2622   write_psml_preamble(&cf->cinfo, fh);
2623   if (ferror(fh)) {
2624     fclose(fh);
2625     return CF_PRINT_WRITE_ERROR;
2626   }
2627
2628   callback_args.fh = fh;
2629   callback_args.print_args = print_args;
2630
2631   /* Fill in the column information, only create the protocol tree
2632      if having custom columns or field extractors. */
2633   proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2634   epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2635
2636   /* Iterate through the list of packets, printing the packets we were
2637      told to print. */
2638   ret = process_specified_records(cf, &print_args->range, "Writing PSML",
2639                                   "selected packets", TRUE,
2640                                   write_psml_packet, &callback_args, TRUE);
2641
2642   epan_dissect_cleanup(&callback_args.edt);
2643
2644   switch (ret) {
2645
2646   case PSP_FINISHED:
2647     /* Completed successfully. */
2648     break;
2649
2650   case PSP_STOPPED:
2651     /* Well, the user decided to abort the printing. */
2652     break;
2653
2654   case PSP_FAILED:
2655     /* Error while printing. */
2656     fclose(fh);
2657     return CF_PRINT_WRITE_ERROR;
2658   }
2659
2660   write_psml_finale(fh);
2661   if (ferror(fh)) {
2662     fclose(fh);
2663     return CF_PRINT_WRITE_ERROR;
2664   }
2665
2666   /* XXX - check for an error */
2667   fclose(fh);
2668
2669   return CF_PRINT_OK;
2670 }
2671
2672 static gboolean
2673 write_csv_packet(capture_file *cf, frame_data *fdata,
2674                  struct wtap_pkthdr *phdr, const guint8 *pd,
2675                  void *argsp)
2676 {
2677   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2678
2679   /* Fill in the column information */
2680   col_custom_prime_edt(&args->edt, &cf->cinfo);
2681   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2682                    frame_tvbuff_new(&cf->provider, fdata, pd),
2683                    fdata, &cf->cinfo);
2684   epan_dissect_fill_in_columns(&args->edt, FALSE, TRUE);
2685
2686   /* Write out the column information. */
2687   write_csv_columns(&args->edt, args->fh);
2688
2689   epan_dissect_reset(&args->edt);
2690
2691   return !ferror(args->fh);
2692 }
2693
2694 cf_print_status_t
2695 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2696 {
2697   write_packet_callback_args_t callback_args;
2698   gboolean        proto_tree_needed;
2699   FILE         *fh;
2700   psp_return_t  ret;
2701
2702   fh = ws_fopen(print_args->file, "w");
2703   if (fh == NULL)
2704     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2705
2706   write_csv_column_titles(&cf->cinfo, fh);
2707   if (ferror(fh)) {
2708     fclose(fh);
2709     return CF_PRINT_WRITE_ERROR;
2710   }
2711
2712   callback_args.fh = fh;
2713   callback_args.print_args = print_args;
2714
2715   /* only create the protocol tree if having custom columns or field extractors. */
2716   proto_tree_needed = have_custom_cols(&cf->cinfo) || have_field_extractors();
2717   epan_dissect_init(&callback_args.edt, cf->epan, proto_tree_needed, proto_tree_needed);
2718
2719   /* Iterate through the list of packets, printing the packets we were
2720      told to print. */
2721   ret = process_specified_records(cf, &print_args->range, "Writing CSV",
2722                                   "selected packets", TRUE,
2723                                   write_csv_packet, &callback_args, TRUE);
2724
2725   epan_dissect_cleanup(&callback_args.edt);
2726
2727   switch (ret) {
2728
2729   case PSP_FINISHED:
2730     /* Completed successfully. */
2731     break;
2732
2733   case PSP_STOPPED:
2734     /* Well, the user decided to abort the printing. */
2735     break;
2736
2737   case PSP_FAILED:
2738     /* Error while printing. */
2739     fclose(fh);
2740     return CF_PRINT_WRITE_ERROR;
2741   }
2742
2743   /* XXX - check for an error */
2744   fclose(fh);
2745
2746   return CF_PRINT_OK;
2747 }
2748
2749 static gboolean
2750 carrays_write_packet(capture_file *cf, frame_data *fdata,
2751              struct wtap_pkthdr *phdr,
2752              const guint8 *pd, void *argsp)
2753 {
2754   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2755
2756   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2757                    frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2758   write_carrays_hex_data(fdata->num, args->fh, &args->edt);
2759   epan_dissect_reset(&args->edt);
2760
2761   return !ferror(args->fh);
2762 }
2763
2764 cf_print_status_t
2765 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2766 {
2767   write_packet_callback_args_t callback_args;
2768   FILE         *fh;
2769   psp_return_t  ret;
2770
2771   fh = ws_fopen(print_args->file, "w");
2772
2773   if (fh == NULL)
2774     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2775
2776   if (ferror(fh)) {
2777     fclose(fh);
2778     return CF_PRINT_WRITE_ERROR;
2779   }
2780
2781   callback_args.fh = fh;
2782   callback_args.print_args = print_args;
2783   epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2784
2785   /* Iterate through the list of packets, printing the packets we were
2786      told to print. */
2787   ret = process_specified_records(cf, &print_args->range,
2788                                   "Writing C Arrays",
2789                                   "selected packets", TRUE,
2790                                   carrays_write_packet, &callback_args, TRUE);
2791
2792   epan_dissect_cleanup(&callback_args.edt);
2793
2794   switch (ret) {
2795   case PSP_FINISHED:
2796     /* Completed successfully. */
2797     break;
2798   case PSP_STOPPED:
2799     /* Well, the user decided to abort the printing. */
2800     break;
2801   case PSP_FAILED:
2802     /* Error while printing. */
2803     fclose(fh);
2804     return CF_PRINT_WRITE_ERROR;
2805   }
2806
2807   fclose(fh);
2808   return CF_PRINT_OK;
2809 }
2810
2811 static gboolean
2812 write_json_packet(capture_file *cf, frame_data *fdata,
2813                   struct wtap_pkthdr *phdr, const guint8 *pd,
2814           void *argsp)
2815 {
2816   write_packet_callback_args_t *args = (write_packet_callback_args_t *)argsp;
2817
2818   /* Create the protocol tree, but don't fill in the column information. */
2819   epan_dissect_run(&args->edt, cf->cd_t, phdr,
2820                    frame_tvbuff_new(&cf->provider, fdata, pd), fdata, NULL);
2821
2822   /* Write out the information in that tree. */
2823   write_json_proto_tree(NULL, args->print_args->print_dissections,
2824                         args->print_args->print_hex, NULL, PF_NONE,
2825                         &args->edt, &cf->cinfo, proto_node_group_children_by_unique, args->fh);
2826
2827   epan_dissect_reset(&args->edt);
2828
2829   return !ferror(args->fh);
2830 }
2831
2832 cf_print_status_t
2833 cf_write_json_packets(capture_file *cf, print_args_t *print_args)
2834 {
2835   write_packet_callback_args_t callback_args;
2836   FILE         *fh;
2837   psp_return_t  ret;
2838
2839   fh = ws_fopen(print_args->file, "w");
2840   if (fh == NULL)
2841     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2842
2843   write_json_preamble(fh);
2844   if (ferror(fh)) {
2845     fclose(fh);
2846     return CF_PRINT_WRITE_ERROR;
2847   }
2848
2849   callback_args.fh = fh;
2850   callback_args.print_args = print_args;
2851   epan_dissect_init(&callback_args.edt, cf->epan, TRUE, TRUE);
2852
2853   /* Iterate through the list of packets, printing the packets we were
2854      told to print. */
2855   ret = process_specified_records(cf, &print_args->range, "Writing PDML",
2856                                   "selected packets", TRUE,
2857                                   write_json_packet, &callback_args, TRUE);
2858
2859   epan_dissect_cleanup(&callback_args.edt);
2860
2861   switch (ret) {
2862
2863   case PSP_FINISHED:
2864     /* Completed successfully. */
2865     break;
2866
2867   case PSP_STOPPED:
2868     /* Well, the user decided to abort the printing. */
2869     break;
2870
2871   case PSP_FAILED:
2872     /* Error while printing. */
2873     fclose(fh);
2874     return CF_PRINT_WRITE_ERROR;
2875   }
2876
2877   write_json_finale(fh);
2878   if (ferror(fh)) {
2879     fclose(fh);
2880     return CF_PRINT_WRITE_ERROR;
2881   }
2882
2883   /* XXX - check for an error */
2884   fclose(fh);
2885
2886   return CF_PRINT_OK;
2887 }
2888
2889 gboolean
2890 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2891                              search_direction dir)
2892 {
2893   match_data mdata;
2894
2895   mdata.string = string;
2896   mdata.string_len = strlen(string);
2897   return find_packet(cf, match_protocol_tree, &mdata, dir);
2898 }
2899
2900 gboolean
2901 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree,  match_data *mdata)
2902 {
2903   mdata->frame_matched = FALSE;
2904   mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2905   mdata->string_len = strlen(mdata->string);
2906   mdata->cf = cf;
2907   /* Iterate through all the nodes looking for matching text */
2908   proto_tree_children_foreach(tree, match_subtree_text, mdata);
2909   return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2910 }
2911
2912 static match_result
2913 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2914 {
2915   match_data     *mdata = (match_data *)criterion;
2916   epan_dissect_t  edt;
2917
2918   /* Load the frame's data. */
2919   if (!cf_read_record(cf, fdata)) {
2920     /* Attempt to get the packet failed. */
2921     return MR_ERROR;
2922   }
2923
2924   /* Construct the protocol tree, including the displayed text */
2925   epan_dissect_init(&edt, cf->epan, TRUE, TRUE);
2926   /* We don't need the column information */
2927   epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
2928                    frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
2929                    fdata, NULL);
2930
2931   /* Iterate through all the nodes, seeing if they have text that matches. */
2932   mdata->cf = cf;
2933   mdata->frame_matched = FALSE;
2934   proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
2935   epan_dissect_cleanup(&edt);
2936   return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2937 }
2938
2939 static void
2940 match_subtree_text(proto_node *node, gpointer data)
2941 {
2942   match_data   *mdata      = (match_data *) data;
2943   const gchar  *string     = mdata->string;
2944   size_t        string_len = mdata->string_len;
2945   capture_file *cf         = mdata->cf;
2946   field_info   *fi         = PNODE_FINFO(node);
2947   gchar         label_str[ITEM_LABEL_LENGTH];
2948   gchar        *label_ptr;
2949   size_t        label_len;
2950   guint32       i;
2951   guint8        c_char;
2952   size_t        c_match    = 0;
2953
2954   /* dissection with an invisible proto tree? */
2955   g_assert(fi);
2956
2957   if (mdata->frame_matched) {
2958     /* We already had a match; don't bother doing any more work. */
2959     return;
2960   }
2961
2962   /* Don't match invisible entries. */
2963   if (PROTO_ITEM_IS_HIDDEN(node))
2964     return;
2965
2966   /* was a free format label produced? */
2967   if (fi->rep) {
2968     label_ptr = fi->rep->representation;
2969   } else {
2970     /* no, make a generic label */
2971     label_ptr = label_str;
2972     proto_item_fill_label(fi, label_str);
2973   }
2974
2975   if (cf->regex) {
2976     if (g_regex_match(cf->regex, label_ptr, (GRegexMatchFlags) 0, NULL)) {
2977       mdata->frame_matched = TRUE;
2978       mdata->finfo = fi;
2979       return;
2980     }
2981   } else {
2982     /* Does that label match? */
2983     label_len = strlen(label_ptr);
2984     for (i = 0; i < label_len; i++) {
2985       c_char = label_ptr[i];
2986       if (cf->case_type)
2987         c_char = g_ascii_toupper(c_char);
2988       if (c_char == string[c_match]) {
2989         c_match++;
2990         if (c_match == string_len) {
2991           /* No need to look further; we have a match */
2992           mdata->frame_matched = TRUE;
2993           mdata->finfo = fi;
2994           return;
2995         }
2996       } else
2997         c_match = 0;
2998     }
2999   }
3000
3001   /* Recurse into the subtree, if it exists */
3002   if (node->first_child != NULL)
3003     proto_tree_children_foreach(node, match_subtree_text, mdata);
3004 }
3005
3006 gboolean
3007 cf_find_packet_summary_line(capture_file *cf, const char *string,
3008                             search_direction dir)
3009 {
3010   match_data mdata;
3011
3012   mdata.string = string;
3013   mdata.string_len = strlen(string);
3014   return find_packet(cf, match_summary_line, &mdata, dir);
3015 }
3016
3017 static match_result
3018 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
3019 {
3020   match_data     *mdata      = (match_data *)criterion;
3021   const gchar    *string     = mdata->string;
3022   size_t          string_len = mdata->string_len;
3023   epan_dissect_t  edt;
3024   const char     *info_column;
3025   size_t          info_column_len;
3026   match_result    result     = MR_NOTMATCHED;
3027   gint            colx;
3028   guint32         i;
3029   guint8          c_char;
3030   size_t          c_match    = 0;
3031
3032   /* Load the frame's data. */
3033   if (!cf_read_record(cf, fdata)) {
3034     /* Attempt to get the packet failed. */
3035     return MR_ERROR;
3036   }
3037
3038   /* Don't bother constructing the protocol tree */
3039   epan_dissect_init(&edt, cf->epan, FALSE, FALSE);
3040   /* Get the column information */
3041   epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3042                    frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3043                    fdata, &cf->cinfo);
3044
3045   /* Find the Info column */
3046   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3047     if (cf->cinfo.columns[colx].fmt_matx[COL_INFO]) {
3048       /* Found it.  See if we match. */
3049       info_column = edt.pi.cinfo->columns[colx].col_data;
3050       info_column_len = strlen(info_column);
3051       if (cf->regex) {
3052         if (g_regex_match(cf->regex, info_column, (GRegexMatchFlags) 0, NULL)) {
3053           result = MR_MATCHED;
3054           break;
3055         }
3056       } else {
3057         for (i = 0; i < info_column_len; i++) {
3058           c_char = info_column[i];
3059           if (cf->case_type)
3060             c_char = g_ascii_toupper(c_char);
3061           if (c_char == string[c_match]) {
3062             c_match++;
3063             if (c_match == string_len) {
3064               result = MR_MATCHED;
3065               break;
3066             }
3067           } else
3068             c_match = 0;
3069         }
3070       }
3071       break;
3072     }
3073   }
3074   epan_dissect_cleanup(&edt);
3075   return result;
3076 }
3077
3078 typedef struct {
3079     const guint8 *data;
3080     size_t        data_len;
3081 } cbs_t;    /* "Counted byte string" */
3082
3083
3084 /*
3085  * The current match_* routines only support ASCII case insensitivity and don't
3086  * convert UTF-8 inputs to UTF-16 for matching.
3087  *
3088  * We could modify them to use the GLib Unicode routines or the International
3089  * Components for Unicode library but it's not apparent that we could do so
3090  * without consuming a lot more CPU and memory or that searching would be
3091  * significantly better.
3092  */
3093
3094 gboolean
3095 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3096                     search_direction dir)
3097 {
3098   cbs_t info;
3099
3100   info.data = string;
3101   info.data_len = string_size;
3102
3103   /* Regex, String or hex search? */
3104   if (cf->regex) {
3105     /* Regular Expression search */
3106     return find_packet(cf, match_regex, NULL, dir);
3107   } else if (cf->string) {
3108     /* String search - what type of string? */
3109     switch (cf->scs_type) {
3110
3111     case SCS_NARROW_AND_WIDE:
3112       return find_packet(cf, match_narrow_and_wide, &info, dir);
3113
3114     case SCS_NARROW:
3115       return find_packet(cf, match_narrow, &info, dir);
3116
3117     case SCS_WIDE:
3118       return find_packet(cf, match_wide, &info, dir);
3119
3120     default:
3121       g_assert_not_reached();
3122       return FALSE;
3123     }
3124   } else
3125     return find_packet(cf, match_binary, &info, dir);
3126 }
3127
3128 static match_result
3129 match_narrow_and_wide(capture_file *cf, frame_data *fdata, void *criterion)
3130 {
3131   cbs_t        *info       = (cbs_t *)criterion;
3132   const guint8 *ascii_text = info->data;
3133   size_t        textlen    = info->data_len;
3134   match_result  result;
3135   guint32       buf_len;
3136   guint8       *pd;
3137   guint32       i;
3138   guint8        c_char;
3139   size_t        c_match    = 0;
3140
3141   /* Load the frame's data. */
3142   if (!cf_read_record(cf, fdata)) {
3143     /* Attempt to get the packet failed. */
3144     return MR_ERROR;
3145   }
3146
3147   result = MR_NOTMATCHED;
3148   buf_len = fdata->cap_len;
3149   pd = ws_buffer_start_ptr(&cf->buf);
3150   i = 0;
3151   while (i < buf_len) {
3152     c_char = pd[i];
3153     if (cf->case_type)
3154       c_char = g_ascii_toupper(c_char);
3155     if (c_char != '\0') {
3156       if (c_char == ascii_text[c_match]) {
3157         c_match += 1;
3158         if (c_match == textlen) {
3159           result = MR_MATCHED;
3160           cf->search_pos = i; /* Save the position of the last character
3161                                  for highlighting the field. */
3162           cf->search_len = (guint32)textlen;
3163           break;
3164         }
3165       }
3166       else {
3167         g_assert(i>=c_match);
3168         i -= (guint32)c_match;
3169         c_match = 0;
3170       }
3171     }
3172     i += 1;
3173   }
3174   return result;
3175 }
3176
3177 static match_result
3178 match_narrow(capture_file *cf, frame_data *fdata, void *criterion)
3179 {
3180   guint8       *pd;
3181   cbs_t        *info       = (cbs_t *)criterion;
3182   const guint8 *ascii_text = info->data;
3183   size_t        textlen    = info->data_len;
3184   match_result  result;
3185   guint32       buf_len;
3186   guint32       i;
3187   guint8        c_char;
3188   size_t        c_match    = 0;
3189
3190   /* Load the frame's data. */
3191   if (!cf_read_record(cf, fdata)) {
3192     /* Attempt to get the packet failed. */
3193     return MR_ERROR;
3194   }
3195
3196   result = MR_NOTMATCHED;
3197   buf_len = fdata->cap_len;
3198   pd = ws_buffer_start_ptr(&cf->buf);
3199   i = 0;
3200   while (i < buf_len) {
3201     c_char = pd[i];
3202     if (cf->case_type)
3203       c_char = g_ascii_toupper(c_char);
3204     if (c_char == ascii_text[c_match]) {
3205       c_match += 1;
3206       if (c_match == textlen) {
3207         result = MR_MATCHED;
3208         cf->search_pos = i; /* Save the position of the last character
3209                                for highlighting the field. */
3210         cf->search_len = (guint32)textlen;
3211         break;
3212       }
3213     }
3214     else {
3215       g_assert(i>=c_match);
3216       i -= (guint32)c_match;
3217       c_match = 0;
3218     }
3219     i += 1;
3220   }
3221
3222   return result;
3223 }
3224
3225 static match_result
3226 match_wide(capture_file *cf, frame_data *fdata, void *criterion)
3227 {
3228   cbs_t        *info       = (cbs_t *)criterion;
3229   const guint8 *ascii_text = info->data;
3230   size_t        textlen    = info->data_len;
3231   match_result  result;
3232   guint32       buf_len;
3233   guint8       *pd;
3234   guint32       i;
3235   guint8        c_char;
3236   size_t        c_match    = 0;
3237
3238   /* Load the frame's data. */
3239   if (!cf_read_record(cf, fdata)) {
3240     /* Attempt to get the packet failed. */
3241     return MR_ERROR;
3242   }
3243
3244   result = MR_NOTMATCHED;
3245   buf_len = fdata->cap_len;
3246   pd = ws_buffer_start_ptr(&cf->buf);
3247   i = 0;
3248   while (i < buf_len) {
3249     c_char = pd[i];
3250     if (cf->case_type)
3251       c_char = g_ascii_toupper(c_char);
3252     if (c_char == ascii_text[c_match]) {
3253       c_match += 1;
3254       if (c_match == textlen) {
3255         result = MR_MATCHED;
3256         cf->search_pos = i; /* Save the position of the last character
3257                                for highlighting the field. */
3258         cf->search_len = (guint32)textlen;
3259         break;
3260       }
3261       i += 1;
3262     }
3263     else {
3264       g_assert(i>=(c_match*2));
3265       i -= (guint32)c_match*2;
3266       c_match = 0;
3267     }
3268     i += 1;
3269   }
3270   return result;
3271 }
3272
3273 static match_result
3274 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3275 {
3276   cbs_t        *info        = (cbs_t *)criterion;
3277   const guint8 *binary_data = info->data;
3278   size_t        datalen     = info->data_len;
3279   match_result  result;
3280   guint32       buf_len;
3281   guint8       *pd;
3282   guint32       i;
3283   size_t        c_match     = 0;
3284
3285   /* Load the frame's data. */
3286   if (!cf_read_record(cf, fdata)) {
3287     /* Attempt to get the packet failed. */
3288     return MR_ERROR;
3289   }
3290
3291   result = MR_NOTMATCHED;
3292   buf_len = fdata->cap_len;
3293   pd = ws_buffer_start_ptr(&cf->buf);
3294   i = 0;
3295   while (i < buf_len) {
3296     if (pd[i] == binary_data[c_match]) {
3297       c_match += 1;
3298       if (c_match == datalen) {
3299         result = MR_MATCHED;
3300         cf->search_pos = i; /* Save the position of the last character
3301                                for highlighting the field. */
3302         cf->search_len = (guint32)datalen;
3303         break;
3304       }
3305     }
3306     else {
3307       g_assert(i>=c_match);
3308       i -= (guint32)c_match;
3309       c_match = 0;
3310     }
3311     i += 1;
3312   }
3313   return result;
3314 }
3315
3316 static match_result
3317 match_regex(capture_file *cf, frame_data *fdata, void *criterion _U_)
3318 {
3319     match_result  result = MR_NOTMATCHED;
3320     GMatchInfo   *match_info = NULL;
3321
3322     /* Load the frame's data. */
3323     if (!cf_read_record(cf, fdata)) {
3324         /* Attempt to get the packet failed. */
3325         return MR_ERROR;
3326     }
3327
3328     if (g_regex_match_full(cf->regex, (const gchar *)ws_buffer_start_ptr(&cf->buf), fdata->cap_len,
3329                            0, (GRegexMatchFlags) 0, &match_info, NULL))
3330     {
3331         gint start_pos = 0, end_pos = 0;
3332         g_match_info_fetch_pos (match_info, 0, &start_pos, &end_pos);
3333         cf->search_pos = end_pos - 1;
3334         cf->search_len = end_pos - start_pos;
3335         result = MR_MATCHED;
3336     }
3337     return result;
3338 }
3339
3340 gboolean
3341 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3342                        search_direction dir)
3343 {
3344   return find_packet(cf, match_dfilter, sfcode, dir);
3345 }
3346
3347 gboolean
3348 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3349                               search_direction dir)
3350 {
3351   dfilter_t *sfcode;
3352   gboolean   result;
3353
3354   if (!dfilter_compile(filter, &sfcode, NULL)) {
3355      /*
3356       * XXX - this shouldn't happen, as the filter string is machine
3357       * generated
3358       */
3359     return FALSE;
3360   }
3361   if (sfcode == NULL) {
3362     /*
3363      * XXX - this shouldn't happen, as the filter string is machine
3364      * generated.
3365      */
3366     return FALSE;
3367   }
3368   result = find_packet(cf, match_dfilter, sfcode, dir);
3369   dfilter_free(sfcode);
3370   return result;
3371 }
3372
3373 static match_result
3374 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3375 {
3376   dfilter_t      *sfcode = (dfilter_t *)criterion;
3377   epan_dissect_t  edt;
3378   match_result    result;
3379
3380   /* Load the frame's data. */
3381   if (!cf_read_record(cf, fdata)) {
3382     /* Attempt to get the packet failed. */
3383     return MR_ERROR;
3384   }
3385
3386   epan_dissect_init(&edt, cf->epan, TRUE, FALSE);
3387   epan_dissect_prime_with_dfilter(&edt, sfcode);
3388   epan_dissect_run(&edt, cf->cd_t, &cf->phdr,
3389                    frame_tvbuff_new_buffer(&cf->provider, fdata, &cf->buf),
3390                    fdata, NULL);
3391   result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3392   epan_dissect_cleanup(&edt);
3393   return result;
3394 }
3395
3396 gboolean
3397 cf_find_packet_marked(capture_file *cf, search_direction dir)
3398 {
3399   return find_packet(cf, match_marked, NULL, dir);
3400 }
3401
3402 static match_result
3403 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3404 {
3405   return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3406 }
3407
3408 gboolean
3409 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3410 {
3411   return find_packet(cf, match_time_reference, NULL, dir);
3412 }
3413
3414 static match_result
3415 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3416 {
3417   return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3418 }
3419
3420 static gboolean
3421 find_packet(capture_file *cf,
3422             match_result (*match_function)(capture_file *, frame_data *, void *),
3423             void *criterion, search_direction dir)
3424 {
3425   frame_data  *start_fd;
3426   guint32      framenum;
3427   frame_data  *fdata;
3428   frame_data  *new_fd = NULL;
3429   progdlg_t   *progbar = NULL;
3430   GTimer      *prog_timer = g_timer_new();
3431   int          count;
3432   gboolean     found;
3433   float        progbar_val;
3434   GTimeVal     start_time;
3435   gchar        status_str[100];
3436   const char  *title;
3437   match_result result;
3438
3439   start_fd = cf->current_frame;
3440   if (start_fd != NULL)  {
3441     /* Iterate through the list of packets, starting at the packet we've
3442        picked, calling a routine to run the filter on the packet, see if
3443        it matches, and stop if so.  */
3444     count = 0;
3445     framenum = start_fd->num;
3446
3447     g_timer_start(prog_timer);
3448     /* Progress so far. */
3449     progbar_val = 0.0f;
3450
3451     cf->stop_flag = FALSE;
3452     g_get_current_time(&start_time);
3453
3454     title = cf->sfilter?cf->sfilter:"";
3455     for (;;) {
3456       /* Create the progress bar if necessary.
3457          We check on every iteration of the loop, so that it takes no
3458          longer than the standard time to create it (otherwise, for a
3459          large file, we might take considerably longer than that standard
3460          time in order to get to the next progress bar step). */
3461       if (progbar == NULL)
3462          progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3463            FALSE, &cf->stop_flag, &start_time, progbar_val);
3464
3465       /*
3466        * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
3467        * has elapsed. Calling update_progress_dlg and packets_bar_update will
3468        * likely trigger UI paint events, which might take a while depending on
3469        * the platform and display. Reset our timer *after* painting.
3470        */
3471       if (g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
3472         /* let's not divide by zero. I should never be started
3473          * with count == 0, so let's assert that
3474          */
3475         g_assert(cf->count > 0);
3476
3477         progbar_val = (gfloat) count / cf->count;
3478
3479         g_snprintf(status_str, sizeof(status_str),
3480                     "%4u of %u packets", count, cf->count);
3481         update_progress_dlg(progbar, progbar_val, status_str);
3482
3483         g_timer_start(prog_timer);
3484       }
3485
3486       if (cf->stop_flag) {
3487         /* Well, the user decided to abort the search.  Go back to the
3488            frame where we started. */
3489         new_fd = start_fd;
3490         break;
3491       }
3492
3493       /* Go past the current frame. */
3494       if (dir == SD_BACKWARD) {
3495         /* Go on to the previous frame. */
3496         if (framenum == 1) {
3497           /*
3498            * XXX - other apps have a bit more of a detailed message
3499            * for this, and instead of offering "OK" and "Cancel",
3500            * they offer things such as "Continue" and "Cancel";
3501            * we need an API for popping up alert boxes with
3502            * {Verb} and "Cancel".
3503            */
3504
3505           if (prefs.gui_find_wrap)
3506           {
3507               statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3508               framenum = cf->count;     /* wrap around */
3509           }
3510           else
3511           {
3512               statusbar_push_temporary_msg("Search reached the beginning.");
3513               framenum = start_fd->num; /* stay on previous packet */
3514           }
3515         } else
3516           framenum--;
3517       } else {
3518         /* Go on to the next frame. */
3519         if (framenum == cf->count) {
3520           if (prefs.gui_find_wrap)
3521           {
3522               statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3523               framenum = 1;             /* wrap around */
3524           }
3525           else
3526           {
3527               statusbar_push_temporary_msg("Search reached the end.");
3528               framenum = start_fd->num; /* stay on previous packet */
3529           }
3530         } else
3531           framenum++;
3532       }
3533       fdata = frame_data_sequence_find(cf->provider.frames, framenum);
3534
3535       count++;
3536
3537       /* Is this packet in the display? */
3538       if (fdata->flags.passed_dfilter) {
3539         /* Yes.  Does it match the search criterion? */
3540         result = (*match_function)(cf, fdata, criterion);
3541         if (result == MR_ERROR) {
3542           /* Error; our caller has reported the error.  Go back to the frame
3543              where we started. */
3544           new_fd = start_fd;
3545           break;
3546         } else if (result == MR_MATCHED) {
3547           /* Yes.  Go to the new frame. */
3548           new_fd = fdata;
3549           break;
3550         }
3551       }
3552
3553       if (fdata == start_fd) {
3554         /* We're back to the frame we were on originally, and that frame
3555            doesn't match the search filter.  The search failed. */
3556         break;
3557       }
3558     }
3559
3560     /* We're done scanning the packets; destroy the progress bar if it
3561        was created. */
3562     if (progbar != NULL)
3563       destroy_progress_dlg(progbar);
3564     g_timer_destroy(prog_timer);
3565   }
3566
3567   if (new_fd != NULL) {
3568     /* Find and select */
3569     cf->search_in_progress = TRUE;
3570     found = packet_list_select_row_from_data(new_fd);
3571     cf->search_in_progress = FALSE;
3572     cf->search_pos = 0; /* Reset the position */
3573     cf->search_len = 0; /* Reset length */
3574     if (!found) {
3575       /* We didn't find a row corresponding to this frame.
3576          This means that the frame isn't being displayed currently,
3577          so we can't select it. */
3578       simple_message_box(ESD_TYPE_INFO, NULL,
3579                          "The capture file is probably not fully dissected.",
3580                          "End of capture exceeded.");
3581       return FALSE;
3582     }
3583     return TRUE;    /* success */
3584   } else
3585     return FALSE;   /* failure */
3586 }
3587
3588 gboolean
3589 cf_goto_frame(capture_file *cf, guint fnumber)
3590 {
3591   frame_data *fdata;
3592
3593   if (cf == NULL || cf->provider.frames == NULL) {
3594     /* we don't have a loaded capture file - fix for bugs 11810 & 11989 */
3595     statusbar_push_temporary_msg("There is no file loaded");
3596     return FALSE;   /* we failed to go to that packet */
3597   }
3598
3599   fdata = frame_data_sequence_find(cf->provider.frames, fnumber);
3600
3601   if (fdata == NULL) {
3602     /* we didn't find a packet with that packet number */
3603     statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3604     return FALSE;   /* we failed to go to that packet */
3605   }
3606   if (!fdata->flags.passed_dfilter) {
3607     /* that packet currently isn't displayed */
3608     /* XXX - add it to the set of displayed packets? */
3609     statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3610     return FALSE;   /* we failed to go to that packet */
3611   }
3612
3613   if (!packet_list_select_row_from_data(fdata)) {
3614     /* We didn't find a row corresponding to this frame.
3615        This means that the frame isn't being displayed currently,
3616        so we can't select it. */
3617     simple_message_box(ESD_TYPE_INFO, NULL,
3618                        "The capture file is probably not fully dissected.",
3619                        "End of capture exceeded.");
3620     return FALSE;
3621   }
3622   return TRUE;  /* we got to that packet */
3623 }
3624
3625 /*
3626  * Go to frame specified by currently selected protocol tree item.
3627  */
3628 gboolean
3629 cf_goto_framenum(capture_file *cf)
3630 {
3631   header_field_info *hfinfo;
3632   guint32            framenum;
3633
3634   if (cf->finfo_selected) {
3635     hfinfo = cf->finfo_selected->hfinfo;
3636     g_assert(hfinfo);
3637     if (hfinfo->type == FT_FRAMENUM) {
3638       framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3639       if (framenum != 0)
3640         return cf_goto_frame(cf, framenum);
3641       }
3642   }
3643
3644   return FALSE;
3645 }
3646
3647 /* Select the packet on a given row. */
3648 void
3649 cf_select_packet(capture_file *cf, int row)
3650 {
3651   epan_dissect_t *old_edt;
3652   frame_data     *fdata;
3653
3654   /* Get the frame data struct pointer for this frame */
3655   fdata = packet_list_get_row_data(row);
3656
3657   if (fdata == NULL) {
3658     return;
3659   }
3660
3661   /* Get the data in that frame. */
3662   if (!cf_read_record (cf, fdata)) {
3663     return;
3664   }
3665
3666   /* Record that this frame is the current frame. */
3667   cf->current_frame = fdata;
3668   cf->current_row = row;
3669
3670   old_edt = cf->edt;
3671   /* Create the logical protocol tree. */
3672   /* We don't need the columns here. */
3673   cf->edt = epan_dissect_new(cf->epan, TRUE, TRUE);
3674
3675   tap_build_interesting(cf->edt);
3676   epan_dissect_run(cf->edt, cf->cd_t, &cf->phdr,
3677                    frame_tvbuff_new_buffer(&cf->provider, cf->current_frame, &cf->buf),
3678                    cf->current_frame, NULL);
3679
3680   dfilter_macro_build_ftv_cache(cf->edt->tree);
3681
3682   cf_callback_invoke(cf_cb_packet_selected, cf);
3683
3684   if (old_edt != NULL)
3685     epan_dissect_free(old_edt);
3686
3687 }
3688
3689 /* Unselect the selected packet, if any. */
3690 void
3691 cf_unselect_packet(capture_file *cf)
3692 {
3693   epan_dissect_t *old_edt = cf->edt;
3694
3695   cf->edt = NULL;
3696
3697   /* No packet is selected. */
3698   cf->current_frame = NULL;
3699   cf->current_row = 0;
3700
3701   cf_callback_invoke(cf_cb_packet_unselected, cf);
3702
3703   /* No protocol tree means no selected field. */
3704   cf_unselect_field(cf);
3705
3706   /* Destroy the epan_dissect_t for the unselected packet. */
3707   if (old_edt != NULL)
3708     epan_dissect_free(old_edt);
3709 }
3710
3711 /* Unset the selected protocol tree field, if any. */
3712 void
3713 cf_unselect_field(capture_file *cf)
3714 {
3715   cf->finfo_selected = NULL;
3716
3717   cf_callback_invoke(cf_cb_field_unselected, cf);
3718 }
3719
3720 /*
3721  * Mark a particular frame.
3722  */
3723 void
3724 cf_mark_frame(capture_file *cf, frame_data *frame)
3725 {
3726   if (! frame->flags.marked) {
3727     frame->flags.marked = TRUE;
3728     if (cf->count > cf->marked_count)
3729       cf->marked_count++;
3730   }
3731 }
3732
3733 /*
3734  * Unmark a particular frame.
3735  */
3736 void
3737 cf_unmark_frame(capture_file *cf, frame_data *frame)
3738 {
3739   if (frame->flags.marked) {
3740     frame->flags.marked = FALSE;
3741     if (cf->marked_count > 0)
3742       cf->marked_count--;
3743   }
3744 }
3745
3746 /*
3747  * Ignore a particular frame.
3748  */
3749 void
3750 cf_ignore_frame(capture_file *cf, frame_data *frame)
3751 {
3752   if (! frame->flags.ignored) {
3753     frame->flags.ignored = TRUE;
3754     if (cf->count > cf->ignored_count)
3755       cf->ignored_count++;
3756   }
3757 }
3758
3759 /*
3760  * Un-ignore a particular frame.
3761  */
3762 void
3763 cf_unignore_frame(capture_file *cf, frame_data *frame)
3764 {
3765   if (frame->flags.ignored) {
3766     frame->flags.ignored = FALSE;
3767     if (cf->ignored_count > 0)
3768       cf->ignored_count--;
3769   }
3770 }
3771
3772 /*
3773  * Read the section comment.
3774  */
3775 const gchar *
3776 cf_read_section_comment(capture_file *cf)
3777 {
3778   wtap_block_t shb_inf;
3779   char *shb_comment;
3780
3781   /* Get the SHB. */
3782   /* XXX - support multiple SHBs */
3783   shb_inf = wtap_file_get_shb(cf->provider.wth);
3784
3785   /* Get the first comment from the SHB. */
3786   /* XXX - support multiple comments */
3787   if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS)
3788     return NULL;
3789   return shb_comment;
3790 }
3791
3792 /*
3793  * Modify the section comment.
3794  */
3795 void
3796 cf_update_section_comment(capture_file *cf, gchar *comment)
3797 {
3798   wtap_block_t shb_inf;
3799   gchar *shb_comment;
3800
3801   /* Get the SHB. */
3802   /* XXX - support multiple SHBs */
3803   shb_inf = wtap_file_get_shb(cf->provider.wth);
3804
3805   /* Get the first comment from the SHB. */
3806   /* XXX - support multiple comments */
3807   if (wtap_block_get_nth_string_option_value(shb_inf, OPT_COMMENT, 0, &shb_comment) != WTAP_OPTTYPE_SUCCESS) {
3808     /* There's no comment - add one. */
3809     wtap_block_add_string_option(shb_inf, OPT_COMMENT, comment, strlen(comment));
3810   } else {
3811     /* See if the comment has changed or not */
3812     if (strcmp(shb_comment, comment) == 0) {
3813       g_free(comment);
3814       return;
3815     }
3816
3817     /* The comment has changed, let's update it */
3818     wtap_block_set_nth_string_option_value(shb_inf, OPT_COMMENT, 0, comment, strlen(comment));
3819   }
3820   /* Mark the file as having unsaved changes */
3821   cf->unsaved_changes = TRUE;
3822 }
3823
3824 /*
3825  * Get the comment on a packet (record).
3826  * If the comment has been edited, it returns the result of the edit,
3827  * otherwise it returns the comment from the file.
3828  */
3829 char *
3830 cf_get_packet_comment(capture_file *cf, const frame_data *fd)
3831 {
3832   char *comment;
3833
3834   /* fetch user comment */
3835   if (fd->flags.has_user_comment)
3836     return g_strdup(cap_file_provider_get_user_comment(&cf->provider, fd));
3837
3838   /* fetch phdr comment */
3839   if (fd->flags.has_phdr_comment) {
3840     struct wtap_pkthdr phdr; /* Packet header */
3841     Buffer buf; /* Packet data */
3842
3843     wtap_phdr_init(&phdr);
3844     ws_buffer_init(&buf, 1500);
3845
3846     if (!cf_read_record_r(cf, fd, &phdr, &buf))
3847       { /* XXX, what we can do here? */ }
3848
3849     comment = phdr.opt_comment;
3850     wtap_phdr_cleanup(&phdr);
3851     ws_buffer_free(&buf);
3852     return comment;
3853   }
3854   return NULL;
3855 }
3856
3857 /*
3858  * Update(replace) the comment on a capture from a frame
3859  */
3860 gboolean
3861 cf_set_user_packet_comment(capture_file *cf, frame_data *fd, const gchar *new_comment)
3862 {
3863   char *pkt_comment = cf_get_packet_comment(cf, fd);
3864
3865   /* Check if the comment has changed */
3866   if (!g_strcmp0(pkt_comment, new_comment)) {
3867     g_free(pkt_comment);
3868     return FALSE;
3869   }
3870   g_free(pkt_comment);
3871
3872   if (pkt_comment)
3873     cf->packet_comment_count--;
3874
3875   if (new_comment)
3876     cf->packet_comment_count++;
3877
3878   cap_file_provider_set_user_comment(&cf->provider, fd, new_comment);
3879
3880   expert_update_comment_count(cf->packet_comment_count);
3881
3882   /* OK, we have unsaved changes. */
3883   cf->unsaved_changes = TRUE;
3884   return TRUE;
3885 }
3886
3887 /*
3888  * What types of comments does this capture file have?
3889  */
3890 guint32
3891 cf_comment_types(capture_file *cf)
3892 {
3893   guint32 comment_types = 0;
3894
3895   if (cf_read_section_comment(cf) != NULL)
3896     comment_types |= WTAP_COMMENT_PER_SECTION;
3897   if (cf->packet_comment_count != 0)
3898     comment_types |= WTAP_COMMENT_PER_PACKET;
3899   return comment_types;
3900 }
3901
3902 /*
3903  * Add a resolved address to this file's list of resolved addresses.
3904  */
3905 gboolean
3906 cf_add_ip_name_from_string(capture_file *cf, const char *addr, const char *name)
3907 {
3908   /*
3909    * XXX - support multiple resolved address lists, and add to the one
3910    * attached to this file?
3911    */
3912   if (!add_ip_name_from_string(addr, name))
3913     return FALSE;
3914
3915   /* OK, we have unsaved changes. */
3916   cf->unsaved_changes = TRUE;
3917   return TRUE;
3918 }
3919
3920 typedef struct {
3921   wtap_dumper *pdh;
3922   const char  *fname;
3923   int          file_type;
3924 } save_callback_args_t;
3925
3926 /*
3927  * Save a capture to a file, in a particular format, saving either
3928  * all packets, all currently-displayed packets, or all marked packets.
3929  *
3930  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3931  * up a message box for the failure.
3932  */
3933 static gboolean
3934 save_record(capture_file *cf, frame_data *fdata,
3935             struct wtap_pkthdr *phdr, const guint8 *pd,
3936             void *argsp)
3937 {
3938   save_callback_args_t *args = (save_callback_args_t *)argsp;
3939   struct wtap_pkthdr    hdr;
3940   int           err;
3941   gchar        *err_info;
3942   const char   *pkt_comment;
3943
3944   if (fdata->flags.has_user_comment)
3945     pkt_comment = cap_file_provider_get_user_comment(&cf->provider, fdata);
3946   else
3947     pkt_comment = phdr->opt_comment;
3948
3949   /* init the wtap header for saving */
3950   /* TODO: reuse phdr */
3951   /* XXX - these are the only flags that correspond to data that we have
3952      in the frame_data structure and that matter on a per-packet basis.
3953
3954      For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3955      and "on the wire" lengths, or it doesn't.
3956
3957      For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3958      to its callers.
3959
3960      For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3961      from the packet flags. */
3962   hdr.rec_type = phdr->rec_type;
3963   hdr.presence_flags = 0;
3964   if (fdata->flags.has_ts)
3965     hdr.presence_flags |= WTAP_HAS_TS;
3966   if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID)
3967     hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3968   if (phdr->presence_flags & WTAP_HAS_PACK_FLAGS)
3969     hdr.presence_flags |= WTAP_HAS_PACK_FLAGS;
3970   hdr.ts           = phdr->ts;
3971   hdr.caplen       = phdr->caplen;
3972   hdr.len          = phdr->len;
3973   hdr.pkt_encap    = phdr->pkt_encap;
3974   /* pcapng */
3975   hdr.interface_id = phdr->interface_id;   /* identifier of the interface. */
3976   /* options */
3977   hdr.pack_flags   = phdr->pack_flags;
3978   hdr.opt_comment  = g_strdup(pkt_comment);
3979   hdr.has_comment_changed = fdata->flags.has_user_comment ? TRUE : FALSE;
3980
3981   /* pseudo */
3982   hdr.pseudo_header = phdr->pseudo_header;
3983 #if 0
3984   hdr.drop_count   =
3985   hdr.pack_flags   =     /* XXX - 0 for now (any value for "we don't have it"?) */
3986 #endif
3987   /* and save the packet */
3988   if (!wtap_dump(args->pdh, &hdr, pd, &err, &err_info)) {
3989     cfile_write_failure_alert_box(NULL, args->fname, err, err_info, fdata->num,
3990                                   args->file_type);
3991     return FALSE;
3992   }
3993
3994   g_free(hdr.opt_comment);
3995   return TRUE;
3996 }
3997
3998 /*
3999  * Can this capture file be written out in any format using Wiretap
4000  * rather than by copying the raw data?
4001  */
4002 gboolean
4003 cf_can_write_with_wiretap(capture_file *cf)
4004 {
4005   /* We don't care whether we support the comments in this file or not;
4006      if we can't, we'll offer the user the option of discarding the
4007      comments. */
4008   return wtap_dump_can_write(cf->linktypes, 0);
4009 }
4010
4011 /*
4012  * Should we let the user do a save?
4013  *
4014  * We should if:
4015  *
4016  *  the file has unsaved changes, and we can save it in some
4017  *  format through Wiretap
4018  *
4019  * or
4020  *
4021  *  the file is a temporary file and has no unsaved changes (so
4022  *  that "saving" it just means copying it).
4023  *
4024  * XXX - we shouldn't allow files to be edited if they can't be saved,
4025  * so cf->unsaved_changes should be true only if the file can be saved.
4026  *
4027  * We don't care whether we support the comments in this file or not;
4028  * if we can't, we'll offer the user the option of discarding the
4029  * comments.
4030  */
4031 gboolean
4032 cf_can_save(capture_file *cf)
4033 {
4034   if (cf->unsaved_changes && wtap_dump_can_write(cf->linktypes, 0)) {
4035     /* Saved changes, and we can write it out with Wiretap. */
4036     return TRUE;
4037   }
4038
4039   if (cf->is_tempfile && !cf->unsaved_changes) {
4040     /*
4041      * Temporary file with no unsaved changes, so we can just do a
4042      * raw binary copy.
4043      */
4044     return TRUE;
4045   }
4046
4047   /* Nothing to save. */
4048   return FALSE;
4049 }
4050
4051 /*
4052  * Should we let the user do a "save as"?
4053  *
4054  * That's true if:
4055  *
4056  *  we can save it in some format through Wiretap
4057  *
4058  * or
4059  *
4060  *  the file is a temporary file and has no unsaved changes (so
4061  *  that "saving" it just means copying it).
4062  *
4063  * XXX - we shouldn't allow files to be edited if they can't be saved,
4064  * so cf->unsaved_changes should be true only if the file can be saved.
4065  *
4066  * We don't care whether we support the comments in this file or not;
4067  * if we can't, we'll offer the user the option of discarding the
4068  * comments.
4069  */
4070 gboolean
4071 cf_can_save_as(capture_file *cf)
4072 {
4073   if (wtap_dump_can_write(cf->linktypes, 0)) {
4074     /* We can write it out with Wiretap. */
4075     return TRUE;
4076   }
4077
4078   if (cf->is_tempfile && !cf->unsaved_changes) {
4079     /*
4080      * Temporary file with no unsaved changes, so we can just do a
4081      * raw binary copy.
4082      */
4083     return TRUE;
4084   }
4085
4086   /* Nothing to save. */
4087   return FALSE;
4088 }
4089
4090 /*
4091  * Does this file have unsaved data?
4092  */
4093 gboolean
4094 cf_has_unsaved_data(capture_file *cf)
4095 {
4096   /*
4097    * If this is a temporary file, or a file with unsaved changes, it
4098    * has unsaved data.
4099    */
4100   return (cf->is_tempfile && cf->count>0) || cf->unsaved_changes;
4101 }
4102
4103 /*
4104  * Quick scan to find packet offsets.
4105  */
4106 static cf_read_status_t
4107 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile)
4108 {
4109   const struct wtap_pkthdr *phdr;
4110   int                  err;
4111   gchar               *err_info;
4112   gchar               *name_ptr;
4113   gint64               data_offset;
4114   progdlg_t           *progbar        = NULL;
4115   GTimer              *prog_timer = g_timer_new();
4116   gint64               size;
4117   float                progbar_val;
4118   GTimeVal             start_time;
4119   gchar                status_str[100];
4120   guint32              framenum;
4121   frame_data          *fdata;
4122   int                  count          = 0;
4123
4124   /* Close the old handle. */
4125   wtap_close(cf->provider.wth);
4126
4127   /* Open the new file. */
4128   /* XXX: this will go through all open_routines for a matching one. But right
4129      now rescan_file() is only used when a file is being saved to a different
4130      format than the original, and the user is not given a choice of which
4131      reader to use (only which format to save it in), so doing this makes
4132      sense for now. */
4133   cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4134   if (cf->provider.wth == NULL) {
4135     cfile_open_failure_alert_box(fname, err, err_info);
4136     return CF_READ_ERROR;
4137   }
4138
4139   /* We're scanning a file whose contents should be the same as what
4140      we had before, so we don't discard dissection state etc.. */
4141   cf->f_datalen = 0;
4142
4143   /* Set the file name because we need it to set the follow stream filter.
4144      XXX - is that still true?  We need it for other reasons, though,
4145      in any case. */
4146   cf->filename = g_strdup(fname);
4147
4148   /* Indicate whether it's a permanent or temporary file. */
4149   cf->is_tempfile = is_tempfile;
4150
4151   /* No user changes yet. */
4152   cf->unsaved_changes = FALSE;
4153
4154   cf->cd_t        = wtap_file_type_subtype(cf->provider.wth);
4155   cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4156
4157   cf->snap      = wtap_snapshot_length(cf->provider.wth);
4158
4159   name_ptr = g_filename_display_basename(cf->filename);
4160
4161   cf_callback_invoke(cf_cb_file_rescan_started, cf);
4162
4163   /* Record whether the file is compressed.
4164      XXX - do we know this at open time? */
4165   cf->iscompressed = wtap_iscompressed(cf->provider.wth);
4166
4167   /* Find the size of the file. */
4168   size = wtap_file_size(cf->provider.wth, NULL);
4169
4170   g_timer_start(prog_timer);
4171
4172   cf->stop_flag = FALSE;
4173   g_get_current_time(&start_time);
4174
4175   framenum = 0;
4176   phdr = wtap_phdr(cf->provider.wth);
4177   while ((wtap_read(cf->provider.wth, &err, &err_info, &data_offset))) {
4178     framenum++;
4179     fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4180     fdata->file_off = data_offset;
4181     if (size >= 0) {
4182       count++;
4183       cf->f_datalen = wtap_read_so_far(cf->provider.wth);
4184
4185       /* Create the progress bar if necessary. */
4186       if (progress_is_slow(progbar, prog_timer, size, cf->f_datalen)) {
4187         progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4188         progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4189                                               TRUE, &cf->stop_flag, &start_time, progbar_val);
4190       }
4191
4192       /*
4193        * Update the progress bar, but do it only after PROGBAR_UPDATE_INTERVAL
4194        * has elapsed. Calling update_progress_dlg and packets_bar_update will
4195        * likely trigger UI paint events, which might take a while depending on
4196        * the platform and display. Reset our timer *after* painting.
4197        */
4198       if (progbar && g_timer_elapsed(prog_timer, NULL) > PROGBAR_UPDATE_INTERVAL) {
4199         progbar_val = calc_progbar_val(cf, size, cf->f_datalen, status_str, sizeof(status_str));
4200         /* update the packet bar content on the first run or frequently on very large files */
4201         update_progress_dlg(progbar, progbar_val, status_str);
4202         compute_elapsed(cf, &start_time);
4203         packets_bar_update();
4204         g_timer_start(prog_timer);
4205       }
4206     }
4207
4208     if (cf->stop_flag) {
4209       /* Well, the user decided to abort the rescan.  Sadly, as this
4210          isn't a reread, recovering is difficult, so we'll just
4211          close the current capture. */
4212       break;
4213     }
4214
4215     /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4216        it's not already there.
4217        XXX - yes, this is O(N), so if every packet had a different
4218        link-layer encapsulation type, it'd be O(N^2) to read the file, but
4219        there are probably going to be a small number of encapsulation types
4220        in a file. */
4221     cf_add_encapsulation_type(cf, phdr->pkt_encap);
4222   }
4223
4224   /* Free the display name */
4225   g_free(name_ptr);
4226
4227   /* We're done reading the file; destroy the progress bar if it was created. */
4228   if (progbar != NULL)
4229     destroy_progress_dlg(progbar);
4230   g_timer_destroy(prog_timer);
4231
4232   /* We're done reading sequentially through the file. */
4233   cf->state = FILE_READ_DONE;
4234
4235   /* Close the sequential I/O side, to free up memory it requires. */
4236   wtap_sequential_close(cf->provider.wth);
4237
4238   /* compute the time it took to load the file */
4239   compute_elapsed(cf, &start_time);
4240
4241   /* Set the file encapsulation type now; we don't know what it is until
4242      we've looked at all the packets, as we don't know until then whether
4243      there's more than one type (and thus whether it's
4244      WTAP_ENCAP_PER_PACKET). */
4245   cf->lnk_t = wtap_file_encap(cf->provider.wth);
4246
4247   cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4248
4249   if (cf->stop_flag) {
4250     /* Our caller will give up at this point. */
4251     return CF_READ_ABORTED;
4252   }
4253
4254   if (err != 0) {
4255     /* Put up a message box noting that the read failed somewhere along
4256        the line.  Don't throw out the stuff we managed to read, though,
4257        if any. */
4258     cfile_read_failure_alert_box(NULL, err, err_info);
4259     return CF_READ_ERROR;
4260   } else
4261     return CF_READ_OK;
4262 }
4263
4264 cf_write_status_t
4265 cf_save_records(capture_file *cf, const char *fname, guint save_format,
4266                 gboolean compressed, gboolean discard_comments,
4267                 gboolean dont_reopen)
4268 {
4269   gchar           *err_info;
4270   gchar           *fname_new = NULL;
4271   wtap_dumper     *pdh;
4272   frame_data      *fdata;
4273   addrinfo_lists_t *addr_lists;
4274   guint            framenum;
4275   int              err;
4276 #ifdef _WIN32
4277   gchar           *display_basename;
4278 #endif
4279   enum {
4280      SAVE_WITH_MOVE,
4281      SAVE_WITH_COPY,
4282      SAVE_WITH_WTAP
4283   }                    how_to_save;
4284   save_callback_args_t callback_args;
4285   gboolean needs_reload = FALSE;
4286
4287   cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4288
4289   addr_lists = get_addrinfo_list();
4290
4291   if (save_format == cf->cd_t && compressed == cf->iscompressed
4292       && !discard_comments && !cf->unsaved_changes
4293       && (wtap_addrinfo_list_empty(addr_lists) || !wtap_dump_has_name_resolution(save_format))) {
4294     /* We're saving in the format it's already in, and we're not discarding
4295        comments, and there are no changes we have in memory that aren't saved
4296        to the file, and we have no name resolution information to write or
4297        the file format we're saving in doesn't support writing name
4298        resolution information, so we can just move or copy the raw data. */
4299
4300     if (cf->is_tempfile) {
4301       /* The file being saved is a temporary file from a live
4302          capture, so it doesn't need to stay around under that name;
4303          first, try renaming the capture buffer file to the new name.
4304          This acts as a "safe save", in that, if the file already
4305          exists, the existing file will be removed only if the rename
4306          succeeds.
4307
4308          Sadly, on Windows, as we have the current capture file
4309          open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4310          (to cause the rename to remove an existing target), as
4311          done by ws_stdio_rename() (ws_rename() is #defined to
4312          be ws_stdio_rename() on Windows) will fail.
4313
4314          According to the MSDN documentation for CreateFile(), if,
4315          when we open a capture file, we were to directly do a CreateFile(),
4316          opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4317          convert it to a file descriptor with _open_osfhandle(),
4318          that would allow the file to be renamed out from under us.
4319
4320          However, that doesn't work in practice.  Perhaps the problem
4321          is that the process doing the rename is the process that
4322          has the file open. */
4323 #ifndef _WIN32
4324       if (ws_rename(cf->filename, fname) == 0) {
4325         /* That succeeded - there's no need to copy the source file. */
4326         how_to_save = SAVE_WITH_MOVE;
4327       } else {
4328         if (errno == EXDEV) {
4329           /* They're on different file systems, so we have to copy the
4330              file. */
4331           how_to_save = SAVE_WITH_COPY;
4332         } else {
4333           /* The rename failed, but not because they're on different
4334              file systems - put up an error message.  (Or should we
4335              just punt and try to copy?  The only reason why I'd
4336              expect the rename to fail and the copy to succeed would
4337              be if we didn't have permission to remove the file from
4338              the temporary directory, and that might be fixable - but
4339              is it worth requiring the user to go off and fix it?) */
4340           cf_rename_failure_alert_box(fname, errno);
4341           goto fail;
4342         }
4343       }
4344 #else
4345       /* Windows - copy the file to its new location. */
4346       how_to_save = SAVE_WITH_COPY;
4347 #endif
4348     } else {
4349       /* It's a permanent file, so we should copy it, and not remove the
4350          original. */
4351       how_to_save = SAVE_WITH_COPY;
4352     }
4353
4354     if (how_to_save == SAVE_WITH_COPY) {
4355       /* Copy the file, if we haven't moved it.  If we're overwriting
4356          an existing file, we do it with a "safe save", by writing
4357          to a new file and, if the write succeeds, renaming the
4358          new file on top of the old file. */
4359       if (file_exists(fname)) {
4360         fname_new = g_strdup_printf("%s~", fname);
4361         if (!copy_file_binary_mode(cf->filename, fname_new))
4362           goto fail;
4363       } else {
4364         if (!copy_file_binary_mode(cf->filename, fname))
4365           goto fail;
4366       }
4367     }
4368   } else {
4369     /* Either we're saving in a different format or we're saving changes,
4370        such as added, modified, or removed comments, that haven't yet
4371        been written to the underlying file; we can't do that by copying
4372        or moving the capture file, we have to do it by writing the packets
4373        out in Wiretap. */
4374
4375     GArray                      *shb_hdrs = NULL;
4376     wtapng_iface_descriptions_t *idb_inf = NULL;
4377     GArray                      *nrb_hdrs = NULL;
4378     int encap;
4379
4380     /* XXX: what free's this shb_hdr? */
4381     shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4382     idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4383     nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4384
4385     /* Determine what file encapsulation type we should use. */
4386     encap = wtap_dump_file_encap_type(cf->linktypes);
4387
4388     if (file_exists(fname)) {
4389       /* We're overwriting an existing file; write out to a new file,
4390          and, if that succeeds, rename the new file on top of the
4391          old file.  That makes this a "safe save", so that we don't
4392          lose the old file if we have a problem writing out the new
4393          file.  (If the existing file is the current capture file,
4394          we *HAVE* to do that, otherwise we're overwriting the file
4395          from which we're reading the packets that we're writing!) */
4396       fname_new = g_strdup_printf("%s~", fname);
4397       pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4398                               compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4399     } else {
4400       pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4401                               compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4402     }
4403     g_free(idb_inf);
4404     idb_inf = NULL;
4405
4406     if (pdh == NULL) {
4407       cfile_dump_open_failure_alert_box(fname, err, save_format);
4408       goto fail;
4409     }
4410
4411     /* Add address resolution */
4412     wtap_dump_set_addrinfo_list(pdh, addr_lists);
4413
4414     /* Iterate through the list of packets, processing all the packets. */
4415     callback_args.pdh = pdh;
4416     callback_args.fname = fname;
4417     callback_args.file_type = save_format;
4418     switch (process_specified_records(cf, NULL, "Saving", "packets",
4419                                       TRUE, save_record, &callback_args, TRUE)) {
4420
4421     case PSP_FINISHED:
4422       /* Completed successfully. */
4423       break;
4424
4425     case PSP_STOPPED:
4426       /* The user decided to abort the saving.
4427          If we're writing to a temporary file, remove it.
4428          XXX - should we do so even if we're not writing to a
4429          temporary file? */
4430       wtap_dump_close(pdh, &err);
4431       if (fname_new != NULL)
4432         ws_unlink(fname_new);
4433       cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4434       return CF_WRITE_ABORTED;
4435
4436     case PSP_FAILED:
4437       /* Error while saving.
4438          If we're writing to a temporary file, remove it. */
4439       if (fname_new != NULL)
4440         ws_unlink(fname_new);
4441       wtap_dump_close(pdh, &err);
4442       goto fail;
4443     }
4444
4445     needs_reload = wtap_dump_get_needs_reload(pdh);
4446
4447     if (!wtap_dump_close(pdh, &err)) {
4448       cfile_close_failure_alert_box(fname, err);
4449       goto fail;
4450     }
4451
4452     how_to_save = SAVE_WITH_WTAP;
4453   }
4454
4455   if (fname_new != NULL) {
4456     /* We wrote out to fname_new, and should rename it on top of
4457        fname.  fname_new is now closed, so that should be possible even
4458        on Windows.  However, on Windows, we first need to close whatever
4459        file descriptors we have open for fname. */
4460 #ifdef _WIN32
4461     wtap_fdclose(cf->provider.wth);
4462 #endif
4463     /* Now do the rename. */
4464     if (ws_rename(fname_new, fname) == -1) {
4465       /* Well, the rename failed. */
4466       cf_rename_failure_alert_box(fname, errno);
4467 #ifdef _WIN32
4468       /* Attempt to reopen the random file descriptor using the
4469          current file's filename.  (At this point, the sequential
4470          file descriptor is closed.) */
4471       if (!wtap_fdreopen(cf->provider.wth, cf->filename, &err)) {
4472         /* Oh, well, we're screwed. */
4473         display_basename = g_filename_display_basename(cf->filename);
4474         simple_error_message_box(
4475                       file_open_error_message(err, FALSE), display_basename);
4476         g_free(display_basename);
4477       }
4478 #endif
4479       goto fail;
4480     }
4481   }
4482
4483   /* If this was a temporary file, and we didn't do the save by doing
4484      a move, so the tempoary file is still around under its old name,
4485      remove it. */
4486   if (cf->is_tempfile && how_to_save != SAVE_WITH_MOVE) {
4487     /* If this fails, there's not much we can do, so just ignore errors. */
4488     ws_unlink(cf->filename);
4489   }
4490
4491   cf_callback_invoke(cf_cb_file_save_finished, NULL);
4492   cf->unsaved_changes = FALSE;
4493
4494   if (!dont_reopen) {
4495     switch (how_to_save) {
4496
4497     case SAVE_WITH_MOVE:
4498       /* We just moved the file, so the wtap structure refers to the
4499          new file, and all the information other than the filename
4500          and the "is temporary" status applies to the new file; just
4501          update that. */
4502       g_free(cf->filename);
4503       cf->filename = g_strdup(fname);
4504       cf->is_tempfile = FALSE;
4505       cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4506       break;
4507
4508     case SAVE_WITH_COPY:
4509       /* We just copied the file, so all the information other than
4510          the wtap structure, the filename, and the "is temporary"
4511          status applies to the new file; just update that. */
4512       wtap_close(cf->provider.wth);
4513       /* Although we're just "copying" and then opening the copy, it will
4514          try all open_routine readers to open the copy, so we need to
4515          reset the cfile's open_type. */
4516       cf->open_type = WTAP_TYPE_AUTO;
4517       cf->provider.wth = wtap_open_offline(fname, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
4518       if (cf->provider.wth == NULL) {
4519         cfile_open_failure_alert_box(fname, err, err_info);
4520         cf_close(cf);
4521       } else {
4522         g_free(cf->filename);
4523         cf->filename = g_strdup(fname);
4524         cf->is_tempfile = FALSE;
4525       }
4526       cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4527       break;
4528
4529     case SAVE_WITH_WTAP:
4530       /* Open and read the file we saved to.
4531
4532          XXX - this is somewhat of a waste; we already have the
4533          packets, all this gets us is updated file type information
4534          (which we could just stuff into "cf"), and having the new
4535          file be the one we have opened and from which we're reading
4536          the data, and it means we have to spend time opening and
4537          reading the file, which could be a significant amount of
4538          time if the file is large.
4539
4540          If the capture-file-writing code were to return the
4541          seek offset of each packet it writes, we could save that
4542          in the frame_data structure for the frame, and just open
4543          the file without reading it again...
4544
4545          ...as long as, for gzipped files, the process of writing
4546          out the file *also* generates the information needed to
4547          support fast random access to the compressed file. */
4548       /* rescan_file will cause us to try all open_routines, so
4549          reset cfile's open_type */
4550       cf->open_type = WTAP_TYPE_AUTO;
4551       /* There are cases when SAVE_WITH_WTAP can result in new packets
4552          being written to the file, e.g ERF records
4553          In that case, we need to reload the whole file */
4554       if(needs_reload) {
4555         if (cf_open(cf, fname, WTAP_TYPE_AUTO, FALSE, &err) == CF_OK) {
4556           if (cf_read(cf, TRUE) != CF_READ_OK) {
4557              /* The rescan failed; just close the file.  Either
4558                a dialog was popped up for the failure, so the
4559                user knows what happened, or they stopped the
4560                rescan, in which case they know what happened.  */
4561             /* XXX: This is inconsistent with normal open/reload behaviour. */
4562             cf_close(cf);
4563           }
4564         }
4565       }
4566       else {
4567         if (rescan_file(cf, fname, FALSE) != CF_READ_OK) {
4568            /* The rescan failed; just close the file.  Either
4569              a dialog was popped up for the failure, so the
4570              user knows what happened, or they stopped the
4571              rescan, in which case they know what happened.  */
4572           cf_close(cf);
4573         }
4574       }
4575       break;
4576     }
4577
4578     /* If we were told to discard the comments, do so. */
4579     if (discard_comments) {
4580       /* Remove SHB comment, if any. */
4581       wtap_write_shb_comment(cf->provider.wth, NULL);
4582
4583       /* remove all user comments */
4584       for (framenum = 1; framenum <= cf->count; framenum++) {
4585         fdata = frame_data_sequence_find(cf->provider.frames, framenum);
4586
4587         fdata->flags.has_phdr_comment = FALSE;
4588         fdata->flags.has_user_comment = FALSE;
4589       }
4590
4591       if (cf->provider.frames_user_comments) {
4592         g_tree_destroy(cf->provider.frames_user_comments);
4593         cf->provider.frames_user_comments = NULL;
4594       }
4595
4596       cf->packet_comment_count = 0;
4597     }
4598   }
4599   return CF_WRITE_OK;
4600
4601 fail:
4602   if (fname_new != NULL) {
4603     /* We were trying to write to a temporary file; get rid of it if it
4604        exists.  (We don't care whether this fails, as, if it fails,
4605        there's not much we can do about it.  I guess if it failed for
4606        a reason other than "it doesn't exist", we could report an
4607        error, so the user knows there's a junk file that they might
4608        want to clean up.) */
4609     ws_unlink(fname_new);
4610     g_free(fname_new);
4611   }
4612   cf_callback_invoke(cf_cb_file_save_failed, NULL);
4613   return CF_WRITE_ERROR;
4614 }
4615
4616 cf_write_status_t
4617 cf_export_specified_packets(capture_file *cf, const char *fname,
4618                             packet_range_t *range, guint save_format,
4619                             gboolean compressed)
4620 {
4621   gchar                       *fname_new = NULL;
4622   int                          err;
4623   wtap_dumper                 *pdh;
4624   save_callback_args_t         callback_args;
4625   GArray                      *shb_hdrs = NULL;
4626   wtapng_iface_descriptions_t *idb_inf = NULL;
4627   GArray                      *nrb_hdrs = NULL;
4628   int                          encap;
4629
4630   cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4631
4632   packet_range_process_init(range);
4633
4634   /* We're writing out specified packets from the specified capture
4635      file to another file.  Even if all captured packets are to be
4636      written, don't special-case the operation - read each packet
4637      and then write it out if it's one of the specified ones. */
4638
4639   /* XXX: what free's this shb_hdr? */
4640   shb_hdrs = wtap_file_get_shb_for_new_file(cf->provider.wth);
4641   idb_inf = wtap_file_get_idb_info(cf->provider.wth);
4642   nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->provider.wth);
4643
4644   /* Determine what file encapsulation type we should use. */
4645   encap = wtap_dump_file_encap_type(cf->linktypes);
4646
4647   if (file_exists(fname)) {
4648     /* We're overwriting an existing file; write out to a new file,
4649        and, if that succeeds, rename the new file on top of the
4650        old file.  That makes this a "safe save", so that we don't
4651        lose the old file if we have a problem writing out the new
4652        file.  (If the existing file is the current capture file,
4653        we *HAVE* to do that, otherwise we're overwriting the file
4654        from which we're reading the packets that we're writing!) */
4655     fname_new = g_strdup_printf("%s~", fname);
4656     pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4657                             compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4658   } else {
4659     pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4660                             compressed, shb_hdrs, idb_inf, nrb_hdrs, &err);
4661   }
4662   g_free(idb_inf);
4663   idb_inf = NULL;
4664
4665   if (pdh == NULL) {
4666     cfile_dump_open_failure_alert_box(fname, err, save_format);
4667     goto fail;
4668   }
4669
4670   /* Add address resolution */
4671   wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4672
4673   /* Iterate through the list of packets, processing the packets we were
4674      told to process.
4675
4676      XXX - we've already called "packet_range_process_init(range)", but
4677      "process_specified_records()" will do it again.  Fortunately,
4678      that's harmless in this case, as we haven't done anything to
4679      "range" since we initialized it. */
4680   callback_args.pdh = pdh;
4681   callback_args.fname = fname;
4682   callback_args.file_type = save_format;
4683   switch (process_specified_records(cf, range, "Writing", "specified records",
4684                                     TRUE, save_record, &callback_args, TRUE)) {
4685
4686   case PSP_FINISHED:
4687     /* Completed successfully. */
4688     break;
4689
4690   case PSP_STOPPED:
4691       /* The user decided to abort the saving.
4692          If we're writing to a temporary file, remove it.
4693          XXX - should we do so even if we're not writing to a
4694          temporary file? */
4695       wtap_dump_close(pdh, &err);
4696       if (fname_new != NULL)
4697         ws_unlink(fname_new);
4698       cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4699       return CF_WRITE_ABORTED;
4700     break;
4701
4702   case PSP_FAILED:
4703     /* Error while saving.
4704        If we're writing to a temporary file, remove it. */
4705     if (fname_new != NULL)
4706       ws_unlink(fname_new);
4707     wtap_dump_close(pdh, &err);
4708     goto fail;
4709   }
4710
4711   if (!wtap_dump_close(pdh, &err)) {
4712     cfile_close_failure_alert_box(fname, err);
4713     goto fail;
4714   }
4715
4716   if (fname_new != NULL) {
4717     /* We wrote out to fname_new, and should rename it on top of
4718        fname; fname is now closed, so that should be possible even
4719        on Windows.  Do the rename. */
4720     if (ws_rename(fname_new, fname) == -1) {
4721       /* Well, the rename failed. */
4722       cf_rename_failure_alert_box(fname, errno);
4723       goto fail;
4724     }
4725   }
4726
4727   cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4728   return CF_WRITE_OK;
4729
4730 fail:
4731   if (fname_new != NULL) {
4732     /* We were trying to write to a temporary file; get rid of it if it
4733        exists.  (We don't care whether this fails, as, if it fails,
4734        there's not much we can do about it.  I guess if it failed for
4735        a reason other than "it doesn't exist", we could report an
4736        error, so the user knows there's a junk file that they might
4737        want to clean up.) */
4738     ws_unlink(fname_new);
4739     g_free(fname_new);
4740   }
4741   cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4742   return CF_WRITE_ERROR;
4743 }
4744
4745 /*
4746  * XXX - whether we mention the source pathname, the target pathname,
4747  * or both depends on the error and on what we find if we look for
4748  * one or both of them.
4749  */
4750 static void
4751 cf_rename_failure_alert_box(const char *filename, int err)
4752 {
4753   gchar *display_basename;
4754
4755   display_basename = g_filename_display_basename(filename);
4756   switch (err) {
4757
4758   case ENOENT:
4759     /* XXX - should check whether the source exists and, if not,
4760        report it as the problem and, if so, report the destination
4761        as the problem. */
4762     simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4763                              display_basename);
4764     break;
4765
4766   case EACCES:
4767     /* XXX - if we're doing a rename after a safe save, we should
4768        probably say something else. */
4769     simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4770                              display_basename);
4771     break;
4772
4773   default:
4774     /* XXX - this should probably mention both the source and destination
4775        pathnames. */
4776     simple_error_message_box("The file \"%s\" could not be moved: %s.",
4777                              display_basename, wtap_strerror(err));
4778     break;
4779   }
4780   g_free(display_basename);
4781 }
4782
4783 /* Reload the current capture file. */
4784 void
4785 cf_reload(capture_file *cf) {
4786   gchar    *filename;
4787   gboolean  is_tempfile;
4788   int       err;
4789
4790   /* If the file could be opened, "cf_open()" calls "cf_close()"
4791      to get rid of state for the old capture file before filling in state
4792      for the new capture file.  "cf_close()" will remove the file if
4793      it's a temporary file; we don't want that to happen (for one thing,
4794      it'd prevent subsequent reopens from working).  Remember whether it's
4795      a temporary file, mark it as not being a temporary file, and then
4796      reopen it as the type of file it was.
4797
4798      Also, "cf_close()" will free "cf->filename", so we must make
4799      a copy of it first. */
4800   filename = g_strdup(cf->filename);
4801   is_tempfile = cf->is_tempfile;
4802   cf->is_tempfile = FALSE;
4803   if (cf_open(cf, filename, cf->open_type, is_tempfile, &err) == CF_OK) {
4804     switch (cf_read(cf, TRUE)) {
4805
4806     case CF_READ_OK:
4807     case CF_READ_ERROR:
4808       /* Just because we got an error, that doesn't mean we were unable
4809          to read any of the file; we handle what we could get from the
4810          file. */
4811       break;
4812
4813     case CF_READ_ABORTED:
4814       /* The user bailed out of re-reading the capture file; the
4815          capture file has been closed - just free the capture file name
4816          string and return (without changing the last containing
4817          directory). */
4818       g_free(filename);
4819       return;
4820     }
4821   } else {
4822     /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
4823        Instead, the file was left open, so we should restore "cf->is_tempfile"
4824        ourselves.
4825
4826        XXX - change the menu?  Presumably "cf_open()" will do that;
4827        make sure it does! */
4828     cf->is_tempfile = is_tempfile;
4829   }
4830   /* "cf_open()" made a copy of the file name we handed it, so
4831      we should free up our copy. */
4832   g_free(filename);
4833 }
4834
4835 /*
4836  * Editor modelines
4837  *
4838  * Local Variables:
4839  * c-basic-offset: 2
4840  * tab-width: 8
4841  * indent-tabs-mode: nil
4842  * End:
4843  *
4844  * ex: set shiftwidth=2 tabstop=8 expandtab:
4845  * :indentSize=2:tabSize=8:noTabs=true:
4846  */