Move some variables inside TRY { } block.
[metze/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * $Id$
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include "config.h"
26
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
30
31 #include <time.h>
32
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <signal.h>
39
40 #ifdef HAVE_FCNTL_H
41 #include <fcntl.h>
42 #endif
43
44 #include <epan/epan.h>
45 #include <epan/filesystem.h>
46
47 #include "color.h"
48 #include "color_filters.h"
49 #include "cfile.h"
50 #include <epan/column.h>
51 #include <epan/packet.h>
52 #include <epan/column-utils.h>
53 #include "packet-range.h"
54 #include "print.h"
55 #include "file.h"
56 #include "fileset.h"
57 #include "tempfile.h"
58 #include "merge.h"
59
60 #include <epan/prefs.h>
61 #include <epan/dfilter/dfilter.h>
62 #include <epan/epan_dissect.h>
63 #include <epan/tap.h>
64 #include <epan/dissectors/packet-data.h>
65 #include <epan/dissectors/packet-ber.h>
66 #include <epan/timestamp.h>
67 #include <epan/dfilter/dfilter-macro.h>
68 #include <wsutil/file_util.h>
69 #include <epan/strutil.h>
70 #include <epan/addr_resolv.h>
71
72 #include "ui/alert_box.h"
73 #include "ui/simple_dialog.h"
74 #include "ui/main_statusbar.h"
75 #include "ui/progress_dlg.h"
76 #include "ui/ui_util.h"
77
78 #ifdef HAVE_LIBPCAP
79 gboolean auto_scroll_live;
80 #endif
81
82 static guint32 cum_bytes;
83 static nstime_t first_ts;
84 static frame_data *prev_dis;
85 static frame_data *prev_cap;
86
87 static gulong computed_elapsed;
88
89 static void cf_reset_state(capture_file *cf);
90
91 static int read_packet(capture_file *cf, dfilter_t *dfcode,
92     epan_dissect_t *edt, column_info *cinfo, gint64 offset);
93
94 static void rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect);
95
96 typedef enum {
97   MR_NOTMATCHED,
98   MR_MATCHED,
99   MR_ERROR
100 } match_result;
101 static match_result match_protocol_tree(capture_file *cf, frame_data *fdata,
102     void *criterion);
103 static void match_subtree_text(proto_node *node, gpointer data);
104 static match_result match_summary_line(capture_file *cf, frame_data *fdata,
105     void *criterion);
106 static match_result match_ascii_and_unicode(capture_file *cf, frame_data *fdata,
107     void *criterion);
108 static match_result match_ascii(capture_file *cf, frame_data *fdata,
109     void *criterion);
110 static match_result match_unicode(capture_file *cf, frame_data *fdata,
111     void *criterion);
112 static match_result match_binary(capture_file *cf, frame_data *fdata,
113     void *criterion);
114 static match_result match_dfilter(capture_file *cf, frame_data *fdata,
115     void *criterion);
116 static match_result match_marked(capture_file *cf, frame_data *fdata,
117     void *criterion);
118 static match_result match_time_reference(capture_file *cf, frame_data *fdata,
119     void *criterion);
120 static gboolean find_packet(capture_file *cf,
121     match_result (*match_function)(capture_file *, frame_data *, void *),
122     void *criterion, search_direction dir);
123
124 static void cf_open_failure_alert_box(const char *filename, int err,
125                       gchar *err_info, gboolean for_writing,
126                       int file_type);
127 static void cf_rename_failure_alert_box(const char *filename, int err);
128 static void cf_close_failure_alert_box(const char *filename, int err);
129 static void ref_time_packets(capture_file *cf);
130 /* Update the progress bar this many times when reading a file. */
131 #define N_PROGBAR_UPDATES   100
132 /* We read around 200k/100ms don't update the progress bar more often than that */
133 #define MIN_QUANTUM         200000
134 #define MIN_NUMBER_OF_PACKET 1500
135
136 /*
137  * We could probably use g_signal_...() instead of the callbacks below but that
138  * would require linking our CLI programs to libgobject and creating an object
139  * instance for the signals.
140  */
141 typedef struct {
142   cf_callback_t cb_fct;
143   gpointer      user_data;
144 } cf_callback_data_t;
145
146 static GList *cf_callbacks = NULL;
147
148 static void
149 cf_callback_invoke(int event, gpointer data)
150 {
151   cf_callback_data_t *cb;
152   GList              *cb_item = cf_callbacks;
153
154   /* there should be at least one interested */
155   g_assert(cb_item != NULL);
156
157   while (cb_item != NULL) {
158     cb = cb_item->data;
159     cb->cb_fct(event, data, cb->user_data);
160     cb_item = g_list_next(cb_item);
161   }
162 }
163
164
165 void
166 cf_callback_add(cf_callback_t func, gpointer user_data)
167 {
168   cf_callback_data_t *cb;
169
170   cb = g_malloc(sizeof(cf_callback_data_t));
171   cb->cb_fct = func;
172   cb->user_data = user_data;
173
174   cf_callbacks = g_list_append(cf_callbacks, cb);
175 }
176
177 void
178 cf_callback_remove(cf_callback_t func)
179 {
180   cf_callback_data_t *cb;
181   GList              *cb_item = cf_callbacks;
182
183   while (cb_item != NULL) {
184     cb = cb_item->data;
185     if (cb->cb_fct == func) {
186       cf_callbacks = g_list_remove(cf_callbacks, cb);
187       g_free(cb);
188       return;
189     }
190     cb_item = g_list_next(cb_item);
191   }
192
193   g_assert_not_reached();
194 }
195
196 void
197 cf_timestamp_auto_precision(capture_file *cf)
198 {
199   int i;
200   int prec = timestamp_get_precision();
201
202
203   /* don't try to get the file's precision if none is opened */
204   if (cf->state == FILE_CLOSED) {
205     return;
206   }
207
208   /* if we are in auto mode, set precision of current file */
209   if (prec == TS_PREC_AUTO ||
210      prec == TS_PREC_AUTO_SEC ||
211      prec == TS_PREC_AUTO_DSEC ||
212      prec == TS_PREC_AUTO_CSEC ||
213      prec == TS_PREC_AUTO_MSEC ||
214      prec == TS_PREC_AUTO_USEC ||
215      prec == TS_PREC_AUTO_NSEC)
216   {
217     switch(wtap_file_tsprecision(cf->wth)) {
218     case(WTAP_FILE_TSPREC_SEC):
219       timestamp_set_precision(TS_PREC_AUTO_SEC);
220       break;
221     case(WTAP_FILE_TSPREC_DSEC):
222       timestamp_set_precision(TS_PREC_AUTO_DSEC);
223       break;
224     case(WTAP_FILE_TSPREC_CSEC):
225       timestamp_set_precision(TS_PREC_AUTO_CSEC);
226       break;
227     case(WTAP_FILE_TSPREC_MSEC):
228       timestamp_set_precision(TS_PREC_AUTO_MSEC);
229       break;
230     case(WTAP_FILE_TSPREC_USEC):
231       timestamp_set_precision(TS_PREC_AUTO_USEC);
232       break;
233     case(WTAP_FILE_TSPREC_NSEC):
234       timestamp_set_precision(TS_PREC_AUTO_NSEC);
235       break;
236     default:
237       g_assert_not_reached();
238     }
239   }
240   /* Set the column widths of those columns that show the time in
241      "command-line-specified" format. */
242   for (i = 0; i < cf->cinfo.num_cols; i++) {
243     if (col_has_time_fmt(&cf->cinfo, i)) {
244       packet_list_resize_column(i);
245     }
246   }
247 }
248
249 gulong
250 cf_get_computed_elapsed(void)
251 {
252   return computed_elapsed;
253 }
254
255 static void reset_elapsed(void)
256 {
257   computed_elapsed = 0;
258 }
259
260 /*
261  * GLIB_CHECK_VERSION(2,28,0) adds g_get_real_time which could minimize or
262  * replace this
263  */
264 static void compute_elapsed(GTimeVal *start_time)
265 {
266   gdouble  delta_time;
267   GTimeVal time_now;
268
269   g_get_current_time(&time_now);
270
271   delta_time = (time_now.tv_sec - start_time->tv_sec) * 1e6 +
272     time_now.tv_usec - start_time->tv_usec;
273
274   computed_elapsed = (gulong) (delta_time / 1000); /* ms */
275 }
276
277 cf_status_t
278 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
279 {
280   wtap  *wth;
281   gchar *err_info;
282
283   wth = wtap_open_offline(fname, err, &err_info, TRUE);
284   if (wth == NULL)
285     goto fail;
286
287   /* The open succeeded.  Close whatever capture file we had open,
288      and fill in the information for this file. */
289   cf_close(cf);
290
291   /* Cleanup all data structures used for dissection. */
292   cleanup_dissection();
293   /* Initialize all data structures used for dissection. */
294   init_dissection();
295
296   /* We're about to start reading the file. */
297   cf->state = FILE_READ_IN_PROGRESS;
298
299   cf->wth = wth;
300   cf->f_datalen = 0;
301
302   /* Set the file name because we need it to set the follow stream filter.
303      XXX - is that still true?  We need it for other reasons, though,
304      in any case. */
305   cf->filename = g_strdup(fname);
306
307   /* Indicate whether it's a permanent or temporary file. */
308   cf->is_tempfile = is_tempfile;
309
310   /* No user changes yet. */
311   cf->unsaved_changes = FALSE;
312
313   reset_elapsed();
314
315   cf->cd_t        = wtap_file_type(cf->wth);
316   cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
317   cf->count     = 0;
318   cf->packet_comment_count = 0;
319   cf->displayed_count = 0;
320   cf->marked_count = 0;
321   cf->ignored_count = 0;
322   cf->ref_time_count = 0;
323   cf->drops_known = FALSE;
324   cf->drops     = 0;
325   cf->snap      = wtap_snapshot_length(cf->wth);
326   if (cf->snap == 0) {
327     /* Snapshot length not known. */
328     cf->has_snap = FALSE;
329     cf->snap = WTAP_MAX_PACKET_SIZE;
330   } else
331     cf->has_snap = TRUE;
332
333   /* Allocate a frame_data_sequence for the frames in this file */
334   cf->frames = new_frame_data_sequence();
335
336   nstime_set_zero(&cf->elapsed_time);
337   nstime_set_unset(&first_ts);
338   prev_dis = NULL;
339   prev_cap = NULL;
340   cum_bytes = 0;
341
342   /* Adjust timestamp precision if auto is selected, col width will be adjusted */
343   cf_timestamp_auto_precision(cf);
344   /* XXX needed ? */
345   packet_list_queue_draw();
346   cf_callback_invoke(cf_cb_file_opened, cf);
347
348   if (cf->cd_t == WTAP_FILE_BER) {
349     /* tell the BER dissector the file name */
350     ber_set_filename(cf->filename);
351   }
352
353   wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
354   wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
355
356   return CF_OK;
357
358 fail:
359   cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
360   return CF_ERROR;
361 }
362
363 /*
364  * Add an encapsulation type to cf->linktypes.
365  */
366 void
367 cf_add_encapsulation_type(capture_file *cf, int encap)
368 {
369   guint i;
370
371   for (i = 0; i < cf->linktypes->len; i++) {
372     if (g_array_index(cf->linktypes, gint, i) == encap)
373       return; /* it's already there */
374   }
375   /* It's not already there - add it. */
376   g_array_append_val(cf->linktypes, encap);
377 }
378
379 /*
380  * Reset the state for the currently closed file, but don't do the
381  * UI callbacks; this is for use in "cf_open()", where we don't
382  * want the UI to go from "file open" to "file closed" back to
383  * "file open", we want it to go from "old file open" to "new file
384  * open and being read".
385  *
386  * XXX - currently, cf_open() calls cf_close(), rather than
387  * cf_reset_state().
388  */
389 static void
390 cf_reset_state(capture_file *cf)
391 {
392   /* Die if we're in the middle of reading a file. */
393   g_assert(cf->state != FILE_READ_IN_PROGRESS);
394
395   if (cf->wth) {
396     wtap_close(cf->wth);
397     cf->wth = NULL;
398   }
399   /* We have no file open... */
400   if (cf->filename != NULL) {
401     /* If it's a temporary file, remove it. */
402     if (cf->is_tempfile)
403       ws_unlink(cf->filename);
404     g_free(cf->filename);
405     cf->filename = NULL;
406   }
407   /* ...which means we have no changes to that file to save. */
408   cf->unsaved_changes = FALSE;
409
410   dfilter_free(cf->rfcode);
411   cf->rfcode = NULL;
412   if (cf->frames != NULL) {
413     free_frame_data_sequence(cf->frames);
414     cf->frames = NULL;
415   }
416 #ifdef WANT_PACKET_EDITOR
417   if (cf->edited_frames) {
418     g_tree_destroy(cf->edited_frames);
419     cf->edited_frames = NULL;
420   }
421 #endif
422   cf_unselect_packet(cf);   /* nothing to select */
423   cf->first_displayed = 0;
424   cf->last_displayed = 0;
425
426   /* No frames, no frame selected, no field in that frame selected. */
427   cf->count = 0;
428   cf->current_frame = 0;
429   cf->current_row = 0;
430   cf->finfo_selected = NULL;
431
432   /* No frame link-layer types, either. */
433   g_array_free(cf->linktypes, TRUE);
434   cf->linktypes = NULL;
435
436   /* Clear the packet list. */
437   packet_list_freeze();
438   packet_list_clear();
439   packet_list_thaw();
440
441   cf->f_datalen = 0;
442   nstime_set_zero(&cf->elapsed_time);
443
444   reset_tap_listeners();
445
446   /* We have no file open. */
447   cf->state = FILE_CLOSED;
448 }
449
450 /* Reset everything to a pristine state */
451 void
452 cf_close(capture_file *cf)
453 {
454   if (cf->state != FILE_CLOSED) {
455     cf_callback_invoke(cf_cb_file_closing, cf);
456
457   /* close things, if not already closed before */
458     color_filters_cleanup();
459     cf_reset_state(cf);
460     cleanup_dissection();
461
462     cf_callback_invoke(cf_cb_file_closed, cf);
463   }
464 }
465
466 static float
467 calc_progbar_val(capture_file *cf, gint64 size, gint64 file_pos, gchar *status_str, gulong status_size)
468 {
469   float progbar_val;
470
471   progbar_val = (gfloat) file_pos / (gfloat) size;
472   if (progbar_val > 1.0) {
473
474     /*  The file probably grew while we were reading it.
475      *  Update file size, and try again.
476      */
477     size = wtap_file_size(cf->wth, NULL);
478
479     if (size >= 0)
480       progbar_val = (gfloat) file_pos / (gfloat) size;
481
482     /*  If it's still > 1, either "wtap_file_size()" failed (in which
483      *  case there's not much we can do about it), or the file
484      *  *shrank* (in which case there's not much we can do about
485      *  it); just clip the progress value at 1.0.
486      */
487     if (progbar_val > 1.0f)
488       progbar_val = 1.0f;
489   }
490
491   g_snprintf(status_str, status_size,
492              "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
493              file_pos / 1024, size / 1024);
494
495   return progbar_val;
496 }
497
498 static void
499 epan_dissect_finish(epan_dissect_t *edt)
500 {
501         if (edt->tree)
502                 proto_tree_free(edt->tree);
503 }
504
505 cf_read_status_t
506 cf_read(capture_file *cf, gboolean reloading)
507 {
508   int                  err;
509   gchar               *err_info;
510   gchar               *name_ptr;
511   progdlg_t           *progbar        = NULL;
512   gboolean             stop_flag;
513   GTimeVal             start_time;
514   gchar                status_str[100];
515   dfilter_t           *dfcode;
516   column_info         *cinfo;
517   epan_dissect_t       edt;
518   gboolean             create_proto_tree;
519   guint                tap_flags;
520   gboolean             compiled;
521
522   /* Compile the current display filter.
523    * We assume this will not fail since cf->dfilter is only set in
524    * cf_filter IFF the filter was valid.
525    */
526   compiled = dfilter_compile(cf->dfilter, &dfcode);
527   g_assert(!cf->dfilter || (compiled && dfcode));
528
529   /* Get the union of the flags for all tap listeners. */
530   tap_flags = union_of_tap_listener_flags();
531   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
532   create_proto_tree =
533     (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
534   epan_dissect_init(&edt, create_proto_tree, FALSE);
535   if (dfcode != NULL)
536     epan_dissect_prime_dfilter(&edt, dfcode);
537
538   reset_tap_listeners();
539
540   name_ptr = g_filename_display_basename(cf->filename);
541
542   if (reloading)
543     cf_callback_invoke(cf_cb_file_reload_started, cf);
544   else
545     cf_callback_invoke(cf_cb_file_read_started, cf);
546
547   /* Record whether the file is compressed.
548      XXX - do we know this at open time? */
549   cf->iscompressed = wtap_iscompressed(cf->wth);
550
551   /* The packet list window will be empty until the file is completly loaded */
552   packet_list_freeze();
553
554   stop_flag = FALSE;
555   g_get_current_time(&start_time);
556
557   TRY {
558 #ifdef HAVE_LIBPCAP
559     int     displayed_once    = 0;
560 #endif
561     int     count             = 0;
562
563     gint64  size;
564     gint64  file_pos;
565     gint64  data_offset;
566
567     gint64  progbar_quantum;
568     gint64  progbar_nextstep;
569     float   progbar_val;
570
571     /* Find the size of the file. */
572     size = wtap_file_size(cf->wth, NULL);
573
574     /* Update the progress bar when it gets to this value. */
575     progbar_nextstep = 0;
576     /* When we reach the value that triggers a progress bar update,
577        bump that value by this amount. */
578     if (size >= 0) {
579       progbar_quantum = size/N_PROGBAR_UPDATES;
580       if (progbar_quantum < MIN_QUANTUM)
581         progbar_quantum = MIN_QUANTUM;
582     }else
583       progbar_quantum = 0;
584     /* Progress so far. */
585     progbar_val = 0.0f;
586
587     while ((wtap_read(cf->wth, &err, &err_info, &data_offset))) {
588       if (size >= 0) {
589         count++;
590         file_pos = wtap_read_so_far(cf->wth);
591
592         /* Create the progress bar if necessary.
593          * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
594          */
595         if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
596           progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
597           if (reloading)
598             progbar = delayed_create_progress_dlg(cf->window, "Reloading", name_ptr,
599                 TRUE, &stop_flag, &start_time, progbar_val);
600           else
601             progbar = delayed_create_progress_dlg(cf->window, "Loading", name_ptr,
602                 TRUE, &stop_flag, &start_time, progbar_val);
603         }
604
605         /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
606            when we update it, we have to run the GTK+ main loop to get it
607            to repaint what's pending, and doing so may involve an "ioctl()"
608            to see if there's any pending input from an X server, and doing
609            that for every packet can be costly, especially on a big file. */
610         if (file_pos >= progbar_nextstep) {
611           if (progbar != NULL) {
612             progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
613             /* update the packet bar content on the first run or frequently on very large files */
614 #ifdef HAVE_LIBPCAP
615             if (progbar_quantum > 500000 || displayed_once == 0) {
616               if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
617                 displayed_once = 1;
618                 packets_bar_update();
619               }
620             }
621 #endif /* HAVE_LIBPCAP */
622             update_progress_dlg(progbar, progbar_val, status_str);
623           }
624           progbar_nextstep += progbar_quantum;
625         }
626       }
627
628       if (stop_flag) {
629         /* Well, the user decided to abort the read. He/She will be warned and
630            it might be enough for him/her to work with the already loaded
631            packets.
632            This is especially true for very large capture files, where you don't
633            want to wait loading the whole file (which may last minutes or even
634            hours even on fast machines) just to see that it was the wrong file. */
635         break;
636       }
637       read_packet(cf, dfcode, &edt, cinfo, data_offset);
638     } 
639   }
640   CATCH(OutOfMemoryError) {
641     simple_message_box(ESD_TYPE_ERROR, NULL,
642                    "Some infos / workarounds can be found at:\n"
643                    "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
644                    "Sorry, but Wireshark has run out of memory and has to terminate now!");
645 #if 0
646     /* Could we close the current capture and free up memory from that? */
647 #else
648     /* we have to terminate, as we cannot recover from the memory error */
649     exit(1);
650 #endif
651   }
652   ENDTRY;
653   epan_dissect_finish(&edt);
654
655   /* Free the display name */
656   g_free(name_ptr);
657
658   /* Cleanup and release all dfilter resources */
659   if (dfcode != NULL) {
660     dfilter_free(dfcode);
661   }
662
663   /* We're done reading the file; destroy the progress bar if it was created. */
664   if (progbar != NULL)
665     destroy_progress_dlg(progbar);
666
667   /* We're done reading sequentially through the file. */
668   cf->state = FILE_READ_DONE;
669
670   /* Close the sequential I/O side, to free up memory it requires. */
671   wtap_sequential_close(cf->wth);
672
673   /* Allow the protocol dissectors to free up memory that they
674    * don't need after the sequential run-through of the packets. */
675   postseq_cleanup_all_protocols();
676
677   /* compute the time it took to load the file */
678   compute_elapsed(&start_time);
679
680   /* Set the file encapsulation type now; we don't know what it is until
681      we've looked at all the packets, as we don't know until then whether
682      there's more than one type (and thus whether it's
683      WTAP_ENCAP_PER_PACKET). */
684   cf->lnk_t = wtap_file_encap(cf->wth);
685
686   cf->current_frame = frame_data_sequence_find(cf->frames, cf->first_displayed);
687   cf->current_row = 0;
688
689   packet_list_thaw();
690   if (reloading)
691     cf_callback_invoke(cf_cb_file_reload_finished, cf);
692   else
693     cf_callback_invoke(cf_cb_file_read_finished, cf);
694
695   /* If we have any displayed packets to select, select the first of those
696      packets by making the first row the selected row. */
697   if (cf->first_displayed != 0) {
698     packet_list_select_first_row();
699   }
700
701   if (stop_flag) {
702     simple_message_box(ESD_TYPE_WARN, NULL,
703                   "The remaining packets in the file were discarded.\n"
704                   "\n"
705                   "As a lot of packets from the original file will be missing,\n"
706                   "remember to be careful when saving the current content to a file.\n",
707                   "File loading was cancelled!");
708     return CF_READ_ERROR;
709   }
710
711   if (err != 0) {
712     /* Put up a message box noting that the read failed somewhere along
713        the line.  Don't throw out the stuff we managed to read, though,
714        if any. */
715     switch (err) {
716
717     case WTAP_ERR_UNSUPPORTED:
718       simple_error_message_box(
719                  "The capture file contains record data that Wireshark doesn't support.\n(%s)",
720                  err_info);
721       g_free(err_info);
722       break;
723
724     case WTAP_ERR_UNSUPPORTED_ENCAP:
725       simple_error_message_box(
726                  "The capture file has a packet with a network type that Wireshark doesn't support.\n(%s)",
727                  err_info);
728       g_free(err_info);
729       break;
730
731     case WTAP_ERR_CANT_READ:
732       simple_error_message_box(
733                  "An attempt to read from the capture file failed for"
734                  " some unknown reason.");
735       break;
736
737     case WTAP_ERR_SHORT_READ:
738       simple_error_message_box(
739                  "The capture file appears to have been cut short"
740                  " in the middle of a packet.");
741       break;
742
743     case WTAP_ERR_BAD_FILE:
744       simple_error_message_box(
745                  "The capture file appears to be damaged or corrupt.\n(%s)",
746                  err_info);
747       g_free(err_info);
748       break;
749
750     case WTAP_ERR_DECOMPRESS:
751       simple_error_message_box(
752                  "The compressed capture file appears to be damaged or corrupt.\n"
753                  "(%s)", err_info);
754       g_free(err_info);
755       break;
756
757     default:
758       simple_error_message_box(
759                  "An error occurred while reading the"
760                  " capture file: %s.", wtap_strerror(err));
761       break;
762     }
763     return CF_READ_ERROR;
764   } else
765     return CF_READ_OK;
766 }
767
768 #ifdef HAVE_LIBPCAP
769 cf_status_t
770 cf_start_tail(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
771 {
772   cf_status_t cf_status;
773
774   cf_status = cf_open(cf, fname, is_tempfile, err);
775   return cf_status;
776 }
777
778 cf_read_status_t
779 cf_continue_tail(capture_file *cf, int to_read, int *err)
780 {
781   gchar        *err_info;
782   int           newly_displayed_packets = 0;
783   dfilter_t    *dfcode;
784   column_info  *cinfo;
785   epan_dissect_t edt;
786   gboolean      create_proto_tree;
787   guint         tap_flags;
788   gboolean      compiled;
789
790   /* Compile the current display filter.
791    * We assume this will not fail since cf->dfilter is only set in
792    * cf_filter IFF the filter was valid.
793    */
794   compiled = dfilter_compile(cf->dfilter, &dfcode);
795   g_assert(!cf->dfilter || (compiled && dfcode));
796
797   /* Get the union of the flags for all tap listeners. */
798   tap_flags = union_of_tap_listener_flags();
799   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
800   create_proto_tree =
801     (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
802   epan_dissect_init(&edt, create_proto_tree, FALSE);
803   if (dfcode != NULL)
804     epan_dissect_prime_dfilter(&edt, dfcode);
805
806   *err = 0;
807
808   packet_list_check_end();
809   /* Don't freeze/thaw the list when doing live capture */
810   /*packet_list_freeze();*/
811
812   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
813
814   TRY {
815     gint64 data_offset = 0;
816
817     while (to_read != 0) {
818       wtap_cleareof(cf->wth);
819       if (!wtap_read(cf->wth, err, &err_info, &data_offset)) {
820         break;
821       }
822       if (cf->state == FILE_READ_ABORTED) {
823         /* Well, the user decided to exit Wireshark.  Break out of the
824            loop, and let the code below (which is called even if there
825            aren't any packets left to read) exit. */
826         break;
827       }
828       if (read_packet(cf, dfcode, &edt, (column_info *) cinfo, data_offset) != -1) {
829         newly_displayed_packets++;
830       }
831       to_read--;
832     }
833   }
834   CATCH(OutOfMemoryError) {
835     simple_message_box(ESD_TYPE_ERROR, NULL,
836                    "Some infos / workarounds can be found at:\n"
837                    "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
838                    "Sorry, but Wireshark has run out of memory and has to terminate now!");
839 #if 0
840     /* Could we close the current capture and free up memory from that? */
841     return CF_READ_ABORTED;
842 #else
843     /* we have to terminate, as we cannot recover from the memory error */
844     exit(1);
845 #endif
846   }
847   ENDTRY;
848   epan_dissect_finish(&edt);
849
850   /* Update the file encapsulation; it might have changed based on the
851      packets we've read. */
852   cf->lnk_t = wtap_file_encap(cf->wth);
853
854   /* Cleanup and release all dfilter resources */
855   if (dfcode != NULL) {
856     dfilter_free(dfcode);
857   }
858
859   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
860     cf->count, cf->state, *err);*/
861
862   /* Don't freeze/thaw the list when doing live capture */
863   /*packet_list_thaw();*/
864   /* With the new packet list the first packet
865    * isn't automatically selected.
866    */
867   if (!cf->current_frame)
868     packet_list_select_first_row();
869
870   /* moving to the end of the packet list - if the user requested so and
871      we have some new packets. */
872   if (newly_displayed_packets && auto_scroll_live && cf->count != 0)
873       packet_list_moveto_end();
874
875   if (cf->state == FILE_READ_ABORTED) {
876     /* Well, the user decided to exit Wireshark.  Return CF_READ_ABORTED
877        so that our caller can kill off the capture child process;
878        this will cause an EOF on the pipe from the child, so
879        "cf_finish_tail()" will be called, and it will clean up
880        and exit. */
881     return CF_READ_ABORTED;
882   } else if (*err != 0) {
883     /* We got an error reading the capture file.
884        XXX - pop up a dialog box instead? */
885     g_warning("Error \"%s\" while reading: \"%s\" (\"%s\")",
886         wtap_strerror(*err), err_info, cf->filename);
887     g_free(err_info);
888
889     return CF_READ_ERROR;
890   } else
891     return CF_READ_OK;
892 }
893
894 void
895 cf_fake_continue_tail(capture_file *cf) {
896   cf->state = FILE_READ_DONE;
897 }
898
899 cf_read_status_t
900 cf_finish_tail(capture_file *cf, int *err)
901 {
902   gchar     *err_info;
903   gint64     data_offset;
904   dfilter_t *dfcode;
905   column_info *cinfo;
906   gboolean   create_proto_tree;
907   epan_dissect_t edt;
908   guint      tap_flags;
909   gboolean   compiled;
910
911   /* Compile the current display filter.
912    * We assume this will not fail since cf->dfilter is only set in
913    * cf_filter IFF the filter was valid.
914    */
915   compiled = dfilter_compile(cf->dfilter, &dfcode);
916   g_assert(!cf->dfilter || (compiled && dfcode));
917
918   /* Get the union of the flags for all tap listeners. */
919   tap_flags = union_of_tap_listener_flags();
920   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
921   create_proto_tree =
922     (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
923   epan_dissect_init(&edt, create_proto_tree, FALSE);
924   if (dfcode != NULL)
925     epan_dissect_prime_dfilter(&edt, dfcode);
926
927   if (cf->wth == NULL) {
928     cf_close(cf);
929     return CF_READ_ERROR;
930   }
931
932   packet_list_check_end();
933   /* Don't freeze/thaw the list when doing live capture */
934   /*packet_list_freeze();*/
935
936   while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
937     if (cf->state == FILE_READ_ABORTED) {
938       /* Well, the user decided to abort the read.  Break out of the
939          loop, and let the code below (which is called even if there
940          aren't any packets left to read) exit. */
941       break;
942     }
943     read_packet(cf, dfcode, &edt, cinfo, data_offset);
944   }
945   epan_dissect_finish(&edt);
946
947   /* Cleanup and release all dfilter resources */
948   if (dfcode != NULL) {
949     dfilter_free(dfcode);
950   }
951
952   /* Don't freeze/thaw the list when doing live capture */
953   /*packet_list_thaw();*/
954
955   if (cf->state == FILE_READ_ABORTED) {
956     /* Well, the user decided to abort the read.  We're only called
957        when the child capture process closes the pipe to us (meaning
958        it's probably exited), so we can just close the capture
959        file; we return CF_READ_ABORTED so our caller can do whatever
960        is appropriate when that happens. */
961     cf_close(cf);
962     return CF_READ_ABORTED;
963   }
964
965   if (auto_scroll_live && cf->count != 0)
966     packet_list_moveto_end();
967
968   /* We're done reading sequentially through the file. */
969   cf->state = FILE_READ_DONE;
970
971   /* We're done reading sequentially through the file; close the
972      sequential I/O side, to free up memory it requires. */
973   wtap_sequential_close(cf->wth);
974
975   /* Allow the protocol dissectors to free up memory that they
976    * don't need after the sequential run-through of the packets. */
977   postseq_cleanup_all_protocols();
978
979   /* Update the file encapsulation; it might have changed based on the
980      packets we've read. */
981   cf->lnk_t = wtap_file_encap(cf->wth);
982
983   /* Update the details in the file-set dialog, as the capture file
984    * has likely grown since we first stat-ed it */
985   fileset_update_file(cf->filename);
986
987   if (*err != 0) {
988     /* We got an error reading the capture file.
989        XXX - pop up a dialog box? */
990
991     g_warning("Error \"%s\" while reading: \"%s\" (\"%s\")",
992         wtap_strerror(*err), err_info, cf->filename);
993     g_free(err_info);
994     return CF_READ_ERROR;
995   } else {
996     return CF_READ_OK;
997   }
998 }
999 #endif /* HAVE_LIBPCAP */
1000
1001 gchar *
1002 cf_get_display_name(capture_file *cf)
1003 {
1004   gchar *displayname;
1005
1006   /* Return a name to use in displays */
1007   if (!cf->is_tempfile) {
1008     /* Get the last component of the file name, and use that. */
1009     if (cf->filename) {
1010       displayname = g_filename_display_basename(cf->filename);
1011     } else {
1012       displayname=g_strdup("(No file)");
1013     }
1014   } else {
1015     /* The file we read is a temporary file from a live capture or
1016        a merge operation; we don't mention its name, but, if it's
1017        from a capture, give the source of the capture. */
1018     if (cf->source) {
1019       displayname = g_strdup(cf->source);
1020     } else {
1021       displayname = g_strdup("(Untitled)");
1022     }
1023   }
1024   return displayname;
1025 }
1026
1027 void cf_set_tempfile_source(capture_file *cf, gchar *source) {
1028   if (cf->source) {
1029     g_free(cf->source);
1030   }
1031
1032   if (source) {
1033     cf->source = g_strdup(source);
1034   } else {
1035     cf->source = g_strdup("");
1036   }
1037 }
1038
1039 const gchar *cf_get_tempfile_source(capture_file *cf) {
1040   if (!cf->source) {
1041     return "";
1042   }
1043
1044   return cf->source;
1045 }
1046
1047 /* XXX - use a macro instead? */
1048 int
1049 cf_get_packet_count(capture_file *cf)
1050 {
1051   return cf->count;
1052 }
1053
1054 /* XXX - use a macro instead? */
1055 void
1056 cf_set_packet_count(capture_file *cf, int packet_count)
1057 {
1058   cf->count = packet_count;
1059 }
1060
1061 /* XXX - use a macro instead? */
1062 gboolean
1063 cf_is_tempfile(capture_file *cf)
1064 {
1065   return cf->is_tempfile;
1066 }
1067
1068 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
1069 {
1070   cf->is_tempfile = is_tempfile;
1071 }
1072
1073
1074 /* XXX - use a macro instead? */
1075 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
1076 {
1077   cf->drops_known = drops_known;
1078 }
1079
1080 /* XXX - use a macro instead? */
1081 void cf_set_drops(capture_file *cf, guint32 drops)
1082 {
1083   cf->drops = drops;
1084 }
1085
1086 /* XXX - use a macro instead? */
1087 gboolean cf_get_drops_known(capture_file *cf)
1088 {
1089   return cf->drops_known;
1090 }
1091
1092 /* XXX - use a macro instead? */
1093 guint32 cf_get_drops(capture_file *cf)
1094 {
1095   return cf->drops;
1096 }
1097
1098 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
1099 {
1100   cf->rfcode = rfcode;
1101 }
1102
1103 static void
1104 find_and_mark_frame_depended_upon(gpointer data, gpointer user_data)
1105 {
1106   frame_data   *dependent_fd;
1107   guint32       dependent_frame = GPOINTER_TO_UINT(data);
1108   capture_file *cf              = (capture_file *)user_data;
1109
1110   dependent_fd = frame_data_sequence_find(cf->frames, dependent_frame);
1111   dependent_fd->flags.dependent_of_displayed = 1;
1112 }
1113
1114 static int
1115 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
1116     dfilter_t *dfcode, epan_dissect_t *edt, column_info *cinfo,
1117     struct wtap_pkthdr *phdr, const guchar *buf,
1118     gboolean add_to_packet_list)
1119 {
1120   gint row = -1;
1121
1122   frame_data_set_before_dissect(fdata, &cf->elapsed_time,
1123                                 &first_ts, prev_dis, prev_cap);
1124   prev_cap = fdata;
1125
1126   epan_dissect_run_with_taps(edt, phdr, buf, fdata, cinfo);
1127
1128   /* If we don't have a display filter, set "passed_dfilter" to 1. */
1129   if (dfcode != NULL) {
1130     fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, edt) ? 1 : 0;
1131
1132     if (fdata->flags.passed_dfilter) {
1133       /* This frame passed the display filter but it may depend on other
1134        * (potentially not displayed) frames.  Find those frames and mark them
1135        * as depended upon.
1136        */
1137       g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf);
1138     }
1139   } else
1140     fdata->flags.passed_dfilter = 1;
1141
1142   if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1143     cf->displayed_count++;
1144
1145   if (add_to_packet_list) {
1146     /* We fill the needed columns from new_packet_list */
1147       row = packet_list_append(cinfo, fdata, &edt->pi);
1148   }
1149
1150   if (fdata->flags.passed_dfilter || fdata->flags.ref_time)
1151   {
1152     frame_data_set_after_dissect(fdata, &cum_bytes);
1153     prev_dis = fdata;
1154
1155     /* If we haven't yet seen the first frame, this is it.
1156
1157        XXX - we must do this before we add the row to the display,
1158        as, if the display's GtkCList's selection mode is
1159        GTK_SELECTION_BROWSE, when the first entry is added to it,
1160        "cf_select_packet()" will be called, and it will fetch the row
1161        data for the 0th row, and will get a null pointer rather than
1162        "fdata", as "gtk_clist_append()" won't yet have returned and
1163        thus "gtk_clist_set_row_data()" won't yet have been called.
1164
1165        We thus need to leave behind bread crumbs so that
1166        "cf_select_packet()" can find this frame.  See the comment
1167        in "cf_select_packet()". */
1168     if (cf->first_displayed == 0)
1169       cf->first_displayed = fdata->num;
1170
1171     /* This is the last frame we've seen so far. */
1172     cf->last_displayed = fdata->num;
1173   }
1174
1175   epan_dissect_reset(edt);
1176   return row;
1177 }
1178
1179 /* read in a new packet */
1180 /* returns the row of the new packet in the packet list or -1 if not displayed */
1181 static int
1182 read_packet(capture_file *cf, dfilter_t *dfcode,
1183             epan_dissect_t *edt, column_info *cinfo, gint64 offset)
1184 {
1185   struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
1186   const guchar *buf = wtap_buf_ptr(cf->wth);
1187   frame_data    fdlocal;
1188   guint32       framenum;
1189   frame_data   *fdata;
1190   int           passed;
1191   int           row = -1;
1192
1193   /* Add this packet's link-layer encapsulation type to cf->linktypes, if
1194      it's not already there.
1195      XXX - yes, this is O(N), so if every packet had a different
1196      link-layer encapsulation type, it'd be O(N^2) to read the file, but
1197      there are probably going to be a small number of encapsulation types
1198      in a file. */
1199   cf_add_encapsulation_type(cf, phdr->pkt_encap);
1200
1201   /* The frame number of this packet is one more than the count of
1202      frames in the file so far. */
1203   framenum = cf->count + 1;
1204
1205   frame_data_init(&fdlocal, framenum, phdr, offset, cum_bytes);
1206
1207   passed = TRUE;
1208   if (cf->rfcode) {
1209     epan_dissect_t edt;
1210     epan_dissect_init(&edt, TRUE, FALSE);
1211     epan_dissect_prime_dfilter(&edt, cf->rfcode);
1212     epan_dissect_run(&edt, phdr, buf, &fdlocal, NULL);
1213     passed = dfilter_apply_edt(cf->rfcode, &edt);
1214     epan_dissect_cleanup(&edt);
1215   }
1216
1217   if (passed) {
1218     /* This does a shallow copy of fdlocal, which is good enough. */
1219     fdata = frame_data_sequence_add(cf->frames, &fdlocal);
1220
1221     cf->count++;
1222     if (fdlocal.opt_comment != NULL)
1223       cf->packet_comment_count++;
1224     cf->f_datalen = offset + fdlocal.cap_len;
1225
1226     if (!cf->redissecting) {
1227       row = add_packet_to_packet_list(fdata, cf, dfcode,
1228                                       edt, cinfo,
1229                                       phdr, buf, TRUE);
1230     }
1231   }
1232
1233   return row;
1234 }
1235
1236 cf_status_t
1237 cf_merge_files(char **out_filenamep, int in_file_count,
1238                char *const *in_filenames, int file_type, gboolean do_append)
1239 {
1240   merge_in_file_t *in_files, *in_file;
1241   char            *out_filename;
1242   char            *tmpname;
1243   int              out_fd;
1244   wtap_dumper     *pdh;
1245   int              open_err, read_err, write_err, close_err;
1246   gchar           *err_info;
1247   int              err_fileno;
1248   int              i;
1249   gboolean         got_read_error     = FALSE, got_write_error = FALSE;
1250   gint64           data_offset;
1251   progdlg_t       *progbar            = NULL;
1252   gboolean         stop_flag;
1253   gint64           f_len, file_pos;
1254   float            progbar_val;
1255   GTimeVal         start_time;
1256   gchar            status_str[100];
1257   gint64           progbar_nextstep;
1258   gint64           progbar_quantum;
1259   gchar           *display_basename;
1260   int              selected_frame_type;
1261   gboolean         fake_interface_ids = FALSE;
1262
1263   /* open the input files */
1264   if (!merge_open_in_files(in_file_count, in_filenames, &in_files,
1265                            &open_err, &err_info, &err_fileno)) {
1266     g_free(in_files);
1267     cf_open_failure_alert_box(in_filenames[err_fileno], open_err, err_info,
1268                               FALSE, 0);
1269     return CF_ERROR;
1270   }
1271
1272   if (*out_filenamep != NULL) {
1273     out_filename = *out_filenamep;
1274     out_fd = ws_open(out_filename, O_CREAT|O_TRUNC|O_BINARY, 0600);
1275     if (out_fd == -1)
1276       open_err = errno;
1277   } else {
1278     out_fd = create_tempfile(&tmpname, "wireshark");
1279     if (out_fd == -1)
1280       open_err = errno;
1281     out_filename = g_strdup(tmpname);
1282     *out_filenamep = out_filename;
1283   }
1284   if (out_fd == -1) {
1285     err_info = NULL;
1286     merge_close_in_files(in_file_count, in_files);
1287     g_free(in_files);
1288     cf_open_failure_alert_box(out_filename, open_err, NULL, TRUE, file_type);
1289     return CF_ERROR;
1290   }
1291
1292   selected_frame_type = merge_select_frame_type(in_file_count, in_files);
1293
1294   /* If we are trying to merge a number of libpcap files with different encapsulation types
1295    * change the output file type to pcapng and create SHB and IDB:s for the new file use the
1296    * interface index stored in in_files per file to change the phdr before writing the datablock.
1297    * XXX should it be an option to convert to pcapng?
1298    *
1299    * We need something similar when merging pcapng files possibly with an option to say
1300    * the same interface(s) used in all in files. SHBs comments should be merged together.
1301    */
1302   if ((selected_frame_type == WTAP_ENCAP_PER_PACKET)&&(file_type == WTAP_FILE_PCAP)) {
1303     /* Write output in pcapng format */
1304     wtapng_section_t            *shb_hdr;
1305     wtapng_iface_descriptions_t *idb_inf, *idb_inf_merge_file;
1306     wtapng_if_descr_t            int_data, *file_int_data;
1307     GString                     *comment_gstr;
1308     int                          i;
1309
1310     fake_interface_ids = TRUE;
1311     /* Create SHB info */
1312     shb_hdr = wtap_file_get_shb_info(in_files[0].wth);
1313     comment_gstr = g_string_new("");
1314     g_string_append_printf(comment_gstr, "%s \n",shb_hdr->opt_comment);
1315     g_string_append_printf(comment_gstr, "File created by merging: \n");
1316     file_type = WTAP_FILE_PCAPNG;
1317
1318     for (i = 0; i < in_file_count; i++) {
1319         g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
1320     }
1321     shb_hdr->section_length = -1;
1322     /* options */
1323     shb_hdr->opt_comment   = g_string_free(comment_gstr, FALSE);  /* NULL if not available */
1324     shb_hdr->shb_hardware  = NULL;        /* NULL if not available, UTF-8 string containing the        */
1325                                           /*  description of the hardware used to create this section. */
1326     shb_hdr->shb_os        = NULL;        /* NULL if not available, UTF-8 string containing the name   */
1327                                           /*  of the operating system used to create this section.     */
1328     shb_hdr->shb_user_appl = "Wireshark"; /* NULL if not available, UTF-8 string containing the name   */
1329                                           /*  of the application used to create this section.          */
1330
1331     /* create fake IDB info */
1332     idb_inf = g_new(wtapng_iface_descriptions_t,1);
1333     idb_inf->number_of_interfaces = in_file_count; /* TODO make this the number of DIFFERENT encapsulation types
1334                                                     * check that snaplength is the same too?
1335                                                     */
1336     idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));
1337
1338     for (i = 0; i < in_file_count; i++) {
1339       idb_inf_merge_file               = wtap_file_get_idb_info(in_files[i].wth);
1340       /* read the interface data from the in file to our combined interfca data */
1341       file_int_data = &g_array_index (idb_inf_merge_file->interface_data, wtapng_if_descr_t, 0);
1342       int_data.wtap_encap            = file_int_data->wtap_encap;
1343       int_data.time_units_per_second = file_int_data->time_units_per_second;
1344       int_data.link_type             = file_int_data->link_type;
1345       int_data.snap_len              = file_int_data->snap_len;
1346       int_data.if_name               = g_strdup(file_int_data->if_name);
1347       int_data.opt_comment           = NULL;
1348       int_data.if_description        = NULL;
1349       int_data.if_speed              = 0;
1350       int_data.if_tsresol            = 6;
1351       int_data.if_filter_str         = NULL;
1352       int_data.bpf_filter_len        = 0;
1353       int_data.if_filter_bpf_bytes   = NULL;
1354       int_data.if_os                 = NULL;
1355       int_data.if_fcslen             = -1;
1356       int_data.num_stat_entries      = 0;          /* Number of ISB:s */
1357       int_data.interface_statistics  = NULL;
1358
1359       g_array_append_val(idb_inf->interface_data, int_data);
1360       g_free(idb_inf_merge_file);
1361
1362       /* Set fake interface Id in per file data */
1363       in_files[i].interface_id = i;
1364     }
1365
1366     pdh = wtap_dump_fdopen_ng(out_fd, file_type,
1367                               selected_frame_type,
1368                               merge_max_snapshot_length(in_file_count, in_files),
1369                               FALSE /* compressed */, shb_hdr, idb_inf /* wtapng_iface_descriptions_t *idb_inf */, &open_err);
1370
1371     if (pdh == NULL) {
1372       ws_close(out_fd);
1373       merge_close_in_files(in_file_count, in_files);
1374       g_free(in_files);
1375       cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
1376                                 file_type);
1377       return CF_ERROR;
1378     }
1379
1380   } else {
1381
1382     pdh = wtap_dump_fdopen(out_fd, file_type,
1383                            selected_frame_type,
1384                            merge_max_snapshot_length(in_file_count, in_files),
1385                            FALSE /* compressed */, &open_err);
1386     if (pdh == NULL) {
1387       ws_close(out_fd);
1388       merge_close_in_files(in_file_count, in_files);
1389       g_free(in_files);
1390       cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
1391                                 file_type);
1392       return CF_ERROR;
1393     }
1394   }
1395
1396   /* Get the sum of the sizes of all the files. */
1397   f_len = 0;
1398   for (i = 0; i < in_file_count; i++)
1399     f_len += in_files[i].size;
1400
1401   /* Update the progress bar when it gets to this value. */
1402   progbar_nextstep = 0;
1403   /* When we reach the value that triggers a progress bar update,
1404      bump that value by this amount. */
1405   progbar_quantum = f_len/N_PROGBAR_UPDATES;
1406   /* Progress so far. */
1407   progbar_val = 0.0f;
1408
1409   stop_flag = FALSE;
1410   g_get_current_time(&start_time);
1411
1412   /* do the merge (or append) */
1413   for (;;) {
1414     if (do_append)
1415       in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
1416                                          &err_info);
1417     else
1418       in_file = merge_read_packet(in_file_count, in_files, &read_err,
1419                                   &err_info);
1420     if (in_file == NULL) {
1421       /* EOF */
1422       break;
1423     }
1424
1425     if (read_err != 0) {
1426       /* I/O error reading from in_file */
1427       got_read_error = TRUE;
1428       break;
1429     }
1430
1431     /* Get the sum of the data offsets in all of the files. */
1432     data_offset = 0;
1433     for (i = 0; i < in_file_count; i++)
1434       data_offset += in_files[i].data_offset;
1435
1436     /* Create the progress bar if necessary.
1437        We check on every iteration of the loop, so that it takes no
1438        longer than the standard time to create it (otherwise, for a
1439        large file, we might take considerably longer than that standard
1440        time in order to get to the next progress bar step). */
1441     if (progbar == NULL) {
1442       progbar = delayed_create_progress_dlg(NULL, "Merging", "files",
1443         FALSE, &stop_flag, &start_time, progbar_val);
1444     }
1445
1446     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1447        when we update it, we have to run the GTK+ main loop to get it
1448        to repaint what's pending, and doing so may involve an "ioctl()"
1449        to see if there's any pending input from an X server, and doing
1450        that for every packet can be costly, especially on a big file. */
1451     if (data_offset >= progbar_nextstep) {
1452         /* Get the sum of the seek positions in all of the files. */
1453         file_pos = 0;
1454         for (i = 0; i < in_file_count; i++)
1455           file_pos += wtap_read_so_far(in_files[i].wth);
1456         progbar_val = (gfloat) file_pos / (gfloat) f_len;
1457         if (progbar_val > 1.0f) {
1458           /* Some file probably grew while we were reading it.
1459              That "shouldn't happen", so we'll just clip the progress
1460              value at 1.0. */
1461           progbar_val = 1.0f;
1462         }
1463         if (progbar != NULL) {
1464           g_snprintf(status_str, sizeof(status_str),
1465                      "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
1466                      file_pos / 1024, f_len / 1024);
1467           update_progress_dlg(progbar, progbar_val, status_str);
1468         }
1469         progbar_nextstep += progbar_quantum;
1470     }
1471
1472     if (stop_flag) {
1473       /* Well, the user decided to abort the merge. */
1474       break;
1475     }
1476
1477     /* If we have WTAP_ENCAP_PER_PACKETend the infiles are of type WTAP_FILE_PCAP
1478      * we need to set the interface id in the paket header = the interface index we used
1479      * in the IDBs interface description for this file(encapsulation type).
1480      */
1481     if (fake_interface_ids) {
1482       struct wtap_pkthdr *phdr;
1483
1484       phdr = wtap_phdr(in_file->wth);
1485       phdr->interface_id = in_file->interface_id;
1486       phdr->presence_flags = phdr->presence_flags | WTAP_HAS_INTERFACE_ID;
1487     }
1488     if (!wtap_dump(pdh, wtap_phdr(in_file->wth),
1489                    wtap_buf_ptr(in_file->wth), &write_err)) {
1490       got_write_error = TRUE;
1491       break;
1492     }
1493   }
1494
1495   /* We're done merging the files; destroy the progress bar if it was created. */
1496   if (progbar != NULL)
1497     destroy_progress_dlg(progbar);
1498
1499   merge_close_in_files(in_file_count, in_files);
1500   if (!got_read_error && !got_write_error) {
1501     if (!wtap_dump_close(pdh, &write_err))
1502       got_write_error = TRUE;
1503   } else
1504     wtap_dump_close(pdh, &close_err);
1505
1506   if (got_read_error) {
1507     /*
1508      * Find the file on which we got the error, and report the error.
1509      */
1510     for (i = 0; i < in_file_count; i++) {
1511       if (in_files[i].state == GOT_ERROR) {
1512         /* Put up a message box noting that a read failed somewhere along
1513            the line. */
1514         display_basename = g_filename_display_basename(in_files[i].filename);
1515         switch (read_err) {
1516
1517         case WTAP_ERR_UNSUPPORTED_ENCAP:
1518           simple_error_message_box(
1519                      "The capture file %s has a packet with a network type that Wireshark doesn't support.\n(%s)",
1520                      display_basename, err_info);
1521           g_free(err_info);
1522           break;
1523
1524         case WTAP_ERR_CANT_READ:
1525           simple_error_message_box(
1526                      "An attempt to read from the capture file %s failed for"
1527                      " some unknown reason.", display_basename);
1528           break;
1529
1530         case WTAP_ERR_SHORT_READ:
1531           simple_error_message_box(
1532                      "The capture file %s appears to have been cut short"
1533                       " in the middle of a packet.", display_basename);
1534           break;
1535
1536         case WTAP_ERR_BAD_FILE:
1537           simple_error_message_box(
1538                      "The capture file %s appears to be damaged or corrupt.\n(%s)",
1539                      display_basename, err_info);
1540           g_free(err_info);
1541           break;
1542
1543         case WTAP_ERR_DECOMPRESS:
1544           simple_error_message_box(
1545                      "The compressed capture file %s appears to be damaged or corrupt.\n"
1546                      "(%s)", display_basename, err_info);
1547           g_free(err_info);
1548           break;
1549
1550         default:
1551           simple_error_message_box(
1552                      "An error occurred while reading the"
1553                      " capture file %s: %s.",
1554                      display_basename,  wtap_strerror(read_err));
1555           break;
1556         }
1557         g_free(display_basename);
1558       }
1559     }
1560   }
1561
1562   if (got_write_error) {
1563     /* Put up an alert box for the write error. */
1564     if (write_err < 0) {
1565       /* Wiretap error. */
1566       switch (write_err) {
1567
1568       case WTAP_ERR_UNSUPPORTED_ENCAP:
1569         /*
1570          * This is a problem with the particular frame we're writing;
1571          * note that, and give the frame number.
1572          */
1573         display_basename = g_filename_display_basename(in_file->filename);
1574         simple_error_message_box(
1575                       "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.",
1576                       in_file->packet_num, display_basename,
1577                       wtap_file_type_string(file_type));
1578         g_free(display_basename);
1579         break;
1580
1581       default:
1582         display_basename = g_filename_display_basename(out_filename);
1583         simple_error_message_box(
1584                       "An error occurred while writing to the file \"%s\": %s.",
1585                       out_filename, wtap_strerror(write_err));
1586         g_free(display_basename);
1587         break;
1588       }
1589     } else {
1590       /* OS error. */
1591       write_failure_alert_box(out_filename, write_err);
1592     }
1593   }
1594
1595   if (got_read_error || got_write_error || stop_flag) {
1596     /* Callers aren't expected to treat an error or an explicit abort
1597        differently - we put up error dialogs ourselves, so they don't
1598        have to. */
1599     return CF_ERROR;
1600   } else
1601     return CF_OK;
1602 }
1603
1604 cf_status_t
1605 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1606 {
1607   const char *filter_new = dftext ? dftext : "";
1608   const char *filter_old = cf->dfilter ? cf->dfilter : "";
1609   dfilter_t  *dfcode;
1610   GTimeVal    start_time;
1611
1612   /* if new filter equals old one, do nothing unless told to do so */
1613   if (!force && strcmp(filter_new, filter_old) == 0) {
1614     return CF_OK;
1615   }
1616
1617   dfcode=NULL;
1618
1619   if (dftext == NULL) {
1620     /* The new filter is an empty filter (i.e., display all packets).
1621      * so leave dfcode==NULL
1622      */
1623   } else {
1624     /*
1625      * We have a filter; make a copy of it (as we'll be saving it),
1626      * and try to compile it.
1627      */
1628     dftext = g_strdup(dftext);
1629     if (!dfilter_compile(dftext, &dfcode)) {
1630       /* The attempt failed; report an error. */
1631       simple_message_box(ESD_TYPE_ERROR, NULL,
1632           "See the help for a description of the display filter syntax.",
1633           "\"%s\" isn't a valid display filter: %s",
1634           dftext, dfilter_error_msg);
1635       g_free(dftext);
1636       return CF_ERROR;
1637     }
1638
1639     /* Was it empty? */
1640     if (dfcode == NULL) {
1641       /* Yes - free the filter text, and set it to null. */
1642       g_free(dftext);
1643       dftext = NULL;
1644     }
1645   }
1646
1647   /* We have a valid filter.  Replace the current filter. */
1648   g_free(cf->dfilter);
1649   cf->dfilter = dftext;
1650   g_get_current_time(&start_time);
1651
1652
1653   /* Now rescan the packet list, applying the new filter, but not
1654      throwing away information constructed on a previous pass. */
1655   if (dftext == NULL) {
1656     rescan_packets(cf, "Resetting", "Filter", FALSE);
1657   } else {
1658     rescan_packets(cf, "Filtering", dftext, FALSE);
1659   }
1660
1661   /* Cleanup and release all dfilter resources */
1662   dfilter_free(dfcode);
1663
1664   return CF_OK;
1665 }
1666
1667 void
1668 cf_reftime_packets(capture_file *cf)
1669 {
1670   ref_time_packets(cf);
1671 }
1672
1673 void
1674 cf_redissect_packets(capture_file *cf)
1675 {
1676   rescan_packets(cf, "Reprocessing", "all packets", TRUE);
1677 }
1678
1679 gboolean
1680 cf_read_frame_r(capture_file *cf, frame_data *fdata,
1681                 struct wtap_pkthdr *phdr, guint8 *pd)
1682 {
1683   int    err;
1684   gchar *err_info;
1685   gchar *display_basename;
1686
1687 #ifdef WANT_PACKET_EDITOR
1688   /* if fdata->file_off == -1 it means packet was edited, and we must find data inside edited_frames tree */
1689   if (G_UNLIKELY(fdata->file_off == -1)) {
1690     const modified_frame_data *frame = (const modified_frame_data *) g_tree_lookup(cf->edited_frames, GINT_TO_POINTER(fdata->num));
1691
1692     if (!frame) {
1693       simple_error_message_box("fdata->file_off == -1, but can't find modified frame!");
1694       return FALSE;
1695     }
1696
1697     *phdr = frame->phdr;
1698     memcpy(pd, frame->pd, fdata->cap_len);
1699     return TRUE;
1700   }
1701 #endif
1702
1703   if (!wtap_seek_read(cf->wth, fdata->file_off, phdr, pd,
1704                       fdata->cap_len, &err, &err_info)) {
1705     display_basename = g_filename_display_basename(cf->filename);
1706     switch (err) {
1707
1708     case WTAP_ERR_UNSUPPORTED_ENCAP:
1709       simple_error_message_box("The file \"%s\" has a packet with a network type that Wireshark doesn't support.\n(%s)",
1710                  display_basename, err_info);
1711       g_free(err_info);
1712       break;
1713
1714     case WTAP_ERR_BAD_FILE:
1715       simple_error_message_box("An error occurred while reading from the file \"%s\": %s.\n(%s)",
1716                  display_basename, wtap_strerror(err), err_info);
1717       g_free(err_info);
1718       break;
1719
1720     default:
1721       simple_error_message_box(
1722                  "An error occurred while reading from the file \"%s\": %s.",
1723                  display_basename, wtap_strerror(err));
1724       break;
1725     }
1726     g_free(display_basename);
1727     return FALSE;
1728   }
1729   return TRUE;
1730 }
1731
1732 gboolean
1733 cf_read_frame(capture_file *cf, frame_data *fdata)
1734 {
1735   return cf_read_frame_r(cf, fdata, &cf->phdr, cf->pd);
1736 }
1737
1738 /* Rescan the list of packets, reconstructing the CList.
1739
1740    "action" describes why we're doing this; it's used in the progress
1741    dialog box.
1742
1743    "action_item" describes what we're doing; it's used in the progress
1744    dialog box.
1745
1746    "redissect" is TRUE if we need to make the dissectors reconstruct
1747    any state information they have (because a preference that affects
1748    some dissector has changed, meaning some dissector might construct
1749    its state differently from the way it was constructed the last time). */
1750 static void
1751 rescan_packets(capture_file *cf, const char *action, const char *action_item, gboolean redissect)
1752 {
1753   /* Rescan packets new packet list */
1754   guint32     framenum;
1755   frame_data *fdata;
1756   progdlg_t  *progbar = NULL;
1757   gboolean    stop_flag;
1758   int         count;
1759   frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1760   int         selected_frame_num, preceding_frame_num, following_frame_num, prev_frame_num;
1761   gboolean    selected_frame_seen;
1762   float       progbar_val;
1763   GTimeVal    start_time;
1764   gchar       status_str[100];
1765   int         progbar_nextstep;
1766   int         progbar_quantum;
1767   dfilter_t  *dfcode;
1768   column_info *cinfo;
1769   epan_dissect_t edt;
1770   gboolean    create_proto_tree;
1771   guint       tap_flags;
1772   gboolean    add_to_packet_list = FALSE;
1773   gboolean    compiled;
1774   guint32     frames_count;
1775
1776   /* Compile the current display filter.
1777    * We assume this will not fail since cf->dfilter is only set in
1778    * cf_filter IFF the filter was valid.
1779    */
1780   compiled = dfilter_compile(cf->dfilter, &dfcode);
1781   g_assert(!cf->dfilter || (compiled && dfcode));
1782
1783   /* Get the union of the flags for all tap listeners. */
1784   tap_flags = union_of_tap_listener_flags();
1785   cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
1786   create_proto_tree =
1787     (dfcode != NULL || have_filtering_tap_listeners() || (tap_flags & TL_REQUIRES_PROTO_TREE));
1788   epan_dissect_init(&edt, create_proto_tree, FALSE);
1789   if (dfcode != NULL)
1790     epan_dissect_prime_dfilter(&edt, dfcode);
1791
1792   reset_tap_listeners();
1793   /* Which frame, if any, is the currently selected frame?
1794      XXX - should the selected frame or the focus frame be the "current"
1795      frame, that frame being the one from which "Find Frame" searches
1796      start? */
1797   selected_frame = cf->current_frame;
1798
1799   /* Mark frame num as not found */
1800   selected_frame_num = -1;
1801
1802   /* Freeze the packet list while we redo it, so we don't get any
1803      screen updates while it happens. */
1804   packet_list_freeze();
1805
1806   if (redissect) {
1807     /* We need to re-initialize all the state information that protocols
1808        keep, because some preference that controls a dissector has changed,
1809        which might cause the state information to be constructed differently
1810        by that dissector. */
1811
1812     /* We might receive new packets while redissecting, and we don't
1813        want to dissect those before their time. */
1814     cf->redissecting = TRUE;
1815
1816     /* Cleanup all data structures used for dissection. */
1817     cleanup_dissection();
1818     /* Initialize all data structures used for dissection. */
1819     init_dissection();
1820
1821     /* We need to redissect the packets so we have to discard our old
1822      * packet list store. */
1823     packet_list_clear();
1824     add_to_packet_list = TRUE;
1825   }
1826
1827   /* We don't yet know which will be the first and last frames displayed. */
1828   cf->first_displayed = 0;
1829   cf->last_displayed = 0;
1830
1831   /* We currently don't display any packets */
1832   cf->displayed_count = 0;
1833
1834   /* Iterate through the list of frames.  Call a routine for each frame
1835      to check whether it should be displayed and, if so, add it to
1836      the display list. */
1837   nstime_set_unset(&first_ts);
1838   prev_dis = NULL;
1839   prev_cap = NULL;
1840   cum_bytes = 0;
1841
1842   /* Update the progress bar when it gets to this value. */
1843   progbar_nextstep = 0;
1844   /* When we reach the value that triggers a progress bar update,
1845      bump that value by this amount. */
1846   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1847   /* Count of packets at which we've looked. */
1848   count = 0;
1849   /* Progress so far. */
1850   progbar_val = 0.0f;
1851
1852   stop_flag = FALSE;
1853   g_get_current_time(&start_time);
1854
1855   /* no previous row yet */
1856   prev_frame_num = -1;
1857   prev_frame = NULL;
1858
1859   preceding_frame_num = -1;
1860   preceding_frame = NULL;
1861   following_frame_num = -1;
1862   following_frame = NULL;
1863
1864   selected_frame_seen = FALSE;
1865
1866   frames_count = cf->count;
1867   for (framenum = 1; framenum <= frames_count; framenum++) {
1868     fdata = frame_data_sequence_find(cf->frames, framenum);
1869
1870     /* Create the progress bar if necessary.
1871        We check on every iteration of the loop, so that it takes no
1872        longer than the standard time to create it (otherwise, for a
1873        large file, we might take considerably longer than that standard
1874        time in order to get to the next progress bar step). */
1875     if (progbar == NULL)
1876       progbar = delayed_create_progress_dlg(cf->window, action, action_item, TRUE,
1877                                             &stop_flag, &start_time,
1878                                             progbar_val);
1879
1880     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1881        when we update it, we have to run the GTK+ main loop to get it
1882        to repaint what's pending, and doing so may involve an "ioctl()"
1883        to see if there's any pending input from an X server, and doing
1884        that for every packet can be costly, especially on a big file. */
1885     if (count >= progbar_nextstep) {
1886       /* let's not divide by zero. I should never be started
1887        * with count == 0, so let's assert that
1888        */
1889       g_assert(cf->count > 0);
1890       progbar_val = (gfloat) count / frames_count;
1891
1892       if (progbar != NULL) {
1893         g_snprintf(status_str, sizeof(status_str),
1894                   "%4u of %u frames", count, frames_count);
1895         update_progress_dlg(progbar, progbar_val, status_str);
1896       }
1897
1898       progbar_nextstep += progbar_quantum;
1899     }
1900
1901     if (stop_flag) {
1902       /* Well, the user decided to abort the filtering.  Just stop.
1903
1904          XXX - go back to the previous filter?  Users probably just
1905          want not to wait for a filtering operation to finish;
1906          unless we cancel by having no filter, reverting to the
1907          previous filter will probably be even more expensive than
1908          continuing the filtering, as it involves going back to the
1909          beginning and filtering, and even with no filter we currently
1910          have to re-generate the entire clist, which is also expensive.
1911
1912          I'm not sure what Network Monitor does, but it doesn't appear
1913          to give you an unfiltered display if you cancel. */
1914       break;
1915     }
1916
1917     count++;
1918
1919     if (redissect) {
1920       /* Since all state for the frame was destroyed, mark the frame
1921        * as not visited, free the GSList referring to the state
1922        * data (the per-frame data itself was freed by
1923        * "init_dissection()"), and null out the GSList pointer. */
1924       fdata->flags.visited = 0;
1925       frame_data_cleanup(fdata);
1926       frames_count = cf->count;
1927     }
1928
1929     /* Frame dependencies from the previous dissection/filtering are no longer valid. */
1930     fdata->flags.dependent_of_displayed = 0;
1931
1932     if (!cf_read_frame(cf, fdata))
1933       break; /* error reading the frame */
1934
1935     /* If the previous frame is displayed, and we haven't yet seen the
1936        selected frame, remember that frame - it's the closest one we've
1937        yet seen before the selected frame. */
1938     if (prev_frame_num != -1 && !selected_frame_seen && prev_frame->flags.passed_dfilter) {
1939       preceding_frame_num = prev_frame_num;
1940       preceding_frame = prev_frame;
1941     }
1942     add_packet_to_packet_list(fdata, cf, dfcode, &edt,
1943                                     cinfo, &cf->phdr, cf->pd,
1944                                     add_to_packet_list);
1945
1946     /* If this frame is displayed, and this is the first frame we've
1947        seen displayed after the selected frame, remember this frame -
1948        it's the closest one we've yet seen at or after the selected
1949        frame. */
1950     if (fdata->flags.passed_dfilter && selected_frame_seen && following_frame_num == -1) {
1951       following_frame_num = fdata->num;
1952       following_frame = fdata;
1953     }
1954     if (fdata == selected_frame) {
1955       selected_frame_seen = TRUE;
1956       if (fdata->flags.passed_dfilter)
1957           selected_frame_num = fdata->num;
1958     }
1959
1960     /* Remember this frame - it'll be the previous frame
1961        on the next pass through the loop. */
1962     prev_frame_num = fdata->num;
1963     prev_frame = fdata;
1964   }
1965   epan_dissect_finish(&edt);
1966
1967   /* We are done redissecting the packet list. */
1968   cf->redissecting = FALSE;
1969
1970   if (redissect) {
1971       frames_count = cf->count;
1972     /* Clear out what remains of the visited flags and per-frame data
1973        pointers.
1974
1975        XXX - that may cause various forms of bogosity when dissecting
1976        these frames, as they won't have been seen by this sequential
1977        pass, but the only alternative I see is to keep scanning them
1978        even though the user requested that the scan stop, and that
1979        would leave the user stuck with an Wireshark grinding on
1980        until it finishes.  Should we just stick them with that? */
1981     for (; framenum <= frames_count; framenum++) {
1982       fdata = frame_data_sequence_find(cf->frames, framenum);
1983       fdata->flags.visited = 0;
1984       frame_data_cleanup(fdata);
1985     }
1986   }
1987
1988   /* We're done filtering the packets; destroy the progress bar if it
1989      was created. */
1990   if (progbar != NULL)
1991     destroy_progress_dlg(progbar);
1992
1993   /* Unfreeze the packet list. */
1994   if (!add_to_packet_list)
1995     packet_list_recreate_visible_rows();
1996
1997   /* Compute the time it took to filter the file */
1998   compute_elapsed(&start_time);
1999
2000   packet_list_thaw();
2001
2002   if (selected_frame_num == -1) {
2003     /* The selected frame didn't pass the filter. */
2004     if (selected_frame == NULL) {
2005       /* That's because there *was* no selected frame.  Make the first
2006          displayed frame the current frame. */
2007       selected_frame_num = 0;
2008     } else {
2009       /* Find the nearest displayed frame to the selected frame (whether
2010          it's before or after that frame) and make that the current frame.
2011          If the next and previous displayed frames are equidistant from the
2012          selected frame, choose the next one. */
2013       g_assert(following_frame == NULL ||
2014                following_frame->num >= selected_frame->num);
2015       g_assert(preceding_frame == NULL ||
2016                preceding_frame->num <= selected_frame->num);
2017       if (following_frame == NULL) {
2018         /* No frame after the selected frame passed the filter, so we
2019            have to select the last displayed frame before the selected
2020            frame. */
2021         selected_frame_num = preceding_frame_num;
2022         selected_frame = preceding_frame;
2023       } else if (preceding_frame == NULL) {
2024         /* No frame before the selected frame passed the filter, so we
2025            have to select the first displayed frame after the selected
2026            frame. */
2027         selected_frame_num = following_frame_num;
2028         selected_frame = following_frame;
2029       } else {
2030         /* Frames before and after the selected frame passed the filter, so
2031            we'll select the previous frame */
2032         selected_frame_num = preceding_frame_num;
2033         selected_frame = preceding_frame;
2034       }
2035     }
2036   }
2037
2038   if (selected_frame_num == -1) {
2039     /* There are no frames displayed at all. */
2040     cf_unselect_packet(cf);
2041   } else {
2042     /* Either the frame that was selected passed the filter, or we've
2043        found the nearest displayed frame to that frame.  Select it, make
2044        it the focus row, and make it visible. */
2045     /* Set to invalid to force update of packet list and packet details */
2046     cf->current_row = -1;
2047     if (selected_frame_num == 0) {
2048       packet_list_select_first_row();
2049     }else{
2050       if (!packet_list_select_row_from_data(selected_frame)) {
2051         /* We didn't find a row corresponding to this frame.
2052            This means that the frame isn't being displayed currently,
2053            so we can't select it. */
2054         simple_message_box(ESD_TYPE_INFO, NULL,
2055                            "The capture file is probably not fully dissected.",
2056                            "End of capture exceeded!");
2057       }
2058     }
2059   }
2060
2061   /* Cleanup and release all dfilter resources */
2062   dfilter_free(dfcode);
2063 }
2064
2065
2066 /*
2067  * Scan trough all frame data and recalculate the ref time
2068  * without rereading the file.
2069  * XXX - do we need a progres bar or is this fast enough?
2070  */
2071 static void
2072 ref_time_packets(capture_file *cf)
2073 {
2074   guint32     framenum;
2075   frame_data *fdata;
2076
2077   nstime_set_unset(&first_ts);
2078   prev_dis = NULL;
2079   cum_bytes = 0;
2080
2081   for (framenum = 1; framenum <= cf->count; framenum++) {
2082     fdata = frame_data_sequence_find(cf->frames, framenum);
2083
2084     /* just add some value here until we know if it is being displayed or not */
2085     fdata->cum_bytes = cum_bytes + fdata->pkt_len;
2086
2087     /*
2088      *Timestamps
2089      */
2090
2091     /* If we don't have the time stamp of the first packet in the
2092      capture, it's because this is the first packet.  Save the time
2093      stamp of this packet as the time stamp of the first packet. */
2094     if (nstime_is_unset(&first_ts)) {
2095         first_ts  = fdata->abs_ts;
2096     }
2097       /* if this frames is marked as a reference time frame, reset
2098         firstsec and firstusec to this frame */
2099     if (fdata->flags.ref_time) {
2100         first_ts = fdata->abs_ts;
2101     }
2102
2103     /* If we don't have the time stamp of the previous displayed packet,
2104      it's because this is the first displayed packet.  Save the time
2105      stamp of this packet as the time stamp of the previous displayed
2106      packet. */
2107     if (prev_dis == NULL) {
2108         prev_dis = fdata;
2109     }
2110
2111     /* Get the time elapsed between the first packet and this packet. */
2112     nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2113
2114     /* If it's greater than the current elapsed time, set the elapsed time
2115      to it (we check for "greater than" so as not to be confused by
2116      time moving backwards). */
2117     if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2118         || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2119         cf->elapsed_time = fdata->rel_ts;
2120     }
2121
2122     /* If this frame is displayed, get the time elapsed between the
2123      previous displayed packet and this packet. */
2124     if ( fdata->flags.passed_dfilter ) {
2125         fdata->prev_dis = prev_dis;
2126         prev_dis = fdata;
2127     }
2128
2129     /*
2130      * Byte counts
2131      */
2132     if ( (fdata->flags.passed_dfilter) || (fdata->flags.ref_time) ) {
2133         /* This frame either passed the display filter list or is marked as
2134         a time reference frame.  All time reference frames are displayed
2135         even if they dont pass the display filter */
2136         if (fdata->flags.ref_time) {
2137             /* if this was a TIME REF frame we should reset the cum_bytes field */
2138             cum_bytes = fdata->pkt_len;
2139             fdata->cum_bytes =  cum_bytes;
2140         } else {
2141             /* increase cum_bytes with this packets length */
2142             cum_bytes += fdata->pkt_len;
2143         }
2144     }
2145   }
2146 }
2147
2148 typedef enum {
2149   PSP_FINISHED,
2150   PSP_STOPPED,
2151   PSP_FAILED
2152 } psp_return_t;
2153
2154 static psp_return_t
2155 process_specified_packets(capture_file *cf, packet_range_t *range,
2156     const char *string1, const char *string2, gboolean terminate_is_stop,
2157     gboolean (*callback)(capture_file *, frame_data *,
2158                          struct wtap_pkthdr *, const guint8 *, void *),
2159     void *callback_args)
2160 {
2161   guint32          framenum;
2162   frame_data      *fdata;
2163   guint8           pd[WTAP_MAX_PACKET_SIZE+1];
2164   psp_return_t     ret     = PSP_FINISHED;
2165
2166   progdlg_t       *progbar = NULL;
2167   int              progbar_count;
2168   float            progbar_val;
2169   gboolean         progbar_stop_flag;
2170   GTimeVal         progbar_start_time;
2171   gchar            progbar_status_str[100];
2172   int              progbar_nextstep;
2173   int              progbar_quantum;
2174   range_process_e  process_this;
2175   struct wtap_pkthdr phdr;
2176
2177   /* Update the progress bar when it gets to this value. */
2178   progbar_nextstep = 0;
2179   /* When we reach the value that triggers a progress bar update,
2180      bump that value by this amount. */
2181   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2182   /* Count of packets at which we've looked. */
2183   progbar_count = 0;
2184   /* Progress so far. */
2185   progbar_val = 0.0f;
2186
2187   progbar_stop_flag = FALSE;
2188   g_get_current_time(&progbar_start_time);
2189
2190   if (range != NULL)
2191     packet_range_process_init(range);
2192
2193   /* Iterate through all the packets, printing the packets that
2194      were selected by the current display filter.  */
2195   for (framenum = 1; framenum <= cf->count; framenum++) {
2196     fdata = frame_data_sequence_find(cf->frames, framenum);
2197
2198     /* Create the progress bar if necessary.
2199        We check on every iteration of the loop, so that it takes no
2200        longer than the standard time to create it (otherwise, for a
2201        large file, we might take considerably longer than that standard
2202        time in order to get to the next progress bar step). */
2203     if (progbar == NULL)
2204       progbar = delayed_create_progress_dlg(cf->window, string1, string2,
2205                                             terminate_is_stop,
2206                                             &progbar_stop_flag,
2207                                             &progbar_start_time,
2208                                             progbar_val);
2209
2210     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
2211        when we update it, we have to run the GTK+ main loop to get it
2212        to repaint what's pending, and doing so may involve an "ioctl()"
2213        to see if there's any pending input from an X server, and doing
2214        that for every packet can be costly, especially on a big file. */
2215     if (progbar_count >= progbar_nextstep) {
2216       /* let's not divide by zero. I should never be started
2217        * with count == 0, so let's assert that
2218        */
2219       g_assert(cf->count > 0);
2220       progbar_val = (gfloat) progbar_count / cf->count;
2221
2222       if (progbar != NULL) {
2223         g_snprintf(progbar_status_str, sizeof(progbar_status_str),
2224                    "%4u of %u packets", progbar_count, cf->count);
2225         update_progress_dlg(progbar, progbar_val, progbar_status_str);
2226       }
2227
2228       progbar_nextstep += progbar_quantum;
2229     }
2230
2231     if (progbar_stop_flag) {
2232       /* Well, the user decided to abort the operation.  Just stop,
2233          and arrange to return PSP_STOPPED to our caller, so they know
2234          it was stopped explicitly. */
2235       ret = PSP_STOPPED;
2236       break;
2237     }
2238
2239     progbar_count++;
2240
2241     if (range != NULL) {
2242       /* do we have to process this packet? */
2243       process_this = packet_range_process_packet(range, fdata);
2244       if (process_this == range_process_next) {
2245         /* this packet uninteresting, continue with next one */
2246         continue;
2247       } else if (process_this == range_processing_finished) {
2248         /* all interesting packets processed, stop the loop */
2249         break;
2250       }
2251     }
2252
2253     /* Get the packet */
2254     if (!cf_read_frame_r(cf, fdata, &phdr, pd)) {
2255       /* Attempt to get the packet failed. */
2256       ret = PSP_FAILED;
2257       break;
2258     }
2259     /* Process the packet */
2260     if (!callback(cf, fdata, &phdr, pd, callback_args)) {
2261       /* Callback failed.  We assume it reported the error appropriately. */
2262       ret = PSP_FAILED;
2263       break;
2264     }
2265   }
2266
2267   /* We're done printing the packets; destroy the progress bar if
2268      it was created. */
2269   if (progbar != NULL)
2270     destroy_progress_dlg(progbar);
2271
2272   return ret;
2273 }
2274
2275 typedef struct {
2276   gboolean     construct_protocol_tree;
2277   column_info *cinfo;
2278 } retap_callback_args_t;
2279
2280 static gboolean
2281 retap_packet(capture_file *cf _U_, frame_data *fdata,
2282              struct wtap_pkthdr *phdr, const guint8 *pd,
2283              void *argsp)
2284 {
2285   retap_callback_args_t *args = argsp;
2286   epan_dissect_t         edt;
2287
2288   epan_dissect_init(&edt, args->construct_protocol_tree, FALSE);
2289   epan_dissect_run_with_taps(&edt, phdr, pd, fdata, args->cinfo);
2290   epan_dissect_cleanup(&edt);
2291
2292   return TRUE;
2293 }
2294
2295 cf_read_status_t
2296 cf_retap_packets(capture_file *cf)
2297 {
2298   packet_range_t        range;
2299   retap_callback_args_t callback_args;
2300   gboolean              filtering_tap_listeners;
2301   guint                 tap_flags;
2302
2303   /* Do we have any tap listeners with filters? */
2304   filtering_tap_listeners = have_filtering_tap_listeners();
2305
2306   tap_flags = union_of_tap_listener_flags();
2307
2308   /* If any tap listeners have filters, or require the protocol tree,
2309      construct the protocol tree. */
2310   callback_args.construct_protocol_tree = filtering_tap_listeners ||
2311                                           (tap_flags & TL_REQUIRES_PROTO_TREE);
2312
2313   /* If any tap listeners require the columns, construct them. */
2314   callback_args.cinfo = (tap_flags & TL_REQUIRES_COLUMNS) ? &cf->cinfo : NULL;
2315
2316   /* Reset the tap listeners. */
2317   reset_tap_listeners();
2318
2319   /* Iterate through the list of packets, dissecting all packets and
2320      re-running the taps. */
2321   packet_range_init(&range, cf);
2322   packet_range_process_init(&range);
2323   switch (process_specified_packets(cf, &range, "Recalculating statistics on",
2324                                     "all packets", TRUE, retap_packet,
2325                                     &callback_args)) {
2326   case PSP_FINISHED:
2327     /* Completed successfully. */
2328     return CF_READ_OK;
2329
2330   case PSP_STOPPED:
2331     /* Well, the user decided to abort the refiltering.
2332        Return CF_READ_ABORTED so our caller knows they did that. */
2333     return CF_READ_ABORTED;
2334
2335   case PSP_FAILED:
2336     /* Error while retapping. */
2337     return CF_READ_ERROR;
2338   }
2339
2340   g_assert_not_reached();
2341   return CF_READ_OK;
2342 }
2343
2344 typedef struct {
2345   print_args_t *print_args;
2346   gboolean      print_header_line;
2347   char         *header_line_buf;
2348   int           header_line_buf_len;
2349   gboolean      print_formfeed;
2350   gboolean      print_separator;
2351   char         *line_buf;
2352   int           line_buf_len;
2353   gint         *col_widths;
2354   int           num_visible_cols;
2355   gint         *visible_cols;
2356 } print_callback_args_t;
2357
2358 static gboolean
2359 print_packet(capture_file *cf, frame_data *fdata,
2360              struct wtap_pkthdr *phdr, const guint8 *pd,
2361              void *argsp)
2362 {
2363   print_callback_args_t *args = argsp;
2364   epan_dissect_t  edt;
2365   int             i;
2366   char           *cp;
2367   int             line_len;
2368   int             column_len;
2369   int             cp_off;
2370   gboolean        proto_tree_needed;
2371   char            bookmark_name[9+10+1];  /* "__frameNNNNNNNNNN__\0" */
2372   char            bookmark_title[6+10+1]; /* "Frame NNNNNNNNNN__\0"  */
2373
2374   /* Create the protocol tree, and make it visible, if we're printing
2375      the dissection or the hex data.
2376      XXX - do we need it if we're just printing the hex data? */
2377   proto_tree_needed =
2378       args->print_args->print_dissections != print_dissections_none || args->print_args->print_hex || have_custom_cols(&cf->cinfo);
2379   epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2380
2381   /* Fill in the column information if we're printing the summary
2382      information. */
2383   if (args->print_args->print_summary) {
2384     col_custom_prime_edt(&edt, &cf->cinfo);
2385     epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2386     epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2387   } else
2388     epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2389
2390   if (args->print_formfeed) {
2391     if (!new_page(args->print_args->stream))
2392       goto fail;
2393   } else {
2394       if (args->print_separator) {
2395         if (!print_line(args->print_args->stream, 0, ""))
2396           goto fail;
2397       }
2398   }
2399
2400   /*
2401    * We generate bookmarks, if the output format supports them.
2402    * The name is "__frameN__".
2403    */
2404   g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
2405
2406   if (args->print_args->print_summary) {
2407     if (args->print_header_line) {
2408       if (!print_line(args->print_args->stream, 0, args->header_line_buf))
2409         goto fail;
2410       args->print_header_line = FALSE;  /* we might not need to print any more */
2411     }
2412     cp = &args->line_buf[0];
2413     line_len = 0;
2414     for (i = 0; i < args->num_visible_cols; i++) {
2415       /* Find the length of the string for this column. */
2416       column_len = (int) strlen(cf->cinfo.col_data[args->visible_cols[i]]);
2417       if (args->col_widths[i] > column_len)
2418          column_len = args->col_widths[i];
2419
2420       /* Make sure there's room in the line buffer for the column; if not,
2421          double its length. */
2422       line_len += column_len + 1;   /* "+1" for space */
2423       if (line_len > args->line_buf_len) {
2424         cp_off = (int) (cp - args->line_buf);
2425         args->line_buf_len = 2 * line_len;
2426         args->line_buf = g_realloc(args->line_buf, args->line_buf_len + 1);
2427         cp = args->line_buf + cp_off;
2428       }
2429
2430       /* Right-justify the packet number column. */
2431       if (cf->cinfo.col_fmt[args->visible_cols[i]] == COL_NUMBER)
2432         g_snprintf(cp, column_len+1, "%*s", args->col_widths[i], cf->cinfo.col_data[args->visible_cols[i]]);
2433       else
2434         g_snprintf(cp, column_len+1, "%-*s", args->col_widths[i], cf->cinfo.col_data[args->visible_cols[i]]);
2435       cp += column_len;
2436       if (i != args->num_visible_cols - 1)
2437         *cp++ = ' ';
2438     }
2439     *cp = '\0';
2440
2441     /*
2442      * Generate a bookmark, using the summary line as the title.
2443      */
2444     if (!print_bookmark(args->print_args->stream, bookmark_name,
2445                         args->line_buf))
2446       goto fail;
2447
2448     if (!print_line(args->print_args->stream, 0, args->line_buf))
2449       goto fail;
2450   } else {
2451     /*
2452      * Generate a bookmark, using "Frame N" as the title, as we're not
2453      * printing the summary line.
2454      */
2455     g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2456     if (!print_bookmark(args->print_args->stream, bookmark_name,
2457                         bookmark_title))
2458       goto fail;
2459   } /* if (print_summary) */
2460
2461   if (args->print_args->print_dissections != print_dissections_none) {
2462     if (args->print_args->print_summary) {
2463       /* Separate the summary line from the tree with a blank line. */
2464       if (!print_line(args->print_args->stream, 0, ""))
2465         goto fail;
2466     }
2467
2468     /* Print the information in that tree. */
2469     if (!proto_tree_print(args->print_args, &edt, args->print_args->stream))
2470       goto fail;
2471
2472     /* Print a blank line if we print anything after this (aka more than one packet). */
2473     args->print_separator = TRUE;
2474
2475     /* Print a header line if we print any more packet summaries */
2476     args->print_header_line = TRUE;
2477   }
2478
2479   if (args->print_args->print_hex) {
2480     if (args->print_args->print_summary || (args->print_args->print_dissections != print_dissections_none)) {
2481       if (!print_line(args->print_args->stream, 0, ""))
2482         goto fail;
2483     }
2484     /* Print the full packet data as hex. */
2485     if (!print_hex_data(args->print_args->stream, &edt))
2486       goto fail;
2487
2488     /* Print a blank line if we print anything after this (aka more than one packet). */
2489     args->print_separator = TRUE;
2490
2491     /* Print a header line if we print any more packet summaries */
2492     args->print_header_line = TRUE;
2493   } /* if (args->print_args->print_dissections != print_dissections_none) */
2494
2495   epan_dissect_cleanup(&edt);
2496
2497   /* do we want to have a formfeed between each packet from now on? */
2498   if (args->print_args->print_formfeed) {
2499     args->print_formfeed = TRUE;
2500   }
2501
2502   return TRUE;
2503
2504 fail:
2505   epan_dissect_cleanup(&edt);
2506   return FALSE;
2507 }
2508
2509 cf_print_status_t
2510 cf_print_packets(capture_file *cf, print_args_t *print_args)
2511 {
2512   print_callback_args_t callback_args;
2513   gint          data_width;
2514   char         *cp;
2515   int           i, cp_off, column_len, line_len;
2516   int           num_visible_col = 0, last_visible_col = 0, visible_col_count;
2517   psp_return_t  ret;
2518   GList        *clp;
2519   fmt_data     *cfmt;
2520
2521   callback_args.print_args = print_args;
2522   callback_args.print_header_line = TRUE;
2523   callback_args.header_line_buf = NULL;
2524   callback_args.header_line_buf_len = 256;
2525   callback_args.print_formfeed = FALSE;
2526   callback_args.print_separator = FALSE;
2527   callback_args.line_buf = NULL;
2528   callback_args.line_buf_len = 256;
2529   callback_args.col_widths = NULL;
2530   callback_args.num_visible_cols = 0;
2531   callback_args.visible_cols = NULL;
2532
2533   if (!print_preamble(print_args->stream, cf->filename)) {
2534     destroy_print_stream(print_args->stream);
2535     return CF_PRINT_WRITE_ERROR;
2536   }
2537
2538   if (print_args->print_summary) {
2539     /* We're printing packet summaries.  Allocate the header line buffer
2540        and get the column widths. */
2541     callback_args.header_line_buf = g_malloc(callback_args.header_line_buf_len + 1);
2542
2543     /* Find the number of visible columns and the last visible column */
2544     for (i = 0; i < prefs.num_cols; i++) {
2545
2546         clp = g_list_nth(prefs.col_list, i);
2547         if (clp == NULL) /* Sanity check, Invalid column requested */
2548             continue;
2549
2550         cfmt = (fmt_data *) clp->data;
2551         if (cfmt->visible) {
2552             num_visible_col++;
2553             last_visible_col = i;
2554         }
2555     }
2556
2557     /* Find the widths for each of the columns - maximum of the
2558        width of the title and the width of the data - and construct
2559        a buffer with a line containing the column titles. */
2560     callback_args.num_visible_cols = num_visible_col;
2561     callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2562     callback_args.visible_cols = (gint *) g_malloc(sizeof(gint) * num_visible_col);
2563     cp = &callback_args.header_line_buf[0];
2564     line_len = 0;
2565     visible_col_count = 0;
2566     for (i = 0; i < cf->cinfo.num_cols; i++) {
2567
2568       clp = g_list_nth(prefs.col_list, i);
2569       if (clp == NULL) /* Sanity check, Invalid column requested */
2570           continue;
2571
2572       cfmt = (fmt_data *) clp->data;
2573       if (cfmt->visible == FALSE)
2574           continue;
2575
2576       /* Save the order of visible columns */
2577       callback_args.visible_cols[visible_col_count] = i;
2578
2579       /* Don't pad the last column. */
2580       if (i == last_visible_col)
2581         callback_args.col_widths[visible_col_count] = 0;
2582       else {
2583         callback_args.col_widths[visible_col_count] = (gint) strlen(cf->cinfo.col_title[i]);
2584         data_width = get_column_char_width(get_column_format(i));
2585         if (data_width > callback_args.col_widths[visible_col_count])
2586           callback_args.col_widths[visible_col_count] = data_width;
2587       }
2588
2589       /* Find the length of the string for this column. */
2590       column_len = (int) strlen(cf->cinfo.col_title[i]);
2591       if (callback_args.col_widths[i] > column_len)
2592         column_len = callback_args.col_widths[visible_col_count];
2593
2594       /* Make sure there's room in the line buffer for the column; if not,
2595          double its length. */
2596       line_len += column_len + 1;   /* "+1" for space */
2597       if (line_len > callback_args.header_line_buf_len) {
2598         cp_off = (int) (cp - callback_args.header_line_buf);
2599         callback_args.header_line_buf_len = 2 * line_len;
2600         callback_args.header_line_buf = g_realloc(callback_args.header_line_buf,
2601                                                   callback_args.header_line_buf_len + 1);
2602         cp = callback_args.header_line_buf + cp_off;
2603       }
2604
2605       /* Right-justify the packet number column. */
2606 /*      if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2607         g_snprintf(cp, column_len+1, "%*s", callback_args.col_widths[visible_col_count], cf->cinfo.col_title[i]);
2608       else*/
2609       g_snprintf(cp, column_len+1, "%-*s", callback_args.col_widths[visible_col_count], cf->cinfo.col_title[i]);
2610       cp += column_len;
2611       if (i != cf->cinfo.num_cols - 1)
2612         *cp++ = ' ';
2613
2614       visible_col_count++;
2615     }
2616     *cp = '\0';
2617
2618     /* Now start out the main line buffer with the same length as the
2619        header line buffer. */
2620     callback_args.line_buf_len = callback_args.header_line_buf_len;
2621     callback_args.line_buf = g_malloc(callback_args.line_buf_len + 1);
2622   } /* if (print_summary) */
2623
2624   /* Iterate through the list of packets, printing the packets we were
2625      told to print. */
2626   ret = process_specified_packets(cf, &print_args->range, "Printing",
2627                                   "selected packets", TRUE, print_packet,
2628                                   &callback_args);
2629
2630   g_free(callback_args.header_line_buf);
2631   g_free(callback_args.line_buf);
2632   g_free(callback_args.col_widths);
2633   g_free(callback_args.visible_cols);
2634
2635   switch (ret) {
2636
2637   case PSP_FINISHED:
2638     /* Completed successfully. */
2639     break;
2640
2641   case PSP_STOPPED:
2642     /* Well, the user decided to abort the printing.
2643
2644        XXX - note that what got generated before they did that
2645        will get printed if we're piping to a print program; we'd
2646        have to write to a file and then hand that to the print
2647        program to make it actually not print anything. */
2648     break;
2649
2650   case PSP_FAILED:
2651     /* Error while printing.
2652
2653        XXX - note that what got generated before they did that
2654        will get printed if we're piping to a print program; we'd
2655        have to write to a file and then hand that to the print
2656        program to make it actually not print anything. */
2657     destroy_print_stream(print_args->stream);
2658     return CF_PRINT_WRITE_ERROR;
2659   }
2660
2661   if (!print_finale(print_args->stream)) {
2662     destroy_print_stream(print_args->stream);
2663     return CF_PRINT_WRITE_ERROR;
2664   }
2665
2666   if (!destroy_print_stream(print_args->stream))
2667     return CF_PRINT_WRITE_ERROR;
2668
2669   return CF_PRINT_OK;
2670 }
2671
2672 static gboolean
2673 write_pdml_packet(capture_file *cf _U_, frame_data *fdata,
2674                   struct wtap_pkthdr *phdr, const guint8 *pd,
2675           void *argsp)
2676 {
2677   FILE           *fh = argsp;
2678   epan_dissect_t  edt;
2679
2680   /* Create the protocol tree, but don't fill in the column information. */
2681   epan_dissect_init(&edt, TRUE, TRUE);
2682   epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2683
2684   /* Write out the information in that tree. */
2685   proto_tree_write_pdml(&edt, fh);
2686
2687   epan_dissect_cleanup(&edt);
2688
2689   return !ferror(fh);
2690 }
2691
2692 cf_print_status_t
2693 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2694 {
2695   FILE         *fh;
2696   psp_return_t  ret;
2697
2698   fh = ws_fopen(print_args->file, "w");
2699   if (fh == NULL)
2700     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2701
2702   write_pdml_preamble(fh, cf->filename);
2703   if (ferror(fh)) {
2704     fclose(fh);
2705     return CF_PRINT_WRITE_ERROR;
2706   }
2707
2708   /* Iterate through the list of packets, printing the packets we were
2709      told to print. */
2710   ret = process_specified_packets(cf, &print_args->range, "Writing PDML",
2711                                   "selected packets", TRUE,
2712                                   write_pdml_packet, fh);
2713
2714   switch (ret) {
2715
2716   case PSP_FINISHED:
2717     /* Completed successfully. */
2718     break;
2719
2720   case PSP_STOPPED:
2721     /* Well, the user decided to abort the printing. */
2722     break;
2723
2724   case PSP_FAILED:
2725     /* Error while printing. */
2726     fclose(fh);
2727     return CF_PRINT_WRITE_ERROR;
2728   }
2729
2730   write_pdml_finale(fh);
2731   if (ferror(fh)) {
2732     fclose(fh);
2733     return CF_PRINT_WRITE_ERROR;
2734   }
2735
2736   /* XXX - check for an error */
2737   fclose(fh);
2738
2739   return CF_PRINT_OK;
2740 }
2741
2742 static gboolean
2743 write_psml_packet(capture_file *cf, frame_data *fdata,
2744                   struct wtap_pkthdr *phdr, const guint8 *pd,
2745           void *argsp)
2746 {
2747   FILE           *fh = argsp;
2748   epan_dissect_t  edt;
2749   gboolean        proto_tree_needed;
2750
2751   /* Fill in the column information, only create the protocol tree
2752      if having custom columns. */
2753   proto_tree_needed = have_custom_cols(&cf->cinfo);
2754   epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2755   col_custom_prime_edt(&edt, &cf->cinfo);
2756   epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2757   epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2758
2759   /* Write out the information in that tree. */
2760   proto_tree_write_psml(&edt, fh);
2761
2762   epan_dissect_cleanup(&edt);
2763
2764   return !ferror(fh);
2765 }
2766
2767 cf_print_status_t
2768 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2769 {
2770   FILE         *fh;
2771   psp_return_t  ret;
2772
2773   fh = ws_fopen(print_args->file, "w");
2774   if (fh == NULL)
2775     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2776
2777   write_psml_preamble(fh);
2778   if (ferror(fh)) {
2779     fclose(fh);
2780     return CF_PRINT_WRITE_ERROR;
2781   }
2782
2783   /* Iterate through the list of packets, printing the packets we were
2784      told to print. */
2785   ret = process_specified_packets(cf, &print_args->range, "Writing PSML",
2786                                   "selected packets", TRUE,
2787                                   write_psml_packet, fh);
2788
2789   switch (ret) {
2790
2791   case PSP_FINISHED:
2792     /* Completed successfully. */
2793     break;
2794
2795   case PSP_STOPPED:
2796     /* Well, the user decided to abort the printing. */
2797     break;
2798
2799   case PSP_FAILED:
2800     /* Error while printing. */
2801     fclose(fh);
2802     return CF_PRINT_WRITE_ERROR;
2803   }
2804
2805   write_psml_finale(fh);
2806   if (ferror(fh)) {
2807     fclose(fh);
2808     return CF_PRINT_WRITE_ERROR;
2809   }
2810
2811   /* XXX - check for an error */
2812   fclose(fh);
2813
2814   return CF_PRINT_OK;
2815 }
2816
2817 static gboolean
2818 write_csv_packet(capture_file *cf, frame_data *fdata,
2819                  struct wtap_pkthdr *phdr, const guint8 *pd,
2820                  void *argsp)
2821 {
2822   FILE           *fh = argsp;
2823   epan_dissect_t  edt;
2824   gboolean        proto_tree_needed;
2825
2826   /* Fill in the column information, only create the protocol tree
2827      if having custom columns. */
2828   proto_tree_needed = have_custom_cols(&cf->cinfo);
2829   epan_dissect_init(&edt, proto_tree_needed, proto_tree_needed);
2830   col_custom_prime_edt(&edt, &cf->cinfo);
2831   epan_dissect_run(&edt, phdr, pd, fdata, &cf->cinfo);
2832   epan_dissect_fill_in_columns(&edt, FALSE, TRUE);
2833
2834   /* Write out the information in that tree. */
2835   proto_tree_write_csv(&edt, fh);
2836
2837   epan_dissect_cleanup(&edt);
2838
2839   return !ferror(fh);
2840 }
2841
2842 cf_print_status_t
2843 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2844 {
2845   FILE         *fh;
2846   psp_return_t  ret;
2847
2848   fh = ws_fopen(print_args->file, "w");
2849   if (fh == NULL)
2850     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2851
2852   write_csv_preamble(fh);
2853   if (ferror(fh)) {
2854     fclose(fh);
2855     return CF_PRINT_WRITE_ERROR;
2856   }
2857
2858   /* Iterate through the list of packets, printing the packets we were
2859      told to print. */
2860   ret = process_specified_packets(cf, &print_args->range, "Writing CSV",
2861                                   "selected packets", TRUE,
2862                                   write_csv_packet, fh);
2863
2864   switch (ret) {
2865
2866   case PSP_FINISHED:
2867     /* Completed successfully. */
2868     break;
2869
2870   case PSP_STOPPED:
2871     /* Well, the user decided to abort the printing. */
2872     break;
2873
2874   case PSP_FAILED:
2875     /* Error while printing. */
2876     fclose(fh);
2877     return CF_PRINT_WRITE_ERROR;
2878   }
2879
2880   write_csv_finale(fh);
2881   if (ferror(fh)) {
2882     fclose(fh);
2883     return CF_PRINT_WRITE_ERROR;
2884   }
2885
2886   /* XXX - check for an error */
2887   fclose(fh);
2888
2889   return CF_PRINT_OK;
2890 }
2891
2892 static gboolean
2893 write_carrays_packet(capture_file *cf _U_, frame_data *fdata,
2894              struct wtap_pkthdr *phdr,
2895              const guint8 *pd, void *argsp)
2896 {
2897   FILE           *fh = argsp;
2898   epan_dissect_t  edt;
2899
2900   epan_dissect_init(&edt, TRUE, TRUE);
2901   epan_dissect_run(&edt, phdr, pd, fdata, NULL);
2902   proto_tree_write_carrays(fdata->num, fh, &edt);
2903   epan_dissect_cleanup(&edt);
2904
2905   return !ferror(fh);
2906 }
2907
2908 cf_print_status_t
2909 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2910 {
2911   FILE         *fh;
2912   psp_return_t  ret;
2913
2914   fh = ws_fopen(print_args->file, "w");
2915
2916   if (fh == NULL)
2917     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2918
2919   write_carrays_preamble(fh);
2920
2921   if (ferror(fh)) {
2922     fclose(fh);
2923     return CF_PRINT_WRITE_ERROR;
2924   }
2925
2926   /* Iterate through the list of packets, printing the packets we were
2927      told to print. */
2928   ret = process_specified_packets(cf, &print_args->range,
2929                   "Writing C Arrays",
2930                   "selected packets", TRUE,
2931                                   write_carrays_packet, fh);
2932   switch (ret) {
2933   case PSP_FINISHED:
2934     /* Completed successfully. */
2935     break;
2936   case PSP_STOPPED:
2937     /* Well, the user decided to abort the printing. */
2938     break;
2939   case PSP_FAILED:
2940     /* Error while printing. */
2941     fclose(fh);
2942     return CF_PRINT_WRITE_ERROR;
2943   }
2944
2945   write_carrays_finale(fh);
2946
2947   if (ferror(fh)) {
2948     fclose(fh);
2949     return CF_PRINT_WRITE_ERROR;
2950   }
2951
2952   fclose(fh);
2953   return CF_PRINT_OK;
2954 }
2955
2956 gboolean
2957 cf_find_packet_protocol_tree(capture_file *cf, const char *string,
2958                              search_direction dir)
2959 {
2960   match_data mdata;
2961
2962   mdata.string = string;
2963   mdata.string_len = strlen(string);
2964   return find_packet(cf, match_protocol_tree, &mdata, dir);
2965 }
2966
2967 gboolean
2968 cf_find_string_protocol_tree(capture_file *cf, proto_tree *tree,  match_data *mdata)
2969 {
2970   mdata->frame_matched = FALSE;
2971   mdata->string = convert_string_case(cf->sfilter, cf->case_type);
2972   mdata->string_len = strlen(mdata->string);
2973   mdata->cf = cf;
2974   /* Iterate through all the nodes looking for matching text */
2975   proto_tree_children_foreach(tree, match_subtree_text, mdata);
2976   return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
2977 }
2978
2979 static match_result
2980 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2981 {
2982   match_data     *mdata = criterion;
2983   epan_dissect_t  edt;
2984
2985   /* Load the frame's data. */
2986   if (!cf_read_frame(cf, fdata)) {
2987     /* Attempt to get the packet failed. */
2988     return MR_ERROR;
2989   }
2990
2991   /* Construct the protocol tree, including the displayed text */
2992   epan_dissect_init(&edt, TRUE, TRUE);
2993   /* We don't need the column information */
2994   epan_dissect_run(&edt, &cf->phdr, cf->pd, fdata, NULL);
2995
2996   /* Iterate through all the nodes, seeing if they have text that matches. */
2997   mdata->cf = cf;
2998   mdata->frame_matched = FALSE;
2999   proto_tree_children_foreach(edt.tree, match_subtree_text, mdata);
3000   epan_dissect_cleanup(&edt);
3001   return mdata->frame_matched ? MR_MATCHED : MR_NOTMATCHED;
3002 }
3003
3004 static void
3005 match_subtree_text(proto_node *node, gpointer data)
3006 {
3007   match_data   *mdata      = (match_data *) data;
3008   const gchar  *string     = mdata->string;
3009   size_t        string_len = mdata->string_len;
3010   capture_file *cf         = mdata->cf;
3011   field_info   *fi         = PNODE_FINFO(node);
3012   gchar         label_str[ITEM_LABEL_LENGTH];
3013   gchar        *label_ptr;
3014   size_t        label_len;
3015   guint32       i;
3016   guint8        c_char;
3017   size_t        c_match    = 0;
3018
3019   /* dissection with an invisible proto tree? */
3020   g_assert(fi);
3021
3022   if (mdata->frame_matched) {
3023     /* We already had a match; don't bother doing any more work. */
3024     return;
3025   }
3026
3027   /* Don't match invisible entries. */
3028   if (PROTO_ITEM_IS_HIDDEN(node))
3029     return;
3030
3031   /* was a free format label produced? */
3032   if (fi->rep) {
3033     label_ptr = fi->rep->representation;
3034   } else {
3035     /* no, make a generic label */
3036     label_ptr = label_str;
3037     proto_item_fill_label(fi, label_str);
3038   }
3039
3040   /* Does that label match? */
3041   label_len = strlen(label_ptr);
3042   for (i = 0; i < label_len; i++) {
3043     c_char = label_ptr[i];
3044     if (cf->case_type)
3045       c_char = toupper(c_char);
3046     if (c_char == string[c_match]) {
3047       c_match++;
3048       if (c_match == string_len) {
3049         /* No need to look further; we have a match */
3050         mdata->frame_matched = TRUE;
3051         mdata->finfo = fi;
3052         return;
3053       }
3054     } else
3055       c_match = 0;
3056   }
3057
3058   /* Recurse into the subtree, if it exists */
3059   if (node->first_child != NULL)
3060     proto_tree_children_foreach(node, match_subtree_text, mdata);
3061 }
3062
3063 gboolean
3064 cf_find_packet_summary_line(capture_file *cf, const char *string,
3065                             search_direction dir)
3066 {
3067   match_data mdata;
3068
3069   mdata.string = string;
3070   mdata.string_len = strlen(string);
3071   return find_packet(cf, match_summary_line, &mdata, dir);
3072 }
3073
3074 static match_result
3075 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
3076 {
3077   match_data     *mdata      = criterion;
3078   const gchar    *string     = mdata->string;
3079   size_t          string_len = mdata->string_len;
3080   epan_dissect_t  edt;
3081   const char     *info_column;
3082   size_t          info_column_len;
3083   match_result    result     = MR_NOTMATCHED;
3084   gint            colx;
3085   guint32         i;
3086   guint8          c_char;
3087   size_t          c_match    = 0;
3088
3089   /* Load the frame's data. */
3090   if (!cf_read_frame(cf, fdata)) {
3091     /* Attempt to get the packet failed. */
3092     return MR_ERROR;
3093   }
3094
3095   /* Don't bother constructing the protocol tree */
3096   epan_dissect_init(&edt, FALSE, FALSE);
3097   /* Get the column information */
3098   epan_dissect_run(&edt, &cf->phdr, cf->pd, fdata, &cf->cinfo);
3099
3100   /* Find the Info column */
3101   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
3102     if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
3103       /* Found it.  See if we match. */
3104       info_column = edt.pi.cinfo->col_data[colx];
3105       info_column_len = strlen(info_column);
3106       for (i = 0; i < info_column_len; i++) {
3107         c_char = info_column[i];
3108         if (cf->case_type)
3109           c_char = toupper(c_char);
3110         if (c_char == string[c_match]) {
3111           c_match++;
3112           if (c_match == string_len) {
3113             result = MR_MATCHED;
3114             break;
3115           }
3116         } else
3117           c_match = 0;
3118       }
3119       break;
3120     }
3121   }
3122   epan_dissect_cleanup(&edt);
3123   return result;
3124 }
3125
3126 typedef struct {
3127     const guint8 *data;
3128     size_t        data_len;
3129 } cbs_t;    /* "Counted byte string" */
3130
3131 gboolean
3132 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size,
3133                     search_direction dir)
3134 {
3135   cbs_t info;
3136
3137   info.data = string;
3138   info.data_len = string_size;
3139
3140   /* String or hex search? */
3141   if (cf->string) {
3142     /* String search - what type of string? */
3143     switch (cf->scs_type) {
3144
3145     case SCS_ASCII_AND_UNICODE:
3146       return find_packet(cf, match_ascii_and_unicode, &info, dir);
3147
3148     case SCS_ASCII:
3149       return find_packet(cf, match_ascii, &info, dir);
3150
3151     case SCS_UNICODE:
3152       return find_packet(cf, match_unicode, &info, dir);
3153
3154     default:
3155       g_assert_not_reached();
3156       return FALSE;
3157     }
3158   } else
3159     return find_packet(cf, match_binary, &info, dir);
3160 }
3161
3162 static match_result
3163 match_ascii_and_unicode(capture_file *cf, frame_data *fdata, void *criterion)
3164 {
3165   cbs_t        *info       = criterion;
3166   const guint8 *ascii_text = info->data;
3167   size_t        textlen    = info->data_len;
3168   match_result  result;
3169   guint32       buf_len;
3170   guint32       i;
3171   guint8        c_char;
3172   size_t        c_match    = 0;
3173
3174   /* Load the frame's data. */
3175   if (!cf_read_frame(cf, fdata)) {
3176     /* Attempt to get the packet failed. */
3177     return MR_ERROR;
3178   }
3179
3180   result = MR_NOTMATCHED;
3181   buf_len = fdata->cap_len;
3182   i = 0;
3183   while (i < buf_len) {
3184     c_char = cf->pd[i];
3185     if (cf->case_type)
3186       c_char = toupper(c_char);
3187     if (c_char != '\0') {
3188       if (c_char == ascii_text[c_match]) {
3189         c_match += 1;
3190         if (c_match == textlen) {
3191           result = MR_MATCHED;
3192           cf->search_pos = i; /* Save the position of the last character
3193                                  for highlighting the field. */
3194           break;
3195         }
3196       }
3197       else {
3198         g_assert(i>=c_match);
3199         i -= (guint32)c_match;
3200         c_match = 0;
3201       }
3202     }
3203     i += 1;
3204   }
3205   return result;
3206 }
3207
3208 static match_result
3209 match_ascii(capture_file *cf, frame_data *fdata, void *criterion)
3210 {
3211   cbs_t        *info       = criterion;
3212   const guint8 *ascii_text = info->data;
3213   size_t        textlen    = info->data_len;
3214   match_result  result;
3215   guint32       buf_len;
3216   guint32       i;
3217   guint8        c_char;
3218   size_t        c_match    = 0;
3219
3220   /* Load the frame's data. */
3221   if (!cf_read_frame(cf, fdata)) {
3222     /* Attempt to get the packet failed. */
3223     return MR_ERROR;
3224   }
3225
3226   result = MR_NOTMATCHED;
3227   buf_len = fdata->cap_len;
3228   i = 0;
3229   while (i < buf_len) {
3230     c_char = cf->pd[i];
3231     if (cf->case_type)
3232       c_char = toupper(c_char);
3233     if (c_char == ascii_text[c_match]) {
3234       c_match += 1;
3235       if (c_match == textlen) {
3236         result = MR_MATCHED;
3237         cf->search_pos = i; /* Save the position of the last character
3238                                for highlighting the field. */
3239         break;
3240       }
3241     }
3242     else {
3243       g_assert(i>=c_match);
3244       i -= (guint32)c_match;
3245       c_match = 0;
3246     }
3247     i += 1;
3248   }
3249
3250   return result;
3251 }
3252
3253 static match_result
3254 match_unicode(capture_file *cf, frame_data *fdata, void *criterion)
3255 {
3256   cbs_t        *info       = criterion;
3257   const guint8 *ascii_text = info->data;
3258   size_t        textlen    = info->data_len;
3259   match_result  result;
3260   guint32       buf_len;
3261   guint32       i;
3262   guint8        c_char;
3263   size_t        c_match    = 0;
3264
3265   /* Load the frame's data. */
3266   if (!cf_read_frame(cf, fdata)) {
3267     /* Attempt to get the packet failed. */
3268     return MR_ERROR;
3269   }
3270
3271   result = MR_NOTMATCHED;
3272   buf_len = fdata->cap_len;
3273   i = 0;
3274   while (i < buf_len) {
3275     c_char = cf->pd[i];
3276     if (cf->case_type)
3277       c_char = toupper(c_char);
3278     if (c_char == ascii_text[c_match]) {
3279       c_match += 1;
3280       if (c_match == textlen) {
3281         result = MR_MATCHED;
3282         cf->search_pos = i; /* Save the position of the last character
3283                                for highlighting the field. */
3284         break;
3285       }
3286       i += 1;
3287     }
3288     else {
3289       g_assert(i>=(c_match*2));
3290       i -= (guint32)c_match*2;
3291       c_match = 0;
3292     }
3293     i += 1;
3294   }
3295   return result;
3296 }
3297
3298 static match_result
3299 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
3300 {
3301   cbs_t        *info        = criterion;
3302   const guint8 *binary_data = info->data;
3303   size_t        datalen     = info->data_len;
3304   match_result  result;
3305   guint32       buf_len;
3306   guint32       i;
3307   size_t        c_match     = 0;
3308
3309   /* Load the frame's data. */
3310   if (!cf_read_frame(cf, fdata)) {
3311     /* Attempt to get the packet failed. */
3312     return MR_ERROR;
3313   }
3314
3315   result = MR_NOTMATCHED;
3316   buf_len = fdata->cap_len;
3317   i = 0;
3318   while (i < buf_len) {
3319     if (cf->pd[i] == binary_data[c_match]) {
3320       c_match += 1;
3321       if (c_match == datalen) {
3322         result = MR_MATCHED;
3323         cf->search_pos = i; /* Save the position of the last character
3324                                for highlighting the field. */
3325         break;
3326       }
3327     }
3328     else {
3329       g_assert(i>=c_match);
3330       i -= (guint32)c_match;
3331       c_match = 0;
3332     }
3333     i += 1;
3334   }
3335   return result;
3336 }
3337
3338 gboolean
3339 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode,
3340                        search_direction dir)
3341 {
3342   return find_packet(cf, match_dfilter, sfcode, dir);
3343 }
3344
3345 gboolean
3346 cf_find_packet_dfilter_string(capture_file *cf, const char *filter,
3347                               search_direction dir)
3348 {
3349   dfilter_t *sfcode;
3350   gboolean   result;
3351
3352   if (!dfilter_compile(filter, &sfcode)) {
3353      /*
3354       * XXX - this shouldn't happen, as the filter string is machine
3355       * generated
3356       */
3357     return FALSE;
3358   }
3359   if (sfcode == NULL) {
3360     /*
3361      * XXX - this shouldn't happen, as the filter string is machine
3362      * generated.
3363      */
3364     return FALSE;
3365   }
3366   result = find_packet(cf, match_dfilter, sfcode, dir);
3367   dfilter_free(sfcode);
3368   return result;
3369 }
3370
3371 static match_result
3372 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
3373 {
3374   dfilter_t      *sfcode = criterion;
3375   epan_dissect_t  edt;
3376   match_result    result;
3377
3378   /* Load the frame's data. */
3379   if (!cf_read_frame(cf, fdata)) {
3380     /* Attempt to get the packet failed. */
3381     return MR_ERROR;
3382   }
3383
3384   epan_dissect_init(&edt, TRUE, FALSE);
3385   epan_dissect_prime_dfilter(&edt, sfcode);
3386   epan_dissect_run(&edt, &cf->phdr, cf->pd, fdata, NULL);
3387   result = dfilter_apply_edt(sfcode, &edt) ? MR_MATCHED : MR_NOTMATCHED;
3388   epan_dissect_cleanup(&edt);
3389   return result;
3390 }
3391
3392 gboolean
3393 cf_find_packet_marked(capture_file *cf, search_direction dir)
3394 {
3395   return find_packet(cf, match_marked, NULL, dir);
3396 }
3397
3398 static match_result
3399 match_marked(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3400 {
3401   return fdata->flags.marked ? MR_MATCHED : MR_NOTMATCHED;
3402 }
3403
3404 gboolean
3405 cf_find_packet_time_reference(capture_file *cf, search_direction dir)
3406 {
3407   return find_packet(cf, match_time_reference, NULL, dir);
3408 }
3409
3410 static match_result
3411 match_time_reference(capture_file *cf _U_, frame_data *fdata, void *criterion _U_)
3412 {
3413   return fdata->flags.ref_time ? MR_MATCHED : MR_NOTMATCHED;
3414 }
3415
3416 static gboolean
3417 find_packet(capture_file *cf,
3418             match_result (*match_function)(capture_file *, frame_data *, void *),
3419             void *criterion, search_direction dir)
3420 {
3421   frame_data  *start_fd;
3422   guint32      framenum;
3423   frame_data  *fdata;
3424   frame_data  *new_fd = NULL;
3425   progdlg_t   *progbar = NULL;
3426   gboolean     stop_flag;
3427   int          count;
3428   gboolean     found;
3429   float        progbar_val;
3430   GTimeVal     start_time;
3431   gchar        status_str[100];
3432   int          progbar_nextstep;
3433   int          progbar_quantum;
3434   const char  *title;
3435   match_result result;
3436
3437   start_fd = cf->current_frame;
3438   if (start_fd != NULL)  {
3439     /* Iterate through the list of packets, starting at the packet we've
3440        picked, calling a routine to run the filter on the packet, see if
3441        it matches, and stop if so.  */
3442     count = 0;
3443     framenum = start_fd->num;
3444
3445     /* Update the progress bar when it gets to this value. */
3446     progbar_nextstep = 0;
3447     /* When we reach the value that triggers a progress bar update,
3448        bump that value by this amount. */
3449     progbar_quantum = cf->count/N_PROGBAR_UPDATES;
3450     /* Progress so far. */
3451     progbar_val = 0.0f;
3452
3453     stop_flag = FALSE;
3454     g_get_current_time(&start_time);
3455
3456     title = cf->sfilter?cf->sfilter:"";
3457     for (;;) {
3458       /* Create the progress bar if necessary.
3459          We check on every iteration of the loop, so that it takes no
3460          longer than the standard time to create it (otherwise, for a
3461          large file, we might take considerably longer than that standard
3462          time in order to get to the next progress bar step). */
3463       if (progbar == NULL)
3464          progbar = delayed_create_progress_dlg(cf->window, "Searching", title,
3465            FALSE, &stop_flag, &start_time, progbar_val);
3466
3467       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
3468          when we update it, we have to run the GTK+ main loop to get it
3469          to repaint what's pending, and doing so may involve an "ioctl()"
3470          to see if there's any pending input from an X server, and doing
3471          that for every packet can be costly, especially on a big file. */
3472       if (count >= progbar_nextstep) {
3473         /* let's not divide by zero. I should never be started
3474          * with count == 0, so let's assert that
3475          */
3476         g_assert(cf->count > 0);
3477
3478         progbar_val = (gfloat) count / cf->count;
3479
3480         if (progbar != NULL) {
3481           g_snprintf(status_str, sizeof(status_str),
3482                      "%4u of %u packets", count, cf->count);
3483           update_progress_dlg(progbar, progbar_val, status_str);
3484         }
3485
3486         progbar_nextstep += progbar_quantum;
3487       }
3488
3489       if (stop_flag) {
3490         /* Well, the user decided to abort the search.  Go back to the
3491            frame where we started. */
3492         new_fd = start_fd;
3493         break;
3494       }
3495
3496       /* Go past the current frame. */
3497       if (dir == SD_BACKWARD) {
3498         /* Go on to the previous frame. */
3499         if (framenum == 1) {
3500           /*
3501            * XXX - other apps have a bit more of a detailed message
3502            * for this, and instead of offering "OK" and "Cancel",
3503            * they offer things such as "Continue" and "Cancel";
3504            * we need an API for popping up alert boxes with
3505            * {Verb} and "Cancel".
3506            */
3507
3508           if (prefs.gui_find_wrap)
3509           {
3510               statusbar_push_temporary_msg("Search reached the beginning. Continuing at end.");
3511               framenum = cf->count;     /* wrap around */
3512           }
3513           else
3514           {
3515               statusbar_push_temporary_msg("Search reached the beginning.");
3516               framenum = start_fd->num; /* stay on previous packet */
3517           }
3518         } else
3519           framenum--;
3520       } else {
3521         /* Go on to the next frame. */
3522         if (framenum == cf->count) {
3523           if (prefs.gui_find_wrap)
3524           {
3525               statusbar_push_temporary_msg("Search reached the end. Continuing at beginning.");
3526               framenum = 1;             /* wrap around */
3527           }
3528           else
3529           {
3530               statusbar_push_temporary_msg("Search reached the end.");
3531               framenum = start_fd->num; /* stay on previous packet */
3532           }
3533         } else
3534           framenum++;
3535       }
3536       fdata = frame_data_sequence_find(cf->frames, framenum);
3537
3538       count++;
3539
3540       /* Is this packet in the display? */
3541       if (fdata->flags.passed_dfilter) {
3542         /* Yes.  Does it match the search criterion? */
3543         result = (*match_function)(cf, fdata, criterion);
3544         if (result == MR_ERROR) {
3545           /* Error; our caller has reported the error.  Go back to the frame
3546              where we started. */
3547           new_fd = start_fd;
3548           break;
3549         } else if (result == MR_MATCHED) {
3550           /* Yes.  Go to the new frame. */
3551           new_fd = fdata;
3552           break;
3553         }
3554       }
3555
3556       if (fdata == start_fd) {
3557         /* We're back to the frame we were on originally, and that frame
3558            doesn't match the search filter.  The search failed. */
3559         break;
3560       }
3561     }
3562
3563     /* We're done scanning the packets; destroy the progress bar if it
3564        was created. */
3565     if (progbar != NULL)
3566       destroy_progress_dlg(progbar);
3567   }
3568
3569   if (new_fd != NULL) {
3570     /* Find and select */
3571     cf->search_in_progress = TRUE;
3572     found = packet_list_select_row_from_data(new_fd);
3573     cf->search_in_progress = FALSE;
3574     cf->search_pos = 0; /* Reset the position */
3575     if (!found) {
3576       /* We didn't find a row corresponding to this frame.
3577          This means that the frame isn't being displayed currently,
3578          so we can't select it. */
3579       simple_message_box(ESD_TYPE_INFO, NULL,
3580                          "The capture file is probably not fully dissected.",
3581                          "End of capture exceeded!");
3582       return FALSE;
3583     }
3584     return TRUE;    /* success */
3585   } else
3586     return FALSE;   /* failure */
3587 }
3588
3589 gboolean
3590 cf_goto_frame(capture_file *cf, guint fnumber)
3591 {
3592   frame_data *fdata;
3593
3594   fdata = frame_data_sequence_find(cf->frames, fnumber);
3595
3596   if (fdata == NULL) {
3597     /* we didn't find a packet with that packet number */
3598     statusbar_push_temporary_msg("There is no packet number %u.", fnumber);
3599     return FALSE;   /* we failed to go to that packet */
3600   }
3601   if (!fdata->flags.passed_dfilter) {
3602     /* that packet currently isn't displayed */
3603     /* XXX - add it to the set of displayed packets? */
3604     statusbar_push_temporary_msg("Packet number %u isn't displayed.", fnumber);
3605     return FALSE;   /* we failed to go to that packet */
3606   }
3607
3608   if (!packet_list_select_row_from_data(fdata)) {
3609     /* We didn't find a row corresponding to this frame.
3610        This means that the frame isn't being displayed currently,
3611        so we can't select it. */
3612     simple_message_box(ESD_TYPE_INFO, NULL,
3613                        "The capture file is probably not fully dissected.",
3614                        "End of capture exceeded!");
3615     return FALSE;
3616   }
3617   return TRUE;  /* we got to that packet */
3618 }
3619
3620 gboolean
3621 cf_goto_top_frame(void)
3622 {
3623   /* Find and select */
3624   packet_list_select_first_row();
3625   return TRUE;  /* we got to that packet */
3626 }
3627
3628 gboolean
3629 cf_goto_bottom_frame(void)
3630 {
3631   /* Find and select */
3632   packet_list_select_last_row();
3633   return TRUE;  /* we got to that packet */
3634 }
3635
3636 /*
3637  * Go to frame specified by currently selected protocol tree item.
3638  */
3639 gboolean
3640 cf_goto_framenum(capture_file *cf)
3641 {
3642   header_field_info *hfinfo;
3643   guint32            framenum;
3644
3645   if (cf->finfo_selected) {
3646     hfinfo = cf->finfo_selected->hfinfo;
3647     g_assert(hfinfo);
3648     if (hfinfo->type == FT_FRAMENUM) {
3649       framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3650       if (framenum != 0)
3651         return cf_goto_frame(cf, framenum);
3652       }
3653   }
3654
3655   return FALSE;
3656 }
3657
3658 /* Select the packet on a given row. */
3659 void
3660 cf_select_packet(capture_file *cf, int row)
3661 {
3662   epan_dissect_t *old_edt;
3663   frame_data     *fdata;
3664
3665   /* Get the frame data struct pointer for this frame */
3666   fdata = packet_list_get_row_data(row);
3667
3668   if (fdata == NULL) {
3669     /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
3670        the first entry is added to it by "real_insert_row()", that row
3671        is selected (see "real_insert_row()", in "ui/gtk/gtkclist.c", in both
3672        our version and the vanilla GTK+ version).
3673
3674        This means that a "select-row" signal is emitted; this causes
3675        "packet_list_select_cb()" to be called, which causes "cf_select_packet()"
3676        to be called.
3677
3678        "cf_select_packet()" fetches, above, the data associated with the
3679        row that was selected; however, as "gtk_clist_append()", which
3680        called "real_insert_row()", hasn't yet returned, we haven't yet
3681        associated any data with that row, so we get back a null pointer.
3682
3683        We can't assume that there's only one frame in the frame list,
3684        either, as we may be filtering the display.
3685
3686        We therefore assume that, if "row" is 0, i.e. the first row
3687        is being selected, and "cf->first_displayed" equals
3688        "cf->last_displayed", i.e. there's only one frame being
3689        displayed, that frame is the frame we want.
3690
3691        This means we have to set "cf->first_displayed" and
3692        "cf->last_displayed" before adding the row to the
3693        GtkCList; see the comment in "add_packet_to_packet_list()". */
3694
3695        if (row == 0 && cf->first_displayed == cf->last_displayed)
3696          fdata = frame_data_sequence_find(cf->frames, cf->first_displayed);
3697   }
3698
3699   /* If fdata _still_ isn't set simply give up. */
3700   if (fdata == NULL) {
3701     return;
3702   }
3703
3704   /* Get the data in that frame. */
3705   if (!cf_read_frame (cf, fdata)) {
3706     return;
3707   }
3708
3709   /* Record that this frame is the current frame. */
3710   cf->current_frame = fdata;
3711   cf->current_row = row;
3712
3713   old_edt = cf->edt;
3714   /* Create the logical protocol tree. */
3715   /* We don't need the columns here. */
3716   cf->edt = epan_dissect_new(TRUE, TRUE);
3717
3718   tap_build_interesting(cf->edt);
3719   epan_dissect_run(cf->edt, &cf->phdr, cf->pd, cf->current_frame, 
3720           NULL);
3721
3722   dfilter_macro_build_ftv_cache(cf->edt->tree);
3723
3724   cf_callback_invoke(cf_cb_packet_selected, cf);
3725
3726   if (old_edt != NULL)
3727     epan_dissect_free(old_edt);
3728
3729 }
3730
3731 /* Unselect the selected packet, if any. */
3732 void
3733 cf_unselect_packet(capture_file *cf)
3734 {
3735   epan_dissect_t *old_edt = cf->edt;
3736
3737   cf->edt = NULL;
3738
3739   /* No packet is selected. */
3740   cf->current_frame = NULL;
3741   cf->current_row = 0;
3742
3743   cf_callback_invoke(cf_cb_packet_unselected, cf);
3744
3745   /* No protocol tree means no selected field. */
3746   cf_unselect_field(cf);
3747
3748   /* Destroy the epan_dissect_t for the unselected packet. */
3749   if (old_edt != NULL)
3750     epan_dissect_free(old_edt);
3751 }
3752
3753 /* Unset the selected protocol tree field, if any. */
3754 void
3755 cf_unselect_field(capture_file *cf)
3756 {
3757   cf->finfo_selected = NULL;
3758
3759   cf_callback_invoke(cf_cb_field_unselected, cf);
3760 }
3761
3762 /*
3763  * Mark a particular frame.
3764  */
3765 void
3766 cf_mark_frame(capture_file *cf, frame_data *frame)
3767 {
3768   if (! frame->flags.marked) {
3769     frame->flags.marked = TRUE;
3770     if (cf->count > cf->marked_count)
3771       cf->marked_count++;
3772   }
3773 }
3774
3775 /*
3776  * Unmark a particular frame.
3777  */
3778 void
3779 cf_unmark_frame(capture_file *cf, frame_data *frame)
3780 {
3781   if (frame->flags.marked) {
3782     frame->flags.marked = FALSE;
3783     if (cf->marked_count > 0)
3784       cf->marked_count--;
3785   }
3786 }
3787
3788 /*
3789  * Ignore a particular frame.
3790  */
3791 void
3792 cf_ignore_frame(capture_file *cf, frame_data *frame)
3793 {
3794   if (! frame->flags.ignored) {
3795     frame->flags.ignored = TRUE;
3796     if (cf->count > cf->ignored_count)
3797       cf->ignored_count++;
3798   }
3799 }
3800
3801 /*
3802  * Un-ignore a particular frame.
3803  */
3804 void
3805 cf_unignore_frame(capture_file *cf, frame_data *frame)
3806 {
3807   if (frame->flags.ignored) {
3808     frame->flags.ignored = FALSE;
3809     if (cf->ignored_count > 0)
3810       cf->ignored_count--;
3811   }
3812 }
3813
3814 /*
3815  * Read the comment in SHB block
3816  */
3817
3818 const gchar *
3819 cf_read_shb_comment(capture_file *cf)
3820 {
3821   wtapng_section_t *shb_inf;
3822   const gchar      *temp_str;
3823
3824   /* Get info from SHB */
3825   shb_inf = wtap_file_get_shb_info(cf->wth);
3826   if (shb_inf == NULL)
3827         return NULL;
3828   temp_str = shb_inf->opt_comment;
3829   g_free(shb_inf);
3830
3831   return temp_str;
3832
3833 }
3834
3835 void
3836 cf_update_capture_comment(capture_file *cf, gchar *comment)
3837 {
3838   wtapng_section_t *shb_inf;
3839
3840   /* Get info from SHB */
3841   shb_inf = wtap_file_get_shb_info(cf->wth);
3842
3843   /* See if the comment has changed or not */
3844   if (shb_inf && shb_inf->opt_comment) {
3845     if (strcmp(shb_inf->opt_comment, comment) == 0) {
3846       g_free(comment);
3847       g_free(shb_inf);
3848       return;
3849     }
3850   }
3851
3852   g_free(shb_inf);
3853
3854   /* The comment has changed, let's update it */
3855   wtap_write_shb_comment(cf->wth, comment);
3856   /* Mark the file as having unsaved changes */
3857   cf->unsaved_changes = TRUE;
3858 }
3859
3860 void
3861 cf_update_packet_comment(capture_file *cf, frame_data *fdata, gchar *comment)
3862 {
3863   if (fdata->opt_comment != NULL) {
3864     /* OK, remove the old comment. */
3865     g_free(fdata->opt_comment);
3866     fdata->opt_comment = NULL;
3867     cf->packet_comment_count--;
3868   }
3869   if (comment != NULL) {
3870     /* Add the new comment. */
3871     fdata->opt_comment = comment;
3872     cf->packet_comment_count++;
3873   }
3874
3875   /* OK, we have unsaved changes. */
3876   cf->unsaved_changes = TRUE;
3877 }
3878
3879 /*
3880  * Does this capture file have any comments?
3881  */
3882 gboolean
3883 cf_has_comments(capture_file *cf)
3884 {
3885   return (cf_read_shb_comment(cf) != NULL || cf->packet_comment_count != 0);
3886 }
3887
3888 typedef struct {
3889   wtap_dumper *pdh;
3890   const char  *fname;
3891   int          file_type;
3892 } save_callback_args_t;
3893
3894 /*
3895  * Save a capture to a file, in a particular format, saving either
3896  * all packets, all currently-displayed packets, or all marked packets.
3897  *
3898  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3899  * up a message box for the failure.
3900  */
3901 static gboolean
3902 save_packet(capture_file *cf _U_, frame_data *fdata,
3903             struct wtap_pkthdr *phdr, const guint8 *pd,
3904             void *argsp)
3905 {
3906   save_callback_args_t *args = argsp;
3907   struct wtap_pkthdr    hdr;
3908   int           err;
3909   gchar        *display_basename;
3910
3911   /* init the wtap header for saving */
3912   /* TODO: reuse phdr */
3913   /* XXX - these are the only flags that correspond to data that we have
3914      in the frame_data structure and that matter on a per-packet basis.
3915
3916      For WTAP_HAS_CAP_LEN, either the file format has separate "captured"
3917      and "on the wire" lengths, or it doesn't.
3918
3919      For WTAP_HAS_DROP_COUNT, Wiretap doesn't actually supply the value
3920      to its callers.
3921
3922      For WTAP_HAS_PACK_FLAGS, we currently don't save the FCS length
3923      from the packet flags. */
3924   hdr.presence_flags = 0;
3925   if (fdata->flags.has_ts)
3926     hdr.presence_flags |= WTAP_HAS_TS;
3927   if (fdata->flags.has_if_id)
3928     hdr.presence_flags |= WTAP_HAS_INTERFACE_ID;
3929   hdr.ts.secs      = fdata->abs_ts.secs;
3930   hdr.ts.nsecs     = fdata->abs_ts.nsecs;
3931   hdr.caplen       = fdata->cap_len;
3932   hdr.len          = fdata->pkt_len;
3933   hdr.pkt_encap    = fdata->lnk_t;
3934   /* pcapng */
3935   hdr.interface_id = fdata->interface_id;   /* identifier of the interface. */
3936   /* options */
3937   hdr.opt_comment  = fdata->opt_comment; /* NULL if not available */
3938   /* pseudo */
3939   hdr.pseudo_header = phdr->pseudo_header;
3940 #if 0
3941   hdr.drop_count   =
3942   hdr.pack_flags   =     /* XXX - 0 for now (any value for "we don't have it"?) */
3943 #endif
3944   /* and save the packet */
3945   if (!wtap_dump(args->pdh, &hdr, pd, &err)) {
3946     if (err < 0) {
3947       /* Wiretap error. */
3948       switch (err) {
3949
3950       case WTAP_ERR_UNSUPPORTED_ENCAP:
3951         /*
3952          * This is a problem with the particular frame we're writing;
3953          * note that, and give the frame number.
3954          */
3955         simple_error_message_box(
3956                       "Frame %u has a network type that can't be saved in a \"%s\" file.",
3957                       fdata->num, wtap_file_type_string(args->file_type));
3958         break;
3959
3960       default:
3961         display_basename = g_filename_display_basename(args->fname);
3962         simple_error_message_box(
3963                       "An error occurred while writing to the file \"%s\": %s.",
3964                       display_basename, wtap_strerror(err));
3965         g_free(display_basename);
3966         break;
3967       }
3968     } else {
3969       /* OS error. */
3970       write_failure_alert_box(args->fname, err);
3971     }
3972     return FALSE;
3973   }
3974   return TRUE;
3975 }
3976
3977 /*
3978  * Can this capture file be written out in any format using Wiretap
3979  * rather than by copying the raw data?
3980  */
3981 gboolean
3982 cf_can_write_with_wiretap(capture_file *cf)
3983 {
3984   int ft;
3985
3986   for (ft = 0; ft < WTAP_NUM_FILE_TYPES; ft++) {
3987     /* To save a file with Wiretap, Wiretap has to handle that format,
3988        and its code to handle that format must be able to write a file
3989        with this file's encapsulation types. */
3990     if (wtap_dump_can_write_encaps(ft, cf->linktypes)) {
3991       /* OK, we can write it out in this type. */
3992       return TRUE;
3993     }
3994   }
3995
3996   /* No, we couldn't save it in any format. */
3997   return FALSE;
3998 }
3999
4000 /*
4001  * Quick scan to find packet offsets.
4002  */
4003 static cf_read_status_t
4004 rescan_file(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
4005 {
4006   const struct wtap_pkthdr *phdr;
4007   gchar               *err_info;
4008   gchar               *name_ptr;
4009   gint64               data_offset;
4010   gint64               file_pos;
4011   progdlg_t           *progbar        = NULL;
4012   gboolean             stop_flag;
4013   gint64               size;
4014   float                progbar_val;
4015   GTimeVal             start_time;
4016   gchar                status_str[100];
4017   gint64               progbar_nextstep;
4018   gint64               progbar_quantum;
4019   guint32              framenum;
4020   frame_data          *fdata;
4021   int                  count          = 0;
4022 #ifdef HAVE_LIBPCAP
4023   int                  displayed_once = 0;
4024 #endif
4025
4026   /* Close the old handle. */
4027   wtap_close(cf->wth);
4028
4029   /* Open the new file. */
4030   cf->wth = wtap_open_offline(fname, err, &err_info, TRUE);
4031   if (cf->wth == NULL) {
4032     cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
4033     return CF_READ_ERROR;
4034   }
4035
4036   /* We're scanning a file whose contents should be the same as what
4037      we had before, so we don't discard dissection state etc.. */
4038   cf->f_datalen = 0;
4039
4040   /* Set the file name because we need it to set the follow stream filter.
4041      XXX - is that still true?  We need it for other reasons, though,
4042      in any case. */
4043   cf->filename = g_strdup(fname);
4044
4045   /* Indicate whether it's a permanent or temporary file. */
4046   cf->is_tempfile = is_tempfile;
4047
4048   /* No user changes yet. */
4049   cf->unsaved_changes = FALSE;
4050
4051   cf->cd_t        = wtap_file_type(cf->wth);
4052   cf->linktypes = g_array_sized_new(FALSE, FALSE, (guint) sizeof(int), 1);
4053
4054   cf->snap      = wtap_snapshot_length(cf->wth);
4055   if (cf->snap == 0) {
4056     /* Snapshot length not known. */
4057     cf->has_snap = FALSE;
4058     cf->snap = WTAP_MAX_PACKET_SIZE;
4059   } else
4060     cf->has_snap = TRUE;
4061
4062   name_ptr = g_filename_display_basename(cf->filename);
4063
4064   cf_callback_invoke(cf_cb_file_rescan_started, cf);
4065
4066   /* Record whether the file is compressed.
4067      XXX - do we know this at open time? */
4068   cf->iscompressed = wtap_iscompressed(cf->wth);
4069
4070   /* Find the size of the file. */
4071   size = wtap_file_size(cf->wth, NULL);
4072
4073   /* Update the progress bar when it gets to this value. */
4074   progbar_nextstep = 0;
4075   /* When we reach the value that triggers a progress bar update,
4076      bump that value by this amount. */
4077   if (size >= 0) {
4078     progbar_quantum = size/N_PROGBAR_UPDATES;
4079     if (progbar_quantum < MIN_QUANTUM)
4080       progbar_quantum = MIN_QUANTUM;
4081   }else
4082     progbar_quantum = 0;
4083   /* Progress so far. */
4084   progbar_val = 0.0f;
4085
4086   stop_flag = FALSE;
4087   g_get_current_time(&start_time);
4088
4089   framenum = 0;
4090   phdr = wtap_phdr(cf->wth);
4091   while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
4092     framenum++;
4093     fdata = frame_data_sequence_find(cf->frames, framenum);
4094     fdata->file_off = data_offset;
4095     if (size >= 0) {
4096       count++;
4097       file_pos = wtap_read_so_far(cf->wth);
4098
4099       /* Create the progress bar if necessary.
4100        * Check whether it should be created or not every MIN_NUMBER_OF_PACKET
4101        */
4102       if ((progbar == NULL) && !(count % MIN_NUMBER_OF_PACKET)) {
4103         progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
4104         progbar = delayed_create_progress_dlg(cf->window, "Rescanning", name_ptr,
4105                                               TRUE, &stop_flag, &start_time, progbar_val);
4106       }
4107
4108       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
4109          when we update it, we have to run the GTK+ main loop to get it
4110          to repaint what's pending, and doing so may involve an "ioctl()"
4111          to see if there's any pending input from an X server, and doing
4112          that for every packet can be costly, especially on a big file. */
4113       if (file_pos >= progbar_nextstep) {
4114         if (progbar != NULL) {
4115           progbar_val = calc_progbar_val(cf, size, file_pos, status_str, sizeof(status_str));
4116           /* update the packet bar content on the first run or frequently on very large files */
4117 #ifdef HAVE_LIBPCAP
4118           if (progbar_quantum > 500000 || displayed_once == 0) {
4119             if ((auto_scroll_live || displayed_once == 0 || cf->displayed_count < 1000) && cf->count != 0) {
4120               displayed_once = 1;
4121               packets_bar_update();
4122             }
4123           }
4124 #endif /* HAVE_LIBPCAP */
4125           update_progress_dlg(progbar, progbar_val, status_str);
4126         }
4127         progbar_nextstep += progbar_quantum;
4128       }
4129     }
4130
4131     if (stop_flag) {
4132       /* Well, the user decided to abort the rescan.  Sadly, as this
4133          isn't a reread, recovering is difficult, so we'll just
4134          close the current capture. */
4135       break;
4136     }
4137
4138     /* Add this packet's link-layer encapsulation type to cf->linktypes, if
4139        it's not already there.
4140        XXX - yes, this is O(N), so if every packet had a different
4141        link-layer encapsulation type, it'd be O(N^2) to read the file, but
4142        there are probably going to be a small number of encapsulation types
4143        in a file. */
4144     cf_add_encapsulation_type(cf, phdr->pkt_encap);
4145   }
4146
4147   /* Free the display name */
4148   g_free(name_ptr);
4149
4150   /* We're done reading the file; destroy the progress bar if it was created. */
4151   if (progbar != NULL)
4152     destroy_progress_dlg(progbar);
4153
4154   /* We're done reading sequentially through the file. */
4155   cf->state = FILE_READ_DONE;
4156
4157   /* Close the sequential I/O side, to free up memory it requires. */
4158   wtap_sequential_close(cf->wth);
4159
4160   /* compute the time it took to load the file */
4161   compute_elapsed(&start_time);
4162
4163   /* Set the file encapsulation type now; we don't know what it is until
4164      we've looked at all the packets, as we don't know until then whether
4165      there's more than one type (and thus whether it's
4166      WTAP_ENCAP_PER_PACKET). */
4167   cf->lnk_t = wtap_file_encap(cf->wth);
4168
4169   cf_callback_invoke(cf_cb_file_rescan_finished, cf);
4170
4171   if (stop_flag) {
4172     /* Our caller will give up at this point. */
4173     return CF_READ_ABORTED;
4174   }
4175
4176   if (*err != 0) {
4177     /* Put up a message box noting that the read failed somewhere along
4178        the line.  Don't throw out the stuff we managed to read, though,
4179        if any. */
4180     switch (*err) {
4181
4182     case WTAP_ERR_UNSUPPORTED:
4183       simple_error_message_box(
4184                  "The capture file contains record data that Wireshark doesn't support.\n(%s)",
4185                  err_info);
4186       g_free(err_info);
4187       break;
4188
4189     case WTAP_ERR_UNSUPPORTED_ENCAP:
4190       simple_error_message_box(
4191                  "The capture file has a packet with a network type that Wireshark doesn't support.\n(%s)",
4192                  err_info);
4193       g_free(err_info);
4194       break;
4195
4196     case WTAP_ERR_CANT_READ:
4197       simple_error_message_box(
4198                  "An attempt to read from the capture file failed for"
4199                  " some unknown reason.");
4200       break;
4201
4202     case WTAP_ERR_SHORT_READ:
4203       simple_error_message_box(
4204                  "The capture file appears to have been cut short"
4205                  " in the middle of a packet.");
4206       break;
4207
4208     case WTAP_ERR_BAD_FILE:
4209       simple_error_message_box(
4210                  "The capture file appears to be damaged or corrupt.\n(%s)",
4211                  err_info);
4212       g_free(err_info);
4213       break;
4214
4215     case WTAP_ERR_DECOMPRESS:
4216       simple_error_message_box(
4217                  "The compressed capture file appears to be damaged or corrupt.\n"
4218                  "(%s)", err_info);
4219       g_free(err_info);
4220       break;
4221
4222     default:
4223       simple_error_message_box(
4224                  "An error occurred while reading the"
4225                  " capture file: %s.", wtap_strerror(*err));
4226       break;
4227     }
4228     return CF_READ_ERROR;
4229   } else
4230     return CF_READ_OK;
4231 }
4232
4233 cf_write_status_t
4234 cf_save_packets(capture_file *cf, const char *fname, guint save_format,
4235                 gboolean compressed, gboolean discard_comments,
4236                 gboolean dont_reopen)
4237 {
4238   gchar        *fname_new = NULL;
4239   int           err;
4240   gchar        *err_info;
4241   enum {
4242      SAVE_WITH_MOVE,
4243      SAVE_WITH_COPY,
4244      SAVE_WITH_WTAP
4245   }             how_to_save;
4246   wtap_dumper  *pdh;
4247   save_callback_args_t callback_args;
4248 #ifdef _WIN32
4249   gchar        *display_basename;
4250 #endif
4251   guint         framenum;
4252   frame_data   *fdata;
4253
4254   cf_callback_invoke(cf_cb_file_save_started, (gpointer)fname);
4255
4256   if (save_format == cf->cd_t && compressed == cf->iscompressed
4257       && !discard_comments && !cf->unsaved_changes) {
4258     /* We're saving in the format it's already in, and we're
4259        not discarding comments, and there are no changes we have
4260        in memory that aren't saved to the file, so we can just move
4261        or copy the raw data. */
4262
4263     if (cf->is_tempfile) {
4264       /* The file being saved is a temporary file from a live
4265          capture, so it doesn't need to stay around under that name;
4266          first, try renaming the capture buffer file to the new name.
4267          This acts as a "safe save", in that, if the file already
4268          exists, the existing file will be removed only if the rename
4269          succeeds.
4270
4271          Sadly, on Windows, as we have the current capture file
4272          open, even MoveFileEx() with MOVEFILE_REPLACE_EXISTING
4273          (to cause the rename to remove an existing target), as
4274          done by ws_stdio_rename() (ws_rename() is #defined to
4275          be ws_stdio_rename() on Windows) will fail.
4276
4277          According to the MSDN documentation for CreateFile(), if,
4278          when we open a capture file, we were to directly do a CreateFile(),
4279          opening with FILE_SHARE_DELETE|FILE_SHARE_READ, and then
4280          convert it to a file descriptor with _open_osfhandle(),
4281          that would allow the file to be renamed out from under us.
4282
4283          However, that doesn't work in practice.  Perhaps the problem
4284          is that the process doing the rename is the process that
4285          has the file open. */
4286 #ifndef _WIN32
4287       if (ws_rename(cf->filename, fname) == 0) {
4288         /* That succeeded - there's no need to copy the source file. */
4289         how_to_save = SAVE_WITH_MOVE;
4290       } else {
4291         if (errno == EXDEV) {
4292           /* They're on different file systems, so we have to copy the
4293              file. */
4294           how_to_save = SAVE_WITH_COPY;
4295         } else {
4296           /* The rename failed, but not because they're on different
4297              file systems - put up an error message.  (Or should we
4298              just punt and try to copy?  The only reason why I'd
4299              expect the rename to fail and the copy to succeed would
4300              be if we didn't have permission to remove the file from
4301              the temporary directory, and that might be fixable - but
4302              is it worth requiring the user to go off and fix it?) */
4303           cf_rename_failure_alert_box(fname, errno);
4304           goto fail;
4305         }
4306       }
4307 #else
4308       how_to_save = SAVE_WITH_COPY;
4309 #endif
4310     } else {
4311       /* It's a permanent file, so we should copy it, and not remove the
4312          original. */
4313       how_to_save = SAVE_WITH_COPY;
4314     }
4315
4316     if (how_to_save == SAVE_WITH_COPY) {
4317       /* Copy the file, if we haven't moved it.  If we're overwriting
4318          an existing file, we do it with a "safe save", by writing
4319          to a new file and, if the write succeeds, renaming the
4320          new file on top of the old file. */
4321       if (file_exists(fname)) {
4322         fname_new = g_strdup_printf("%s~", fname);
4323         if (!copy_file_binary_mode(cf->filename, fname_new))
4324           goto fail;
4325       } else {
4326         if (!copy_file_binary_mode(cf->filename, fname))
4327           goto fail;
4328       }
4329     }
4330   } else {
4331     /* Either we're saving in a different format or we're saving changes,
4332        such as added, modified, or removed comments, that haven't yet
4333        been written to the underlying file; we can't do that by copying
4334        or moving the capture file, we have to do it by writing the packets
4335        out in Wiretap. */
4336
4337     wtapng_section_t *shb_hdr = NULL;
4338     wtapng_iface_descriptions_t *idb_inf = NULL;
4339     int encap;
4340
4341     shb_hdr = wtap_file_get_shb_info(cf->wth);
4342     idb_inf = wtap_file_get_idb_info(cf->wth);
4343
4344     /* Determine what file encapsulation type we should use. */
4345     encap = wtap_dump_file_encap_type(cf->linktypes);
4346
4347     if (file_exists(fname)) {
4348       /* We're overwriting an existing file; write out to a new file,
4349          and, if that succeeds, rename the new file on top of the
4350          old file.  That makes this a "safe save", so that we don't
4351          lose the old file if we have a problem writing out the new
4352          file.  (If the existing file is the current capture file,
4353          we *HAVE* to do that, otherwise we're overwriting the file
4354          from which we're reading the packets that we're writing!) */
4355       fname_new = g_strdup_printf("%s~", fname);
4356       pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4357                               compressed, shb_hdr, idb_inf, &err);
4358     } else {
4359       pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4360                               compressed, shb_hdr, idb_inf, &err);
4361     }
4362     g_free(idb_inf);
4363     idb_inf = NULL;
4364
4365     if (pdh == NULL) {
4366       cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4367       goto fail;
4368     }
4369
4370     /* Add address resolution */
4371     wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4372
4373     /* Iterate through the list of packets, processing all the packets. */
4374     callback_args.pdh = pdh;
4375     callback_args.fname = fname;
4376     callback_args.file_type = save_format;
4377     switch (process_specified_packets(cf, NULL, "Saving", "packets",
4378                                       TRUE, save_packet, &callback_args)) {
4379
4380     case PSP_FINISHED:
4381       /* Completed successfully. */
4382       break;
4383
4384     case PSP_STOPPED:
4385       /* The user decided to abort the saving.
4386          If we're writing to a temporary file, remove it.
4387          XXX - should we do so even if we're not writing to a
4388          temporary file? */
4389       wtap_dump_close(pdh, &err);
4390       if (fname_new != NULL)
4391         ws_unlink(fname_new);
4392       cf_callback_invoke(cf_cb_file_save_stopped, NULL);
4393       return CF_WRITE_ABORTED;
4394
4395     case PSP_FAILED:
4396       /* Error while saving.
4397          If we're writing to a temporary file, remove it. */
4398       if (fname_new != NULL)
4399         ws_unlink(fname_new);
4400       wtap_dump_close(pdh, &err);
4401       goto fail;
4402     }
4403
4404     if (!wtap_dump_close(pdh, &err)) {
4405       cf_close_failure_alert_box(fname, err);
4406       goto fail;
4407     }
4408
4409     how_to_save = SAVE_WITH_WTAP;
4410   }
4411
4412   if (fname_new != NULL) {
4413     /* We wrote out to fname_new, and should rename it on top of
4414        fname.  fname_new is now closed, so that should be possible even
4415        on Windows.  However, on Windows, we first need to close whatever
4416        file descriptors we have open for fname. */
4417 #ifdef _WIN32
4418     wtap_fdclose(cf->wth);
4419 #endif
4420     /* Now do the rename. */
4421     if (ws_rename(fname_new, fname) == -1) {
4422       /* Well, the rename failed. */
4423       cf_rename_failure_alert_box(fname, errno);
4424 #ifdef _WIN32
4425       /* Attempt to reopen the random file descriptor using the
4426          current file's filename.  (At this point, the sequential
4427          file descriptor is closed.) */
4428       if (!wtap_fdreopen(cf->wth, cf->filename, &err)) {
4429         /* Oh, well, we're screwed. */
4430         display_basename = g_filename_display_basename(cf->filename);
4431         simple_error_message_box(
4432                       file_open_error_message(err, FALSE), display_basename);
4433         g_free(display_basename);
4434       }
4435 #endif
4436       goto fail;
4437     }
4438   }
4439
4440   cf_callback_invoke(cf_cb_file_save_finished, NULL);
4441   cf->unsaved_changes = FALSE;
4442
4443   if (!dont_reopen) {
4444     switch (how_to_save) {
4445
4446     case SAVE_WITH_MOVE:
4447       /* We just moved the file, so the wtap structure refers to the
4448          new file, and all the information other than the filename
4449          and the "is temporary" status applies to the new file; just
4450          update that. */
4451       g_free(cf->filename);
4452       cf->filename = g_strdup(fname);
4453       cf->is_tempfile = FALSE;
4454       cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4455       break;
4456
4457     case SAVE_WITH_COPY:
4458       /* We just copied the file, s all the information other than
4459          the wtap structure, the filename, and the "is temporary"
4460          status applies to the new file; just update that. */
4461       wtap_close(cf->wth);
4462       cf->wth = wtap_open_offline(fname, &err, &err_info, TRUE);
4463       if (cf->wth == NULL) {
4464         cf_open_failure_alert_box(fname, err, err_info, FALSE, 0);
4465         cf_close(cf);
4466       } else {
4467         g_free(cf->filename);
4468         cf->filename = g_strdup(fname);
4469         cf->is_tempfile = FALSE;
4470       }
4471       cf_callback_invoke(cf_cb_file_fast_save_finished, cf);
4472       break;
4473
4474     case SAVE_WITH_WTAP:
4475       /* Open and read the file we saved to.
4476
4477          XXX - this is somewhat of a waste; we already have the
4478          packets, all this gets us is updated file type information
4479          (which we could just stuff into "cf"), and having the new
4480          file be the one we have opened and from which we're reading
4481          the data, and it means we have to spend time opening and
4482          reading the file, which could be a significant amount of
4483          time if the file is large.
4484
4485          If the capture-file-writing code were to return the
4486          seek offset of each packet it writes, we could save that
4487          in the frame_data structure for the frame, and just open
4488          the file without reading it again...
4489
4490          ...as long as, for gzipped files, the process of writing
4491          out the file *also* generates the information needed to
4492          support fast random access to the compressed file. */
4493       if (rescan_file(cf, fname, FALSE, &err) != CF_READ_OK) {
4494         /* The rescan failed; just close the file.  Either
4495            a dialog was popped up for the failure, so the
4496            user knows what happened, or they stopped the
4497            rescan, in which case they know what happened. */
4498         cf_close(cf);
4499       }
4500       break;
4501     }
4502
4503     /* If we were told to discard the comments, do so. */
4504     if (discard_comments) {
4505       /* Remove SHB comment, if any. */
4506       wtap_write_shb_comment(cf->wth, NULL);
4507
4508       /* Remove packet comments. */
4509       for (framenum = 1; framenum <= cf->count; framenum++) {
4510         fdata = frame_data_sequence_find(cf->frames, framenum);
4511         if (fdata->opt_comment) {
4512           g_free(fdata->opt_comment);
4513           fdata->opt_comment = NULL;
4514           cf->packet_comment_count--;
4515         }
4516       }
4517     }
4518   }
4519   return CF_WRITE_OK;
4520
4521 fail:
4522   if (fname_new != NULL) {
4523     /* We were trying to write to a temporary file; get rid of it if it
4524        exists.  (We don't care whether this fails, as, if it fails,
4525        there's not much we can do about it.  I guess if it failed for
4526        a reason other than "it doesn't exist", we could report an
4527        error, so the user knows there's a junk file that they might
4528        want to clean up.) */
4529     ws_unlink(fname_new);
4530     g_free(fname_new);
4531   }
4532   cf_callback_invoke(cf_cb_file_save_failed, NULL);
4533   return CF_WRITE_ERROR;
4534 }
4535
4536 cf_write_status_t
4537 cf_export_specified_packets(capture_file *cf, const char *fname,
4538                             packet_range_t *range, guint save_format,
4539                             gboolean compressed)
4540 {
4541   gchar                       *fname_new = NULL;
4542   int                          err;
4543   wtap_dumper                 *pdh;
4544   save_callback_args_t         callback_args;
4545   wtapng_section_t            *shb_hdr;
4546   wtapng_iface_descriptions_t *idb_inf;
4547   int                          encap;
4548
4549   cf_callback_invoke(cf_cb_file_export_specified_packets_started, (gpointer)fname);
4550
4551   packet_range_process_init(range);
4552
4553   /* We're writing out specified packets from the specified capture
4554      file to another file.  Even if all captured packets are to be
4555      written, don't special-case the operation - read each packet
4556      and then write it out if it's one of the specified ones. */
4557
4558   shb_hdr = wtap_file_get_shb_info(cf->wth);
4559   idb_inf = wtap_file_get_idb_info(cf->wth);
4560
4561   /* Determine what file encapsulation type we should use. */
4562   encap = wtap_dump_file_encap_type(cf->linktypes);
4563
4564   if (file_exists(fname)) {
4565     /* We're overwriting an existing file; write out to a new file,
4566        and, if that succeeds, rename the new file on top of the
4567        old file.  That makes this a "safe save", so that we don't
4568        lose the old file if we have a problem writing out the new
4569        file.  (If the existing file is the current capture file,
4570        we *HAVE* to do that, otherwise we're overwriting the file
4571        from which we're reading the packets that we're writing!) */
4572     fname_new = g_strdup_printf("%s~", fname);
4573     pdh = wtap_dump_open_ng(fname_new, save_format, encap, cf->snap,
4574                             compressed, shb_hdr, idb_inf, &err);
4575   } else {
4576     pdh = wtap_dump_open_ng(fname, save_format, encap, cf->snap,
4577                             compressed, shb_hdr, idb_inf, &err);
4578   }
4579   g_free(idb_inf);
4580   idb_inf = NULL;
4581
4582   if (pdh == NULL) {
4583     cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
4584     goto fail;
4585   }
4586
4587   /* Add address resolution */
4588   wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list());
4589
4590   /* Iterate through the list of packets, processing the packets we were
4591      told to process.
4592
4593      XXX - we've already called "packet_range_process_init(range)", but
4594      "process_specified_packets()" will do it again.  Fortunately,
4595      that's harmless in this case, as we haven't done anything to
4596      "range" since we initialized it. */
4597   callback_args.pdh = pdh;
4598   callback_args.fname = fname;
4599   callback_args.file_type = save_format;
4600   switch (process_specified_packets(cf, range, "Writing", "specified packets",
4601                                     TRUE, save_packet, &callback_args)) {
4602
4603   case PSP_FINISHED:
4604     /* Completed successfully. */
4605     break;
4606
4607   case PSP_STOPPED:
4608       /* The user decided to abort the saving.
4609          If we're writing to a temporary file, remove it.
4610          XXX - should we do so even if we're not writing to a
4611          temporary file? */
4612       wtap_dump_close(pdh, &err);
4613       if (fname_new != NULL)
4614         ws_unlink(fname_new);
4615       cf_callback_invoke(cf_cb_file_export_specified_packets_stopped, NULL);
4616       return CF_WRITE_ABORTED;
4617     break;
4618
4619   case PSP_FAILED:
4620     /* Error while saving.
4621        If we're writing to a temporary file, remove it. */
4622     if (fname_new != NULL)
4623       ws_unlink(fname_new);
4624     wtap_dump_close(pdh, &err);
4625     goto fail;
4626   }
4627
4628   if (!wtap_dump_close(pdh, &err)) {
4629     cf_close_failure_alert_box(fname, err);
4630     goto fail;
4631   }
4632
4633   if (fname_new != NULL) {
4634     /* We wrote out to fname_new, and should rename it on top of
4635        fname; fname is now closed, so that should be possible even
4636        on Windows.  Do the rename. */
4637     if (ws_rename(fname_new, fname) == -1) {
4638       /* Well, the rename failed. */
4639       cf_rename_failure_alert_box(fname, errno);
4640       goto fail;
4641     }
4642   }
4643
4644   cf_callback_invoke(cf_cb_file_export_specified_packets_finished, NULL);
4645   return CF_WRITE_OK;
4646
4647 fail:
4648   if (fname_new != NULL) {
4649     /* We were trying to write to a temporary file; get rid of it if it
4650        exists.  (We don't care whether this fails, as, if it fails,
4651        there's not much we can do about it.  I guess if it failed for
4652        a reason other than "it doesn't exist", we could report an
4653        error, so the user knows there's a junk file that they might
4654        want to clean up.) */
4655     ws_unlink(fname_new);
4656     g_free(fname_new);
4657   }
4658   cf_callback_invoke(cf_cb_file_export_specified_packets_failed, NULL);
4659   return CF_WRITE_ERROR;
4660 }
4661
4662 static void
4663 cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
4664                           gboolean for_writing, int file_type)
4665 {
4666   gchar *display_basename;
4667
4668   if (err < 0) {
4669     /* Wiretap error. */
4670     display_basename = g_filename_display_basename(filename);
4671     switch (err) {
4672
4673     case WTAP_ERR_NOT_REGULAR_FILE:
4674       simple_error_message_box(
4675             "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
4676             display_basename);
4677       break;
4678
4679     case WTAP_ERR_RANDOM_OPEN_PIPE:
4680       /* Seen only when opening a capture file for reading. */
4681       simple_error_message_box(
4682             "The file \"%s\" is a pipe or FIFO; Wireshark can't read pipe or FIFO files.\n"
4683             "To capture from a pipe or FIFO use wireshark -i -",
4684             display_basename);
4685       break;
4686
4687     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
4688       /* Seen only when opening a capture file for reading. */
4689       simple_error_message_box(
4690             "The file \"%s\" isn't a capture file in a format Wireshark understands.",
4691             display_basename);
4692       break;
4693
4694     case WTAP_ERR_UNSUPPORTED:
4695       /* Seen only when opening a capture file for reading. */
4696       simple_error_message_box(
4697             "The file \"%s\" isn't a capture file in a format Wireshark understands.\n"
4698             "(%s)",
4699             display_basename, err_info);
4700       g_free(err_info);
4701       break;
4702
4703     case WTAP_ERR_CANT_WRITE_TO_PIPE:
4704       /* Seen only when opening a capture file for writing. */
4705       simple_error_message_box(
4706             "The file \"%s\" is a pipe, and %s capture files can't be "
4707             "written to a pipe.",
4708             display_basename, wtap_file_type_string(file_type));
4709       break;
4710
4711     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
4712       /* Seen only when opening a capture file for writing. */
4713       simple_error_message_box(
4714             "Wireshark doesn't support writing capture files in that format.");
4715       break;
4716
4717     case WTAP_ERR_UNSUPPORTED_ENCAP:
4718       if (for_writing) {
4719         simple_error_message_box("Wireshark can't save this capture in that format.");
4720       } else {
4721         simple_error_message_box(
4722               "The file \"%s\" is a capture for a network type that Wireshark doesn't support.\n"
4723               "(%s)",
4724               display_basename, err_info);
4725         g_free(err_info);
4726       }
4727       break;
4728
4729     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
4730       if (for_writing) {
4731         simple_error_message_box(
4732               "Wireshark can't save this capture in that format.");
4733       } else {
4734         simple_error_message_box(
4735               "The file \"%s\" is a capture for a network type that Wireshark doesn't support.",
4736               display_basename);
4737       }
4738       break;
4739
4740     case WTAP_ERR_BAD_FILE:
4741       /* Seen only when opening a capture file for reading. */
4742       simple_error_message_box(
4743             "The file \"%s\" appears to be damaged or corrupt.\n"
4744             "(%s)",
4745             display_basename, err_info);
4746       g_free(err_info);
4747       break;
4748
4749     case WTAP_ERR_CANT_OPEN:
4750       if (for_writing) {
4751         simple_error_message_box(
4752               "The file \"%s\" could not be created for some unknown reason.",
4753               display_basename);
4754       } else {
4755         simple_error_message_box(
4756               "The file \"%s\" could not be opened for some unknown reason.",
4757               display_basename);
4758       }
4759       break;
4760
4761     case WTAP_ERR_SHORT_READ:
4762       simple_error_message_box(
4763             "The file \"%s\" appears to have been cut short"
4764             " in the middle of a packet or other data.",
4765             display_basename);
4766       break;
4767
4768     case WTAP_ERR_SHORT_WRITE:
4769       simple_error_message_box(
4770             "A full header couldn't be written to the file \"%s\".",
4771             display_basename);
4772       break;
4773
4774     case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
4775       simple_error_message_box(
4776             "This file type cannot be written as a compressed file.");
4777       break;
4778
4779     case WTAP_ERR_DECOMPRESS:
4780       simple_error_message_box(
4781             "The compressed file \"%s\" appears to be damaged or corrupt.\n"
4782             "(%s)", display_basename, err_info);
4783       g_free(err_info);
4784       break;
4785
4786     default:
4787       simple_error_message_box(
4788             "The file \"%s\" could not be %s: %s.",
4789             display_basename,
4790             for_writing ? "created" : "opened",
4791             wtap_strerror(err));
4792       break;
4793     }
4794     g_free(display_basename);
4795   } else {
4796     /* OS error. */
4797     open_failure_alert_box(filename, err, for_writing);
4798   }
4799 }
4800
4801 /*
4802  * XXX - whether we mention the source pathname, the target pathname,
4803  * or both depends on the error and on what we find if we look for
4804  * one or both of them.
4805  */
4806 static void
4807 cf_rename_failure_alert_box(const char *filename, int err)
4808 {
4809   gchar *display_basename;
4810
4811   display_basename = g_filename_display_basename(filename);
4812   switch (err) {
4813
4814   case ENOENT:
4815     /* XXX - should check whether the source exists and, if not,
4816        report it as the problem and, if so, report the destination
4817        as the problem. */
4818     simple_error_message_box("The path to the file \"%s\" doesn't exist.",
4819                              display_basename);
4820     break;
4821
4822   case EACCES:
4823     /* XXX - if we're doing a rename after a safe save, we should
4824        probably say something else. */
4825     simple_error_message_box("You don't have permission to move the capture file to \"%s\".",
4826                              display_basename);
4827     break;
4828
4829   default:
4830     /* XXX - this should probably mention both the source and destination
4831        pathnames. */
4832     simple_error_message_box("The file \"%s\" could not be moved: %s.",
4833                              display_basename, wtap_strerror(err));
4834     break;
4835   }
4836   g_free(display_basename);
4837 }
4838
4839 /* Check for write errors - if the file is being written to an NFS server,
4840    a write error may not show up until the file is closed, as NFS clients
4841    might not send writes to the server until the "write()" call finishes,
4842    so that the write may fail on the server but the "write()" may succeed. */
4843 static void
4844 cf_close_failure_alert_box(const char *filename, int err)
4845 {
4846   gchar *display_basename;
4847
4848   if (err < 0) {
4849     /* Wiretap error. */
4850     display_basename = g_filename_display_basename(filename);
4851     switch (err) {
4852
4853     case WTAP_ERR_CANT_CLOSE:
4854       simple_error_message_box(
4855             "The file \"%s\" couldn't be closed for some unknown reason.",
4856             display_basename);
4857       break;
4858
4859     case WTAP_ERR_SHORT_WRITE:
4860       simple_error_message_box(
4861             "Not all the packets could be written to the file \"%s\".",
4862                     display_basename);
4863       break;
4864
4865     default:
4866       simple_error_message_box(
4867             "An error occurred while closing the file \"%s\": %s.",
4868             display_basename, wtap_strerror(err));
4869       break;
4870     }
4871     g_free(display_basename);
4872   } else {
4873     /* OS error.
4874        We assume that a close error from the OS is really a write error. */
4875     write_failure_alert_box(filename, err);
4876   }
4877 }
4878
4879 /* Reload the current capture file. */
4880 void
4881 cf_reload(capture_file *cf) {
4882   gchar    *filename;
4883   gboolean  is_tempfile;
4884   int       err;
4885
4886   /* If the file could be opened, "cf_open()" calls "cf_close()"
4887      to get rid of state for the old capture file before filling in state
4888      for the new capture file.  "cf_close()" will remove the file if
4889      it's a temporary file; we don't want that to happen (for one thing,
4890      it'd prevent subsequent reopens from working).  Remember whether it's
4891      a temporary file, mark it as not being a temporary file, and then
4892      reopen it as the type of file it was.
4893
4894      Also, "cf_close()" will free "cf->filename", so we must make
4895      a copy of it first. */
4896   filename = g_strdup(cf->filename);
4897   is_tempfile = cf->is_tempfile;
4898   cf->is_tempfile = FALSE;
4899   if (cf_open(cf, filename, is_tempfile, &err) == CF_OK) {
4900     switch (cf_read(cf, TRUE)) {
4901
4902     case CF_READ_OK:
4903     case CF_READ_ERROR:
4904       /* Just because we got an error, that doesn't mean we were unable
4905          to read any of the file; we handle what we could get from the
4906          file. */
4907       break;
4908
4909     case CF_READ_ABORTED:
4910       /* The user bailed out of re-reading the capture file; the
4911          capture file has been closed - just free the capture file name
4912          string and return (without changing the last containing
4913          directory). */
4914       g_free(filename);
4915       return;
4916     }
4917   } else {
4918     /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
4919        Instead, the file was left open, so we should restore "cf->is_tempfile"
4920        ourselves.
4921
4922        XXX - change the menu?  Presumably "cf_open()" will do that;
4923        make sure it does! */
4924     cf->is_tempfile = is_tempfile;
4925   }
4926   /* "cf_open()" made a copy of the file name we handed it, so
4927      we should free up our copy. */
4928   g_free(filename);
4929 }
4930
4931 /*
4932  * Editor modelines
4933  *
4934  * Local Variables:
4935  * c-basic-offset: 2
4936  * tab-width: 8
4937  * indent-tabs-mode: nil
4938  * End:
4939  *
4940  * ex: set shiftwidth=2 tabstop=8 expandtab:
4941  * :indentSize=2:tabSize=8:noTabs=true:
4942  */