From Francesco Fondelli (bug 2349):
[obnox/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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32
33 #include <time.h>
34
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <signal.h>
41
42 #ifdef HAVE_FCNTL_H
43 #include <fcntl.h>
44 #endif
45
46 #ifdef NEED_STRERROR_H
47 #include "strerror.h"
48 #endif
49
50 #include <epan/epan.h>
51 #include <epan/filesystem.h>
52
53 #include "color.h"
54 #include "color_filters.h"
55 #include "cfile.h"
56 #include <epan/column.h>
57 #include <epan/packet.h>
58 #include "packet-range.h"
59 #include "print.h"
60 #include "file.h"
61 #include "fileset.h"
62 #include "tempfile.h"
63 #include "merge.h"
64 #include "alert_box.h"
65 #include "simple_dialog.h"
66 #include "progress_dlg.h"
67 #include "ui_util.h"
68 #include <epan/prefs.h>
69 #include <epan/dfilter/dfilter.h>
70 #include <epan/conversation.h>
71 #include <epan/epan_dissect.h>
72 #include <epan/tap.h>
73 #include "stat_menu.h"
74 #include "tap_dfilter_dlg.h"
75 #include <epan/dissectors/packet-data.h>
76 #include <epan/dissectors/packet-ber.h>
77 #include <epan/timestamp.h>
78 #include <epan/dfilter/dfilter-macro.h>
79 #include "file_util.h"
80 #include <epan/column-utils.h>
81 #include <epan/strutil.h>
82 #include <epan/emem.h>
83
84 #ifdef HAVE_LIBPCAP
85 gboolean auto_scroll_live;
86 #endif
87
88 static nstime_t first_ts;
89 static nstime_t prev_dis_ts;
90 static guint32 cum_bytes = 0;
91
92 static void cf_reset_state(capture_file *cf);
93
94 static int read_packet(capture_file *cf, dfilter_t *dfcode, gint64 offset);
95
96 static void rescan_packets(capture_file *cf, const char *action, const char *action_item,
97         gboolean refilter, gboolean redissect);
98
99 static gboolean match_protocol_tree(capture_file *cf, frame_data *fdata,
100         void *criterion);
101 static void match_subtree_text(proto_node *node, gpointer data);
102 static gboolean match_summary_line(capture_file *cf, frame_data *fdata,
103         void *criterion);
104 static gboolean match_ascii_and_unicode(capture_file *cf, frame_data *fdata,
105         void *criterion);
106 static gboolean match_ascii(capture_file *cf, frame_data *fdata,
107         void *criterion);
108 static gboolean match_unicode(capture_file *cf, frame_data *fdata,
109         void *criterion);
110 static gboolean match_binary(capture_file *cf, frame_data *fdata,
111         void *criterion);
112 static gboolean match_dfilter(capture_file *cf, frame_data *fdata,
113         void *criterion);
114 static gboolean find_packet(capture_file *cf,
115         gboolean (*match_function)(capture_file *, frame_data *, void *),
116         void *criterion);
117
118 static void cf_open_failure_alert_box(const char *filename, int err,
119                                       gchar *err_info, gboolean for_writing,
120                                       int file_type);
121 static const char *file_rename_error_message(int err);
122 static void cf_write_failure_alert_box(const char *filename, int err);
123 static void cf_close_failure_alert_box(const char *filename, int err);
124 static   gboolean copy_binary_file(const char *from_filename, const char *to_filename);
125
126 /* Update the progress bar this many times when reading a file. */
127 #define N_PROGBAR_UPDATES       100
128
129 /* Number of "frame_data" structures per memory chunk.
130    XXX - is this the right number? */
131 #define FRAME_DATA_CHUNK_SIZE   1024
132
133
134 /* one callback for now, we could have a list later */
135 static cf_callback_t cf_cb = NULL;
136 static gpointer cf_cb_user_data = NULL;
137
138 void
139 cf_callback_invoke(int event, gpointer data)
140 {
141     g_assert(cf_cb != NULL);
142     cf_cb(event, data, cf_cb_user_data);
143 }
144
145
146 void
147 cf_callback_add(cf_callback_t func, gpointer user_data)
148 {
149     /* More than one callback listener is currently not implemented,
150        but should be easy to do. */
151     g_assert(cf_cb == NULL);
152     cf_cb = func;
153     cf_cb_user_data = user_data;
154 }
155
156 void
157 cf_callback_remove(cf_callback_t func _U_)
158 {
159     g_assert(cf_cb != NULL);
160     cf_cb = NULL;
161     cf_cb_user_data = NULL;
162 }
163
164 void
165 cf_timestamp_auto_precision(capture_file *cf)
166 {
167         int prec = timestamp_get_precision();
168
169
170         /* don't try to get the file's precision if none is opened */
171         if(cf->state == FILE_CLOSED) {
172                 return;
173         }
174
175         /* if we are in auto mode, set precision of current file */
176         if(prec == TS_PREC_AUTO ||
177           prec == TS_PREC_AUTO_SEC ||
178           prec == TS_PREC_AUTO_DSEC ||
179           prec == TS_PREC_AUTO_CSEC ||
180           prec == TS_PREC_AUTO_MSEC ||
181           prec == TS_PREC_AUTO_USEC ||
182           prec == TS_PREC_AUTO_NSEC)
183         {
184                 switch(wtap_file_tsprecision(cf->wth)) {
185                 case(WTAP_FILE_TSPREC_SEC):
186                         timestamp_set_precision(TS_PREC_AUTO_SEC);
187                         break;
188                 case(WTAP_FILE_TSPREC_DSEC):
189                         timestamp_set_precision(TS_PREC_AUTO_DSEC);
190                         break;
191                 case(WTAP_FILE_TSPREC_CSEC):
192                         timestamp_set_precision(TS_PREC_AUTO_CSEC);
193                         break;
194                 case(WTAP_FILE_TSPREC_MSEC):
195                         timestamp_set_precision(TS_PREC_AUTO_MSEC);
196                         break;
197                 case(WTAP_FILE_TSPREC_USEC):
198                         timestamp_set_precision(TS_PREC_AUTO_USEC);
199                         break;
200                 case(WTAP_FILE_TSPREC_NSEC):
201                         timestamp_set_precision(TS_PREC_AUTO_NSEC);
202                         break;
203                 default:
204                         g_assert_not_reached();
205                 }
206         }
207 }
208
209
210 cf_status_t
211 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
212 {
213   wtap       *wth;
214   gchar       *err_info;
215
216   wth = wtap_open_offline(fname, err, &err_info, TRUE);
217   if (wth == NULL)
218     goto fail;
219
220   /* The open succeeded.  Close whatever capture file we had open,
221      and fill in the information for this file. */
222   cf_reset_state(cf);
223
224   /* Initialize all data structures used for dissection. */
225   init_dissection();
226
227   /* We're about to start reading the file. */
228   cf->state = FILE_READ_IN_PROGRESS;
229
230   cf->wth = wth;
231   cf->f_datalen = 0;
232
233   /* Set the file name because we need it to set the follow stream filter.
234      XXX - is that still true?  We need it for other reasons, though,
235      in any case. */
236   cf->filename = g_strdup(fname);
237
238   /* Indicate whether it's a permanent or temporary file. */
239   cf->is_tempfile = is_tempfile;
240
241   /* If it's a temporary capture buffer file, mark it as not saved. */
242   cf->user_saved = !is_tempfile;
243
244   cf->cd_t        = wtap_file_type(cf->wth);
245   cf->count     = 0;
246   cf->displayed_count = 0;
247   cf->marked_count = 0;
248   cf->drops_known = FALSE;
249   cf->drops     = 0;
250   cf->snap      = wtap_snapshot_length(cf->wth);
251   if (cf->snap == 0) {
252     /* Snapshot length not known. */
253     cf->has_snap = FALSE;
254     cf->snap = WTAP_MAX_PACKET_SIZE;
255   } else
256     cf->has_snap = TRUE;
257   nstime_set_zero(&cf->elapsed_time);
258   nstime_set_unset(&first_ts);
259   nstime_set_unset(&prev_dis_ts);
260
261   cf->plist_chunk = g_mem_chunk_new("frame_data_chunk",
262         sizeof(frame_data),
263         FRAME_DATA_CHUNK_SIZE * sizeof(frame_data),
264         G_ALLOC_AND_FREE);
265   g_assert(cf->plist_chunk);
266
267   /* change the time formats now, as we might have a new precision */
268   cf_change_time_formats(cf);
269
270   fileset_file_opened(fname);
271
272   if(cf->cd_t == WTAP_FILE_BER) {
273     /* tell the BER dissector the file name */
274     ber_set_filename(cf->filename);
275   }
276
277   return CF_OK;
278
279 fail:
280   cf_open_failure_alert_box(fname, *err, err_info, FALSE, 0);
281   return CF_ERROR;
282 }
283
284
285 /*
286  * Reset the state for the currently closed file, but don't do the
287  * UI callbacks; this is for use in "cf_open()", where we don't
288  * want the UI to go from "file open" to "file closed" back to
289  * "file open", we want it to go from "old file open" to "new file
290  * open and being read".
291  */
292 static void
293 cf_reset_state(capture_file *cf)
294 {
295   /* Die if we're in the middle of reading a file. */
296   g_assert(cf->state != FILE_READ_IN_PROGRESS);
297
298   if (cf->wth) {
299     wtap_close(cf->wth);
300     cf->wth = NULL;
301   }
302   /* We have no file open... */
303   if (cf->filename != NULL) {
304     /* If it's a temporary file, remove it. */
305     if (cf->is_tempfile)
306       eth_unlink(cf->filename);
307     g_free(cf->filename);
308     cf->filename = NULL;
309   }
310   /* ...which means we have nothing to save. */
311   cf->user_saved = FALSE;
312
313   if (cf->plist_chunk != NULL) {
314     g_mem_chunk_destroy(cf->plist_chunk);
315     cf->plist_chunk = NULL;
316   }
317   if (cf->rfcode != NULL) {
318     dfilter_free(cf->rfcode);
319     cf->rfcode = NULL;
320   }
321   cf->plist = NULL;
322   cf->plist_end = NULL;
323   cf_unselect_packet(cf);       /* nothing to select */
324   cf->first_displayed = NULL;
325   cf->last_displayed = NULL;
326
327   /* No frame selected, no field in that frame selected. */
328   cf->current_frame = NULL;
329   cf->finfo_selected = NULL;
330
331   /* Clear the packet list. */
332   packet_list_freeze();
333   packet_list_clear();
334   packet_list_thaw();
335
336   cf->f_datalen = 0;
337   cf->count = 0;
338   nstime_set_zero(&cf->elapsed_time);
339
340   reset_tap_listeners();
341
342   /* We have no file open. */
343   cf->state = FILE_CLOSED;
344
345   fileset_file_closed();
346 }
347
348 /* Reset everything to a pristine state */
349 void
350 cf_close(capture_file *cf)
351 {
352   /* do GUI things even if file is already closed,
353    * e.g. to cleanup things if a capture couldn't be started */
354   cf_callback_invoke(cf_cb_file_closing, cf);
355
356   /* close things, if not already closed before */
357   if(cf->state != FILE_CLOSED) {
358
359           color_filters_cleanup();
360
361           cf_reset_state(cf);
362
363           cleanup_dissection();
364   }
365
366   cf_callback_invoke(cf_cb_file_closed, cf);
367 }
368
369 /* an out of memory exception occured, wait for a user button press to exit */
370 void outofmemory_cb(gpointer dialog _U_, gint btn _U_, gpointer data _U_)
371 {
372     main_window_exit();
373 }
374
375 cf_read_status_t
376 cf_read(capture_file *cf)
377 {
378   int         err;
379   gchar       *err_info;
380   const gchar *name_ptr;
381   const char  *errmsg;
382   char         errmsg_errno[1024+1];
383   gchar        err_str[2048+1];
384   gint64       data_offset;
385   progdlg_t *volatile progbar = NULL;
386   gboolean     stop_flag;
387   volatile gint64 size;
388   gint64       file_pos;
389   volatile float progbar_val;
390   GTimeVal     start_time;
391   gchar        status_str[100];
392   volatile gint64 progbar_nextstep;
393   volatile gint64 progbar_quantum;
394   dfilter_t   *dfcode;
395
396   /* Compile the current display filter.
397    * We assume this will not fail since cf->dfilter is only set in
398    * cf_filter IFF the filter was valid.
399    */
400   dfcode=NULL;
401   if(cf->dfilter){
402     dfilter_compile(cf->dfilter, &dfcode);
403   }
404
405   cum_bytes=0;
406
407   reset_tap_listeners();
408   tap_dfilter_dlg_update();
409
410   cf_callback_invoke(cf_cb_file_read_start, cf);
411
412   name_ptr = get_basename(cf->filename);
413
414   /* Find the size of the file. */
415   size = wtap_file_size(cf->wth, NULL);
416
417   /* Update the progress bar when it gets to this value. */
418   progbar_nextstep = 0;
419   /* When we reach the value that triggers a progress bar update,
420      bump that value by this amount. */
421   if (size >= 0)
422     progbar_quantum = size/N_PROGBAR_UPDATES;
423   else
424     progbar_quantum = 0;
425   /* Progress so far. */
426   progbar_val = 0.0;
427
428   packet_list_freeze();
429
430   stop_flag = FALSE;
431   g_get_current_time(&start_time);
432
433   while ((wtap_read(cf->wth, &err, &err_info, &data_offset))) {
434     if (size >= 0) {
435       /* Create the progress bar if necessary.
436          We check on every iteration of the loop, so that it takes no
437          longer than the standard time to create it (otherwise, for a
438          large file, we might take considerably longer than that standard
439          time in order to get to the next progress bar step). */
440       if (progbar == NULL) {
441         progbar = delayed_create_progress_dlg("Loading", name_ptr,
442           TRUE, &stop_flag, &start_time, progbar_val);
443       }
444
445       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
446          when we update it, we have to run the GTK+ main loop to get it
447          to repaint what's pending, and doing so may involve an "ioctl()"
448          to see if there's any pending input from an X server, and doing
449          that for every packet can be costly, especially on a big file. */
450       if (data_offset >= progbar_nextstep) {
451           file_pos = wtap_read_so_far(cf->wth, NULL);
452           progbar_val = (gfloat) file_pos / (gfloat) size;
453           if (progbar_val > 1.0) {
454             /* The file probably grew while we were reading it.
455                Update file size, and try again. */
456             size = wtap_file_size(cf->wth, NULL);
457             if (size >= 0)
458               progbar_val = (gfloat) file_pos / (gfloat) size;
459             /* If it's still > 1, either "wtap_file_size()" failed (in which
460                case there's not much we can do about it), or the file
461                *shrank* (in which case there's not much we can do about
462                it); just clip the progress value at 1.0. */
463             if (progbar_val > 1.0)
464               progbar_val = 1.0;
465           }
466           if (progbar != NULL) {
467                 /* update the packet lists content on the first run or frequently on very large files */
468               /* (on smaller files the display update takes longer than reading the file) */
469 #ifdef HAVE_LIBPCAP
470               if(progbar_quantum > 500000 || progbar_nextstep == 0) {
471             packet_list_thaw();
472             if (auto_scroll_live && cf->plist_end != NULL)
473               packet_list_moveto_end();
474             packet_list_freeze();
475               }
476 #endif
477
478             g_snprintf(status_str, sizeof(status_str),
479                        "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
480                        file_pos / 1024, size / 1024);
481             update_progress_dlg(progbar, progbar_val, status_str);
482           }
483          progbar_nextstep += progbar_quantum;
484       }
485     }
486
487     if (stop_flag) {
488       /* Well, the user decided to abort the read. He/She will be warned and
489          it might be enough for him/her to work with the already loaded
490          packets.
491          This is especially true for very large capture files, where you don't
492          want to wait loading the whole file (which may last minutes or even
493          hours even on fast machines) just to see that it was the wrong file. */
494       break;
495     }
496     TRY {
497         read_packet(cf, dfcode, data_offset);
498     }
499     CATCH(OutOfMemoryError) {
500         gpointer dialog;
501
502         dialog = simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
503               "%sOut Of Memory!%s\n"
504               "\n"
505               "Sorry, but Wireshark has to terminate now!\n"
506               "\n"
507               "Some infos / workarounds can be found at:\n"
508               "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
509               simple_dialog_primary_start(), simple_dialog_primary_end());
510         /* we have to terminate, as we cannot recover from the memory error */
511         simple_dialog_set_cb(dialog, outofmemory_cb, NULL);
512         while(1) {
513             main_window_update();
514             /* XXX - how to avoid a busy wait? */
515             /* Sleep(100); */
516         };
517         break;
518     }
519     ENDTRY;
520   }
521
522   /* Cleanup and release all dfilter resources */
523   if (dfcode != NULL){
524     dfilter_free(dfcode);
525   }
526
527   /* We're done reading the file; destroy the progress bar if it was created. */
528   if (progbar != NULL)
529     destroy_progress_dlg(progbar);
530
531   /* We're done reading sequentially through the file. */
532   cf->state = FILE_READ_DONE;
533
534   /* Close the sequential I/O side, to free up memory it requires. */
535   wtap_sequential_close(cf->wth);
536
537   /* Allow the protocol dissectors to free up memory that they
538    * don't need after the sequential run-through of the packets. */
539   postseq_cleanup_all_protocols();
540
541   /* Set the file encapsulation type now; we don't know what it is until
542      we've looked at all the packets, as we don't know until then whether
543      there's more than one type (and thus whether it's
544      WTAP_ENCAP_PER_PACKET). */
545   cf->lnk_t = wtap_file_encap(cf->wth);
546
547   cf->current_frame = cf->first_displayed;
548   packet_list_thaw();
549
550   cf_callback_invoke(cf_cb_file_read_finished, cf);
551
552   /* If we have any displayed packets to select, select the first of those
553      packets by making the first row the selected row. */
554   if (cf->first_displayed != NULL)
555     packet_list_select_row(0);
556
557   if(stop_flag) {
558     simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
559           "%sFile loading was cancelled!%s\n"
560           "\n"
561                   "The remaining packets in the file were discarded.\n"
562           "\n"
563           "As a lot of packets from the original file will be missing,\n"
564                   "remember to be careful when saving the current content to a file.\n",
565           simple_dialog_primary_start(), simple_dialog_primary_end());
566     return CF_READ_ERROR;
567   }
568
569   if (err != 0) {
570     /* Put up a message box noting that the read failed somewhere along
571        the line.  Don't throw out the stuff we managed to read, though,
572        if any. */
573     switch (err) {
574
575     case WTAP_ERR_UNSUPPORTED_ENCAP:
576       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
577                "The capture file has a packet with a network type that Wireshark doesn't support.\n(%s)",
578                err_info);
579       g_free(err_info);
580       errmsg = errmsg_errno;
581       break;
582
583     case WTAP_ERR_CANT_READ:
584       errmsg = "An attempt to read from the capture file failed for"
585                " some unknown reason.";
586       break;
587
588     case WTAP_ERR_SHORT_READ:
589       errmsg = "The capture file appears to have been cut short"
590                " in the middle of a packet.";
591       break;
592
593     case WTAP_ERR_BAD_RECORD:
594       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
595                "The capture file appears to be damaged or corrupt.\n(%s)",
596                err_info);
597       g_free(err_info);
598       errmsg = errmsg_errno;
599       break;
600
601     default:
602       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
603                "An error occurred while reading the"
604                " capture file: %s.", wtap_strerror(err));
605       errmsg = errmsg_errno;
606       break;
607     }
608     g_snprintf(err_str, sizeof err_str, errmsg);
609     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, err_str);
610     return CF_READ_ERROR;
611   } else
612     return CF_READ_OK;
613 }
614
615 #ifdef HAVE_LIBPCAP
616 cf_status_t
617 cf_start_tail(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
618 {
619   cf_status_t cf_status;
620
621   cf_status = cf_open(cf, fname, is_tempfile, err);
622   return cf_status;
623 }
624
625 cf_read_status_t
626 cf_continue_tail(capture_file *cf, volatile int to_read, int *err)
627 {
628   gint64 data_offset = 0;
629   gchar *err_info;
630   volatile int newly_displayed_packets = 0;
631   dfilter_t   *dfcode;
632
633   /* Compile the current display filter.
634    * We assume this will not fail since cf->dfilter is only set in
635    * cf_filter IFF the filter was valid.
636    */
637   dfcode=NULL;
638   if(cf->dfilter){
639     dfilter_compile(cf->dfilter, &dfcode);
640   }
641
642   *err = 0;
643
644   packet_list_check_end();
645   packet_list_freeze();
646
647   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: %u new: %u", cf->count, to_read);*/
648
649   while (to_read != 0 && (wtap_read(cf->wth, err, &err_info, &data_offset))) {
650     if (cf->state == FILE_READ_ABORTED) {
651       /* Well, the user decided to exit Wireshark.  Break out of the
652          loop, and let the code below (which is called even if there
653          aren't any packets left to read) exit. */
654       break;
655     }
656     TRY{
657         if (read_packet(cf, dfcode, data_offset) != -1) {
658             newly_displayed_packets++;
659         }
660     }
661     CATCH(OutOfMemoryError) {
662         gpointer dialog;
663
664         dialog = simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
665               "%sOut Of Memory!%s\n"
666               "\n"
667               "Sorry, but Wireshark has to terminate now!\n"
668               "\n"
669               "The capture file is not lost, it can be found at:\n"
670               "%s\n"
671               "\n"
672               "Some infos / workarounds can be found at:\n"
673               "http://wiki.wireshark.org/KnownBugs/OutOfMemory",
674               simple_dialog_primary_start(), simple_dialog_primary_end(), cf->filename);
675         /* we have to terminate, as we cannot recover from the memory error */
676         simple_dialog_set_cb(dialog, outofmemory_cb, NULL);
677         while(1) {
678             main_window_update();
679             /* XXX - how to avoid a busy wait? */
680             /* Sleep(100); */
681         };
682         packet_list_thaw();
683         return CF_READ_ABORTED;
684     }
685     ENDTRY;
686     to_read--;
687   }
688
689   /* Cleanup and release all dfilter resources */
690   if (dfcode != NULL){
691     dfilter_free(dfcode);
692   }
693
694   /*g_log(NULL, G_LOG_LEVEL_MESSAGE, "cf_continue_tail: count %u state: %u err: %u",
695           cf->count, cf->state, *err);*/
696
697   /* XXX - this causes "flickering" of the list */
698   packet_list_thaw();
699
700   /* moving to the end of the packet list - if the user requested so and
701      we have some new packets.
702      this doesn't seem to work well with a frozen GTK_Clist, so do this after
703      packet_list_thaw() is done, see bugzilla 1188 */
704   /* XXX - this cheats and looks inside the packet list to find the final
705      row number. */
706   if (newly_displayed_packets && auto_scroll_live && cf->plist_end != NULL)
707     packet_list_moveto_end();
708
709   if (cf->state == FILE_READ_ABORTED) {
710     /* Well, the user decided to exit Wireshark.  Return CF_READ_ABORTED
711        so that our caller can kill off the capture child process;
712        this will cause an EOF on the pipe from the child, so
713        "cf_finish_tail()" will be called, and it will clean up
714        and exit. */
715     return CF_READ_ABORTED;
716   } else if (*err != 0) {
717     /* We got an error reading the capture file.
718        XXX - pop up a dialog box instead? */
719         g_warning("Error \"%s\" while reading: \"%s\"\n",
720                 wtap_strerror(*err), cf->filename);
721
722     return CF_READ_ERROR;
723   } else
724     return CF_READ_OK;
725 }
726
727 cf_read_status_t
728 cf_finish_tail(capture_file *cf, int *err)
729 {
730   gchar *err_info;
731   gint64 data_offset;
732   dfilter_t   *dfcode;
733
734   /* Compile the current display filter.
735    * We assume this will not fail since cf->dfilter is only set in
736    * cf_filter IFF the filter was valid.
737    */
738   dfcode=NULL;
739   if(cf->dfilter){
740     dfilter_compile(cf->dfilter, &dfcode);
741   }
742
743   if(cf->wth == NULL) {
744     cf_close(cf);
745     return CF_READ_ERROR;
746   }
747
748   packet_list_check_end();
749   packet_list_freeze();
750
751   while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
752     if (cf->state == FILE_READ_ABORTED) {
753       /* Well, the user decided to abort the read.  Break out of the
754          loop, and let the code below (which is called even if there
755          aren't any packets left to read) exit. */
756       break;
757     }
758         read_packet(cf, dfcode, data_offset);
759   }
760
761   /* Cleanup and release all dfilter resources */
762   if (dfcode != NULL){
763     dfilter_free(dfcode);
764   }
765
766   packet_list_thaw();
767
768   if (cf->state == FILE_READ_ABORTED) {
769     /* Well, the user decided to abort the read.  We're only called
770        when the child capture process closes the pipe to us (meaning
771        it's probably exited), so we can just close the capture
772        file; we return CF_READ_ABORTED so our caller can do whatever
773        is appropriate when that happens. */
774     cf_close(cf);
775     return CF_READ_ABORTED;
776   }
777
778   if (auto_scroll_live && cf->plist_end != NULL)
779     /* XXX - this cheats and looks inside the packet list to find the final
780        row number. */
781     packet_list_moveto_end();
782
783   /* We're done reading sequentially through the file. */
784   cf->state = FILE_READ_DONE;
785
786   /* We're done reading sequentially through the file; close the
787      sequential I/O side, to free up memory it requires. */
788   wtap_sequential_close(cf->wth);
789
790   /* Allow the protocol dissectors to free up memory that they
791    * don't need after the sequential run-through of the packets. */
792   postseq_cleanup_all_protocols();
793
794   /* Set the file encapsulation type now; we don't know what it is until
795      we've looked at all the packets, as we don't know until then whether
796      there's more than one type (and thus whether it's
797      WTAP_ENCAP_PER_PACKET). */
798   cf->lnk_t = wtap_file_encap(cf->wth);
799
800   if (*err != 0) {
801     /* We got an error reading the capture file.
802        XXX - pop up a dialog box? */
803     return CF_READ_ERROR;
804   } else {
805     return CF_READ_OK;
806   }
807 }
808 #endif /* HAVE_LIBPCAP */
809
810 const gchar *
811 cf_get_display_name(capture_file *cf)
812 {
813   const gchar *displayname;
814
815   /* Return a name to use in displays */
816   if (!cf->is_tempfile) {
817     /* Get the last component of the file name, and use that. */
818     if (cf->filename){
819       displayname = get_basename(cf->filename);
820     } else {
821       displayname="(No file)";
822     }
823   } else {
824     /* The file we read is a temporary file from a live capture;
825        we don't mention its name. */
826     displayname = "(Untitled)";
827   }
828   return displayname;
829 }
830
831 /* XXX - use a macro instead? */
832 int
833 cf_get_packet_count(capture_file *cf)
834 {
835     return cf->count;
836 }
837
838 /* XXX - use a macro instead? */
839 void
840 cf_set_packet_count(capture_file *cf, int packet_count)
841 {
842     cf->count = packet_count;
843 }
844
845 /* XXX - use a macro instead? */
846 gboolean
847 cf_is_tempfile(capture_file *cf)
848 {
849     return cf->is_tempfile;
850 }
851
852 void cf_set_tempfile(capture_file *cf, gboolean is_tempfile)
853 {
854     cf->is_tempfile = is_tempfile;
855 }
856
857
858 /* XXX - use a macro instead? */
859 void cf_set_drops_known(capture_file *cf, gboolean drops_known)
860 {
861     cf->drops_known = drops_known;
862 }
863
864 /* XXX - use a macro instead? */
865 void cf_set_drops(capture_file *cf, guint32 drops)
866 {
867     cf->drops = drops;
868 }
869
870 /* XXX - use a macro instead? */
871 gboolean cf_get_drops_known(capture_file *cf)
872 {
873     return cf->drops_known;
874 }
875
876 /* XXX - use a macro instead? */
877 guint32 cf_get_drops(capture_file *cf)
878 {
879     return cf->drops;
880 }
881
882 void cf_set_rfcode(capture_file *cf, dfilter_t *rfcode)
883 {
884     cf->rfcode = rfcode;
885 }
886
887 static int
888 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
889         dfilter_t *dfcode,
890         union wtap_pseudo_header *pseudo_header, const guchar *buf,
891         gboolean refilter)
892 {
893   gint          row;
894   gboolean      create_proto_tree = FALSE;
895   epan_dissect_t *edt;
896
897   /* just add some value here until we know if it is being displayed or not */
898   fdata->cum_bytes  = cum_bytes + fdata->pkt_len;
899
900   /* If we don't have the time stamp of the first packet in the
901      capture, it's because this is the first packet.  Save the time
902      stamp of this packet as the time stamp of the first packet. */
903   if (nstime_is_unset(&first_ts)) {
904     first_ts  = fdata->abs_ts;
905   }
906   /* if this frames is marked as a reference time frame, reset
907      firstsec and firstusec to this frame */
908   if(fdata->flags.ref_time){
909     first_ts = fdata->abs_ts;
910   }
911
912   /* If we don't have the time stamp of the previous displayed packet,
913      it's because this is the first displayed packet.  Save the time
914      stamp of this packet as the time stamp of the previous displayed
915      packet. */
916   if (nstime_is_unset(&prev_dis_ts)) {
917     prev_dis_ts = fdata->abs_ts;
918   }
919
920   /* Get the time elapsed between the first packet and this packet. */
921   nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
922
923   /* If it's greater than the current elapsed time, set the elapsed time
924      to it (we check for "greater than" so as not to be confused by
925      time moving backwards). */
926   if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
927   || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
928     cf->elapsed_time = fdata->rel_ts;
929   }
930
931   /* Get the time elapsed between the previous displayed packet and
932      this packet. */
933   nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
934
935   /* If either
936
937         we have a display filter and are re-applying it;
938
939         we have a list of color filters;
940
941         we have tap listeners;
942
943         we have custom columns;
944
945      allocate a protocol tree root node, so that we'll construct
946      a protocol tree against which a filter expression can be
947      evaluated. */
948   if ((dfcode != NULL && refilter) || color_filters_used()
949       || num_tap_filters != 0 || have_custom_cols(&cf->cinfo))
950           create_proto_tree = TRUE;
951
952   /* Dissect the frame. */
953   edt = epan_dissect_new(create_proto_tree, FALSE);
954
955   if (dfcode != NULL && refilter) {
956       epan_dissect_prime_dfilter(edt, dfcode);
957   }
958   /* prepare color filters */
959   if (color_filters_used()) {
960       color_filters_prime_edt(edt);
961   }
962
963   col_custom_prime_edt(edt, &cf->cinfo);
964
965   tap_queue_init(edt);
966   epan_dissect_run(edt, pseudo_header, buf, fdata, &cf->cinfo);
967   tap_push_tapped_queue(edt);
968
969   /* If we have a display filter, apply it if we're refiltering, otherwise
970      leave the "passed_dfilter" flag alone.
971
972      If we don't have a display filter, set "passed_dfilter" to 1. */
973   if (dfcode != NULL) {
974     if (refilter) {
975       fdata->flags.passed_dfilter = dfilter_apply_edt(dfcode, edt) ? 1 : 0;
976     }
977   } else
978     fdata->flags.passed_dfilter = 1;
979
980   if( (fdata->flags.passed_dfilter)
981    || (edt->pi.fd->flags.ref_time) ){
982     /* This frame either passed the display filter list or is marked as
983        a time reference frame.  All time reference frames are displayed
984        even if they dont pass the display filter */
985     /* if this was a TIME REF frame we should reset the cul bytes field */
986     if(edt->pi.fd->flags.ref_time){
987       cum_bytes = fdata->pkt_len;
988       fdata->cum_bytes  = cum_bytes;
989     }
990
991     /* increase cum_bytes with this packets length */
992     cum_bytes += fdata->pkt_len;
993
994     epan_dissect_fill_in_columns(edt);
995
996     /* If we haven't yet seen the first frame, this is it.
997
998        XXX - we must do this before we add the row to the display,
999        as, if the display's GtkCList's selection mode is
1000        GTK_SELECTION_BROWSE, when the first entry is added to it,
1001        "cf_select_packet()" will be called, and it will fetch the row
1002        data for the 0th row, and will get a null pointer rather than
1003        "fdata", as "gtk_clist_append()" won't yet have returned and
1004        thus "gtk_clist_set_row_data()" won't yet have been called.
1005
1006        We thus need to leave behind bread crumbs so that
1007        "cf_select_packet()" can find this frame.  See the comment
1008        in "cf_select_packet()". */
1009     if (cf->first_displayed == NULL)
1010       cf->first_displayed = fdata;
1011
1012     /* This is the last frame we've seen so far. */
1013     cf->last_displayed = fdata;
1014
1015     fdata->col_expr.col_expr = cf->cinfo.col_expr.col_expr;
1016     fdata->col_expr.col_expr_val = cf->cinfo.col_expr.col_expr_val;
1017     
1018     row = packet_list_append(cf->cinfo.col_data, fdata);
1019
1020     /* colorize packet: first apply color filters
1021      * then if packet is marked, use preferences to overwrite color
1022      * we do both to make sure that when a packet gets un-marked, the
1023      * color will be correctly set (fixes bug 2038)
1024      */
1025       fdata->color_filter = color_filters_colorize_packet(row, edt);
1026       if (fdata->flags.marked) {
1027           packet_list_set_colors(row, &prefs.gui_marked_fg, &prefs.gui_marked_bg);
1028       }
1029
1030     /* Set the time of the previous displayed frame to the time of this
1031        frame. */
1032     prev_dis_ts = fdata->abs_ts;
1033
1034     cf->displayed_count++;
1035   } else {
1036     /* This frame didn't pass the display filter, so it's not being added
1037        to the clist, and thus has no row. */
1038     row = -1;
1039   }
1040   epan_dissect_free(edt);
1041   return row;
1042 }
1043
1044 /* read in a new packet */
1045 /* returns the row of the new packet in the packet list or -1 if not displayed */
1046 static int
1047 read_packet(capture_file *cf, dfilter_t *dfcode, gint64 offset)
1048 {
1049   const struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
1050   union wtap_pseudo_header *pseudo_header = wtap_pseudoheader(cf->wth);
1051   const guchar *buf = wtap_buf_ptr(cf->wth);
1052   frame_data   *fdata;
1053   int           passed;
1054   frame_data   *plist_end;
1055   epan_dissect_t *edt;
1056   int row = -1;
1057
1058   /* Allocate the next list entry, and add it to the list. */
1059   fdata = g_mem_chunk_alloc(cf->plist_chunk);
1060
1061   fdata->num = 0;
1062   fdata->next = NULL;
1063   fdata->prev = NULL;
1064   fdata->pfd  = NULL;
1065   fdata->pkt_len  = phdr->len;
1066   fdata->cap_len  = phdr->caplen;
1067   fdata->file_off = offset;
1068   fdata->lnk_t = phdr->pkt_encap;
1069   fdata->flags.encoding = CHAR_ASCII;
1070   fdata->flags.visited = 0;
1071   fdata->flags.marked = 0;
1072   fdata->flags.ref_time = 0;
1073   fdata->color_filter = NULL;
1074
1075   fdata->abs_ts.secs = phdr->ts.secs;
1076   fdata->abs_ts.nsecs = phdr->ts.nsecs;
1077
1078   if (cf->plist_end != NULL)
1079     nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &cf->plist_end->abs_ts);
1080   else
1081     nstime_set_zero(&fdata->del_cap_ts);
1082
1083   passed = TRUE;
1084   if (cf->rfcode) {
1085     edt = epan_dissect_new(TRUE, FALSE);
1086     epan_dissect_prime_dfilter(edt, cf->rfcode);
1087     epan_dissect_run(edt, pseudo_header, buf, fdata, NULL);
1088     passed = dfilter_apply_edt(cf->rfcode, edt);
1089     epan_dissect_free(edt);
1090   }
1091   if (passed) {
1092     plist_end = cf->plist_end;
1093     fdata->prev = plist_end;
1094     if (plist_end != NULL)
1095       plist_end->next = fdata;
1096     else
1097       cf->plist = fdata;
1098     cf->plist_end = fdata;
1099
1100     cf->count++;
1101     cf->f_datalen = offset + phdr->caplen;
1102     fdata->num = cf->count;
1103     row = add_packet_to_packet_list(fdata, cf, dfcode, pseudo_header, buf, TRUE);
1104   } else {
1105     /* XXX - if we didn't have read filters, or if we could avoid
1106        allocating the "frame_data" structure until we knew whether
1107        the frame passed the read filter, we could use a G_ALLOC_ONLY
1108        memory chunk...
1109
1110        ...but, at least in one test I did, where I just made the chunk
1111        a G_ALLOC_ONLY chunk and read in a huge capture file, it didn't
1112        seem to save a noticeable amount of time or space. */
1113     g_mem_chunk_free(cf->plist_chunk, fdata);
1114   }
1115
1116   return row;
1117 }
1118
1119 cf_status_t
1120 cf_merge_files(char **out_filenamep, int in_file_count,
1121                char *const *in_filenames, int file_type, gboolean do_append)
1122 {
1123   merge_in_file_t  *in_files;
1124   wtap             *wth;
1125   char             *out_filename;
1126   char              tmpname[128+1];
1127   int               out_fd;
1128   wtap_dumper      *pdh;
1129   int               open_err, read_err, write_err, close_err;
1130   gchar            *err_info;
1131   int               err_fileno;
1132   int               i;
1133   char              errmsg_errno[1024+1];
1134   gchar             err_str[2048+1];
1135   const char       *errmsg;
1136   gboolean          got_read_error = FALSE, got_write_error = FALSE;
1137   gint64            data_offset;
1138   progdlg_t        *progbar = NULL;
1139   gboolean          stop_flag;
1140   gint64            f_len, file_pos;
1141   float             progbar_val;
1142   GTimeVal          start_time;
1143   gchar             status_str[100];
1144   gint64            progbar_nextstep;
1145   gint64            progbar_quantum;
1146
1147   /* open the input files */
1148   if (!merge_open_in_files(in_file_count, in_filenames, &in_files,
1149                            &open_err, &err_info, &err_fileno)) {
1150     g_free(in_files);
1151     cf_open_failure_alert_box(in_filenames[err_fileno], open_err, err_info,
1152                               FALSE, 0);
1153     return CF_ERROR;
1154   }
1155
1156   if (*out_filenamep != NULL) {
1157     out_filename = *out_filenamep;
1158     out_fd = eth_open(out_filename, O_CREAT|O_TRUNC|O_BINARY, 0600);
1159     if (out_fd == -1)
1160       open_err = errno;
1161   } else {
1162     out_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1163     if (out_fd == -1)
1164       open_err = errno;
1165     out_filename = g_strdup(tmpname);
1166     *out_filenamep = out_filename;
1167   }
1168   if (out_fd == -1) {
1169     err_info = NULL;
1170     merge_close_in_files(in_file_count, in_files);
1171     g_free(in_files);
1172     cf_open_failure_alert_box(out_filename, open_err, NULL, TRUE, file_type);
1173     return CF_ERROR;
1174   }
1175
1176   pdh = wtap_dump_fdopen(out_fd, file_type,
1177       merge_select_frame_type(in_file_count, in_files),
1178       merge_max_snapshot_length(in_file_count, in_files),
1179           FALSE /* compressed */, &open_err);
1180   if (pdh == NULL) {
1181     eth_close(out_fd);
1182     merge_close_in_files(in_file_count, in_files);
1183     g_free(in_files);
1184     cf_open_failure_alert_box(out_filename, open_err, err_info, TRUE,
1185                               file_type);
1186     return CF_ERROR;
1187   }
1188
1189   /* Get the sum of the sizes of all the files. */
1190   f_len = 0;
1191   for (i = 0; i < in_file_count; i++)
1192     f_len += in_files[i].size;
1193
1194   /* Update the progress bar when it gets to this value. */
1195   progbar_nextstep = 0;
1196   /* When we reach the value that triggers a progress bar update,
1197      bump that value by this amount. */
1198   progbar_quantum = f_len/N_PROGBAR_UPDATES;
1199   /* Progress so far. */
1200   progbar_val = 0.0;
1201
1202   stop_flag = FALSE;
1203   g_get_current_time(&start_time);
1204
1205   /* do the merge (or append) */
1206   for (;;) {
1207     if (do_append)
1208       wth = merge_append_read_packet(in_file_count, in_files, &read_err,
1209                                      &err_info);
1210     else
1211       wth = merge_read_packet(in_file_count, in_files, &read_err,
1212                               &err_info);
1213     if (wth == NULL) {
1214       if (read_err != 0)
1215         got_read_error = TRUE;
1216       break;
1217     }
1218
1219     /* Get the sum of the data offsets in all of the files. */
1220     data_offset = 0;
1221     for (i = 0; i < in_file_count; i++)
1222       data_offset += in_files[i].data_offset;
1223
1224     /* Create the progress bar if necessary.
1225        We check on every iteration of the loop, so that it takes no
1226        longer than the standard time to create it (otherwise, for a
1227        large file, we might take considerably longer than that standard
1228        time in order to get to the next progress bar step). */
1229     if (progbar == NULL) {
1230       progbar = delayed_create_progress_dlg("Merging", "files",
1231         FALSE, &stop_flag, &start_time, progbar_val);
1232     }
1233
1234     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1235        when we update it, we have to run the GTK+ main loop to get it
1236        to repaint what's pending, and doing so may involve an "ioctl()"
1237        to see if there's any pending input from an X server, and doing
1238        that for every packet can be costly, especially on a big file. */
1239     if (data_offset >= progbar_nextstep) {
1240         /* Get the sum of the seek positions in all of the files. */
1241         file_pos = 0;
1242         for (i = 0; i < in_file_count; i++)
1243           file_pos += wtap_read_so_far(in_files[i].wth, NULL);
1244         progbar_val = (gfloat) file_pos / (gfloat) f_len;
1245         if (progbar_val > 1.0) {
1246           /* Some file probably grew while we were reading it.
1247              That "shouldn't happen", so we'll just clip the progress
1248              value at 1.0. */
1249           progbar_val = 1.0;
1250         }
1251         if (progbar != NULL) {
1252           g_snprintf(status_str, sizeof(status_str),
1253                      "%" G_GINT64_MODIFIER "dKB of %" G_GINT64_MODIFIER "dKB",
1254                      file_pos / 1024, f_len / 1024);
1255           update_progress_dlg(progbar, progbar_val, status_str);
1256         }
1257         progbar_nextstep += progbar_quantum;
1258     }
1259
1260     if (stop_flag) {
1261       /* Well, the user decided to abort the merge. */
1262       break;
1263     }
1264
1265     if (!wtap_dump(pdh, wtap_phdr(wth), wtap_pseudoheader(wth),
1266          wtap_buf_ptr(wth), &write_err)) {
1267       got_write_error = TRUE;
1268       break;
1269     }
1270   }
1271
1272   /* We're done merging the files; destroy the progress bar if it was created. */
1273   if (progbar != NULL)
1274     destroy_progress_dlg(progbar);
1275
1276   merge_close_in_files(in_file_count, in_files);
1277   if (!got_read_error && !got_write_error) {
1278     if (!wtap_dump_close(pdh, &write_err))
1279       got_write_error = TRUE;
1280   } else
1281     wtap_dump_close(pdh, &close_err);
1282
1283   if (got_read_error) {
1284     /*
1285      * Find the file on which we got the error, and report the error.
1286      */
1287     for (i = 0; i < in_file_count; i++) {
1288       if (in_files[i].state == GOT_ERROR) {
1289         /* Put up a message box noting that a read failed somewhere along
1290            the line. */
1291         switch (read_err) {
1292
1293         case WTAP_ERR_UNSUPPORTED_ENCAP:
1294           g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1295                    "The capture file %%s has a packet with a network type that Wireshark doesn't support.\n(%s)",
1296                    err_info);
1297           g_free(err_info);
1298           errmsg = errmsg_errno;
1299           break;
1300
1301         case WTAP_ERR_CANT_READ:
1302           errmsg = "An attempt to read from the capture file %s failed for"
1303                    " some unknown reason.";
1304           break;
1305
1306         case WTAP_ERR_SHORT_READ:
1307           errmsg = "The capture file %s appears to have been cut short"
1308                    " in the middle of a packet.";
1309           break;
1310
1311         case WTAP_ERR_BAD_RECORD:
1312           g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1313                    "The capture file %%s appears to be damaged or corrupt.\n(%s)",
1314                    err_info);
1315           g_free(err_info);
1316           errmsg = errmsg_errno;
1317           break;
1318
1319         default:
1320           g_snprintf(errmsg_errno, sizeof(errmsg_errno),
1321                    "An error occurred while reading the"
1322                    " capture file %%s: %s.", wtap_strerror(read_err));
1323           errmsg = errmsg_errno;
1324           break;
1325         }
1326         g_snprintf(err_str, sizeof err_str, errmsg, in_files[i].filename);
1327         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, err_str);
1328       }
1329     }
1330   }
1331
1332   if (got_write_error) {
1333     /* Put up an alert box for the write error. */
1334     cf_write_failure_alert_box(out_filename, write_err);
1335   }
1336
1337   if (got_read_error || got_write_error || stop_flag) {
1338     /* Callers aren't expected to treat an error or an explicit abort
1339        differently - we put up error dialogs ourselves, so they don't
1340        have to. */
1341     return CF_ERROR;
1342   } else
1343     return CF_READ_OK;
1344 }
1345
1346 cf_status_t
1347 cf_filter_packets(capture_file *cf, gchar *dftext, gboolean force)
1348 {
1349   const char *filter_new = dftext ? dftext : "";
1350   const char *filter_old = cf->dfilter ? cf->dfilter : "";
1351   dfilter_t   *dfcode;
1352
1353   /* if new filter equals old one, do nothing unless told to do so */
1354   if (!force && strcmp(filter_new, filter_old) == 0) {
1355     return CF_OK;
1356   }
1357
1358   dfcode=NULL;
1359
1360   if (dftext == NULL) {
1361     /* The new filter is an empty filter (i.e., display all packets).
1362      * so leave dfcode==NULL
1363      */
1364   } else {
1365     /*
1366      * We have a filter; make a copy of it (as we'll be saving it),
1367      * and try to compile it.
1368      */
1369     dftext = g_strdup(dftext);
1370     if (!dfilter_compile(dftext, &dfcode)) {
1371       /* The attempt failed; report an error. */
1372       gchar *safe_dftext = simple_dialog_format_message(dftext);
1373       gchar *safe_dfilter_error_msg = simple_dialog_format_message(
1374           dfilter_error_msg);
1375       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
1376           "%s%s%s\n"
1377           "\n"
1378           "The following display filter isn't a valid display filter:\n%s\n"
1379           "See the help for a description of the display filter syntax.",
1380           simple_dialog_primary_start(), safe_dfilter_error_msg,
1381           simple_dialog_primary_end(), safe_dftext);
1382       g_free(safe_dfilter_error_msg);
1383       g_free(safe_dftext);
1384       g_free(dftext);
1385       return CF_ERROR;
1386     }
1387
1388     /* Was it empty? */
1389     if (dfcode == NULL) {
1390       /* Yes - free the filter text, and set it to null. */
1391       g_free(dftext);
1392       dftext = NULL;
1393     }
1394   }
1395
1396   /* We have a valid filter.  Replace the current filter. */
1397   if (cf->dfilter != NULL)
1398     g_free(cf->dfilter);
1399   cf->dfilter = dftext;
1400
1401   /* Now rescan the packet list, applying the new filter, but not
1402      throwing away information constructed on a previous pass. */
1403   if (dftext == NULL) {
1404     rescan_packets(cf, "Resetting", "Filter", TRUE, FALSE);
1405   } else {
1406     rescan_packets(cf, "Filtering", dftext, TRUE, FALSE);
1407   }
1408
1409   /* Cleanup and release all dfilter resources */
1410   if (dfcode != NULL){
1411     dfilter_free(dfcode);
1412   }
1413   return CF_OK;
1414 }
1415
1416 void
1417 cf_colorize_packets(capture_file *cf)
1418 {
1419   rescan_packets(cf, "Colorizing", "all packets", FALSE, FALSE);
1420 }
1421
1422 void
1423 cf_reftime_packets(capture_file *cf)
1424 {
1425   rescan_packets(cf, "Updating Reftime", "all packets", FALSE, FALSE);
1426 }
1427
1428 void
1429 cf_redissect_packets(capture_file *cf)
1430 {
1431   rescan_packets(cf, "Reprocessing", "all packets", TRUE, TRUE);
1432 }
1433
1434 /* Rescan the list of packets, reconstructing the CList.
1435
1436    "action" describes why we're doing this; it's used in the progress
1437    dialog box.
1438
1439    "action_item" describes what we're doing; it's used in the progress
1440    dialog box.
1441
1442    "refilter" is TRUE if we need to re-evaluate the filter expression.
1443
1444    "redissect" is TRUE if we need to make the dissectors reconstruct
1445    any state information they have (because a preference that affects
1446    some dissector has changed, meaning some dissector might construct
1447    its state differently from the way it was constructed the last time). */
1448 static void
1449 rescan_packets(capture_file *cf, const char *action, const char *action_item,
1450                 gboolean refilter, gboolean redissect)
1451 {
1452   frame_data *fdata;
1453   progdlg_t  *progbar = NULL;
1454   gboolean    stop_flag;
1455   int         count;
1456   int         err;
1457   gchar      *err_info;
1458   frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1459   int         selected_row, prev_row, preceding_row, following_row;
1460   gboolean    selected_frame_seen;
1461   int         row;
1462   float       progbar_val;
1463   GTimeVal    start_time;
1464   gchar       status_str[100];
1465   int         progbar_nextstep;
1466   int         progbar_quantum;
1467   dfilter_t   *dfcode;
1468
1469   /* Compile the current display filter.
1470    * We assume this will not fail since cf->dfilter is only set in
1471    * cf_filter IFF the filter was valid.
1472    */
1473   dfcode=NULL;
1474   if(cf->dfilter){
1475     dfilter_compile(cf->dfilter, &dfcode);
1476   }
1477
1478   cum_bytes=0;
1479   reset_tap_listeners();
1480   /* Which frame, if any, is the currently selected frame?
1481      XXX - should the selected frame or the focus frame be the "current"
1482      frame, that frame being the one from which "Find Frame" searches
1483      start? */
1484   selected_frame = cf->current_frame;
1485
1486   /* We don't yet know what row that frame will be on, if any, after we
1487      rebuild the clist, however. */
1488   selected_row = -1;
1489
1490   if (redissect) {
1491     /* We need to re-initialize all the state information that protocols
1492        keep, because some preference that controls a dissector has changed,
1493        which might cause the state information to be constructed differently
1494        by that dissector. */
1495
1496     /* Initialize all data structures used for dissection. */
1497     init_dissection();
1498   }
1499
1500   /* Freeze the packet list while we redo it, so we don't get any
1501      screen updates while it happens. */
1502   packet_list_freeze();
1503
1504   /* Clear it out. */
1505   packet_list_clear();
1506
1507   /* We don't yet know which will be the first and last frames displayed. */
1508   cf->first_displayed = NULL;
1509   cf->last_displayed = NULL;
1510
1511   /* We currently don't display any packets */
1512   cf->displayed_count = 0;
1513
1514   /* Iterate through the list of frames.  Call a routine for each frame
1515      to check whether it should be displayed and, if so, add it to
1516      the display list. */
1517   nstime_set_unset(&first_ts);
1518   nstime_set_unset(&prev_dis_ts);
1519
1520   /* Update the progress bar when it gets to this value. */
1521   progbar_nextstep = 0;
1522   /* When we reach the value that triggers a progress bar update,
1523      bump that value by this amount. */
1524   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1525   /* Count of packets at which we've looked. */
1526   count = 0;
1527   /* Progress so far. */
1528   progbar_val = 0.0;
1529
1530   stop_flag = FALSE;
1531   g_get_current_time(&start_time);
1532
1533   row = -1;             /* no previous row yet */
1534   prev_row = -1;
1535   prev_frame = NULL;
1536
1537   preceding_row = -1;
1538   preceding_frame = NULL;
1539   following_row = -1;
1540   following_frame = NULL;
1541
1542   selected_frame_seen = FALSE;
1543
1544   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1545     /* Create the progress bar if necessary.
1546        We check on every iteration of the loop, so that it takes no
1547        longer than the standard time to create it (otherwise, for a
1548        large file, we might take considerably longer than that standard
1549        time in order to get to the next progress bar step). */
1550     if (progbar == NULL)
1551       progbar = delayed_create_progress_dlg(action, action_item, TRUE,
1552                                             &stop_flag, &start_time,
1553                                             progbar_val);
1554
1555     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1556        when we update it, we have to run the GTK+ main loop to get it
1557        to repaint what's pending, and doing so may involve an "ioctl()"
1558        to see if there's any pending input from an X server, and doing
1559        that for every packet can be costly, especially on a big file. */
1560     if (count >= progbar_nextstep) {
1561       /* let's not divide by zero. I should never be started
1562        * with count == 0, so let's assert that
1563        */
1564       g_assert(cf->count > 0);
1565       progbar_val = (gfloat) count / cf->count;
1566
1567       if (progbar != NULL) {
1568         g_snprintf(status_str, sizeof(status_str),
1569                   "%4u of %u frames", count, cf->count);
1570         update_progress_dlg(progbar, progbar_val, status_str);
1571       }
1572
1573       progbar_nextstep += progbar_quantum;
1574     }
1575
1576     if (stop_flag) {
1577       /* Well, the user decided to abort the filtering.  Just stop.
1578
1579          XXX - go back to the previous filter?  Users probably just
1580          want not to wait for a filtering operation to finish;
1581          unless we cancel by having no filter, reverting to the
1582          previous filter will probably be even more expensive than
1583          continuing the filtering, as it involves going back to the
1584          beginning and filtering, and even with no filter we currently
1585          have to re-generate the entire clist, which is also expensive.
1586
1587          I'm not sure what Network Monitor does, but it doesn't appear
1588          to give you an unfiltered display if you cancel. */
1589       break;
1590     }
1591
1592     count++;
1593
1594     if (redissect) {
1595       /* Since all state for the frame was destroyed, mark the frame
1596        * as not visited, free the GSList referring to the state
1597        * data (the per-frame data itself was freed by
1598        * "init_dissection()"), and null out the GSList pointer. */
1599       fdata->flags.visited = 0;
1600       if (fdata->pfd) {
1601         g_slist_free(fdata->pfd);
1602         fdata->pfd = NULL;
1603       }
1604     }
1605
1606     if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1607         cf->pd, fdata->cap_len, &err, &err_info)) {
1608         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
1609                       cf_read_error_message(err, err_info), cf->filename);
1610         break;
1611     }
1612
1613     /* If the previous frame is displayed, and we haven't yet seen the
1614        selected frame, remember that frame - it's the closest one we've
1615        yet seen before the selected frame. */
1616     if (prev_row != -1 && !selected_frame_seen) {
1617       preceding_row = prev_row;
1618       preceding_frame = prev_frame;
1619     }
1620     row = add_packet_to_packet_list(fdata, cf, dfcode, &cf->pseudo_header, cf->pd,
1621                                         refilter);
1622
1623     /* If this frame is displayed, and this is the first frame we've
1624        seen displayed after the selected frame, remember this frame -
1625        it's the closest one we've yet seen at or after the selected
1626        frame. */
1627     if (row != -1 && selected_frame_seen && following_row == -1) {
1628       following_row = row;
1629       following_frame = fdata;
1630     }
1631     if (fdata == selected_frame) {
1632       selected_row = row;
1633       selected_frame_seen = TRUE;
1634     }
1635
1636     /* Remember this row/frame - it'll be the previous row/frame
1637        on the next pass through the loop. */
1638     prev_row = row;
1639     prev_frame = fdata;
1640   }
1641
1642   /* Re-sort the list using the previously selected order */
1643   packet_list_set_sort_column();
1644
1645   if (redissect) {
1646     /* Clear out what remains of the visited flags and per-frame data
1647        pointers.
1648
1649        XXX - that may cause various forms of bogosity when dissecting
1650        these frames, as they won't have been seen by this sequential
1651        pass, but the only alternative I see is to keep scanning them
1652        even though the user requested that the scan stop, and that
1653        would leave the user stuck with an Wireshark grinding on
1654        until it finishes.  Should we just stick them with that? */
1655     for (; fdata != NULL; fdata = fdata->next) {
1656       fdata->flags.visited = 0;
1657       if (fdata->pfd) {
1658         g_slist_free(fdata->pfd);
1659         fdata->pfd = NULL;
1660       }
1661     }
1662   }
1663
1664   /* We're done filtering the packets; destroy the progress bar if it
1665      was created. */
1666   if (progbar != NULL)
1667     destroy_progress_dlg(progbar);
1668
1669   /* Unfreeze the packet list. */
1670   packet_list_thaw();
1671
1672   if (selected_row == -1) {
1673     /* The selected frame didn't pass the filter. */
1674     if (selected_frame == NULL) {
1675       /* That's because there *was* no selected frame.  Make the first
1676          displayed frame the current frame. */
1677       selected_row = 0;
1678     } else {
1679       /* Find the nearest displayed frame to the selected frame (whether
1680          it's before or after that frame) and make that the current frame.
1681          If the next and previous displayed frames are equidistant from the
1682          selected frame, choose the next one. */
1683       g_assert(following_frame == NULL ||
1684                following_frame->num >= selected_frame->num);
1685       g_assert(preceding_frame == NULL ||
1686                preceding_frame->num <= selected_frame->num);
1687       if (following_frame == NULL) {
1688         /* No frame after the selected frame passed the filter, so we
1689            have to select the last displayed frame before the selected
1690            frame. */
1691         selected_row = preceding_row;
1692       } else if (preceding_frame == NULL) {
1693         /* No frame before the selected frame passed the filter, so we
1694            have to select the first displayed frame after the selected
1695            frame. */
1696         selected_row = following_row;
1697       } else {
1698         /* Frames before and after the selected frame passed the filter, so
1699            we'll select the previous frame */
1700         selected_row = preceding_row;
1701       }
1702     }
1703   }
1704
1705   if (selected_row == -1) {
1706     /* There are no frames displayed at all. */
1707     cf_unselect_packet(cf);
1708   } else {
1709     /* Either the frame that was selected passed the filter, or we've
1710        found the nearest displayed frame to that frame.  Select it, make
1711        it the focus row, and make it visible. */
1712     packet_list_set_selected_row(selected_row);
1713   }
1714
1715   /* Cleanup and release all dfilter resources */
1716   if (dfcode != NULL){
1717     dfilter_free(dfcode);
1718   }
1719 }
1720
1721 typedef enum {
1722   PSP_FINISHED,
1723   PSP_STOPPED,
1724   PSP_FAILED
1725 } psp_return_t;
1726
1727 static psp_return_t
1728 process_specified_packets(capture_file *cf, packet_range_t *range,
1729     const char *string1, const char *string2, gboolean terminate_is_stop,
1730     gboolean (*callback)(capture_file *, frame_data *,
1731                          union wtap_pseudo_header *, const guint8 *, void *),
1732     void *callback_args)
1733 {
1734   frame_data *fdata;
1735   int         err;
1736   gchar      *err_info;
1737   union wtap_pseudo_header pseudo_header;
1738   guint8      pd[WTAP_MAX_PACKET_SIZE+1];
1739   psp_return_t ret = PSP_FINISHED;
1740
1741   progdlg_t  *progbar = NULL;
1742   int         progbar_count;
1743   float       progbar_val;
1744   gboolean    progbar_stop_flag;
1745   GTimeVal    progbar_start_time;
1746   gchar       progbar_status_str[100];
1747   int         progbar_nextstep;
1748   int         progbar_quantum;
1749   range_process_e process_this;
1750
1751   /* Update the progress bar when it gets to this value. */
1752   progbar_nextstep = 0;
1753   /* When we reach the value that triggers a progress bar update,
1754      bump that value by this amount. */
1755   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1756   /* Count of packets at which we've looked. */
1757   progbar_count = 0;
1758   /* Progress so far. */
1759   progbar_val = 0.0;
1760
1761   progbar_stop_flag = FALSE;
1762   g_get_current_time(&progbar_start_time);
1763
1764   packet_range_process_init(range);
1765
1766   /* Iterate through the list of packets, printing the packets that
1767      were selected by the current display filter.  */
1768   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1769     /* Create the progress bar if necessary.
1770        We check on every iteration of the loop, so that it takes no
1771        longer than the standard time to create it (otherwise, for a
1772        large file, we might take considerably longer than that standard
1773        time in order to get to the next progress bar step). */
1774     if (progbar == NULL)
1775       progbar = delayed_create_progress_dlg(string1, string2,
1776                                             terminate_is_stop,
1777                                             &progbar_stop_flag,
1778                                             &progbar_start_time,
1779                                             progbar_val);
1780
1781     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1782        when we update it, we have to run the GTK+ main loop to get it
1783        to repaint what's pending, and doing so may involve an "ioctl()"
1784        to see if there's any pending input from an X server, and doing
1785        that for every packet can be costly, especially on a big file. */
1786     if (progbar_count >= progbar_nextstep) {
1787       /* let's not divide by zero. I should never be started
1788        * with count == 0, so let's assert that
1789        */
1790       g_assert(cf->count > 0);
1791       progbar_val = (gfloat) progbar_count / cf->count;
1792
1793       if (progbar != NULL) {
1794         g_snprintf(progbar_status_str, sizeof(progbar_status_str),
1795                    "%4u of %u packets", progbar_count, cf->count);
1796         update_progress_dlg(progbar, progbar_val, progbar_status_str);
1797       }
1798
1799       progbar_nextstep += progbar_quantum;
1800     }
1801
1802     if (progbar_stop_flag) {
1803       /* Well, the user decided to abort the operation.  Just stop,
1804          and arrange to return PSP_STOPPED to our caller, so they know
1805          it was stopped explicitly. */
1806       ret = PSP_STOPPED;
1807       break;
1808     }
1809
1810     progbar_count++;
1811
1812     /* do we have to process this packet? */
1813     process_this = packet_range_process_packet(range, fdata);
1814     if (process_this == range_process_next) {
1815         /* this packet uninteresting, continue with next one */
1816         continue;
1817     } else if (process_this == range_processing_finished) {
1818         /* all interesting packets processed, stop the loop */
1819         break;
1820     }
1821
1822     /* Get the packet */
1823     if (!wtap_seek_read(cf->wth, fdata->file_off, &pseudo_header,
1824                         pd, fdata->cap_len, &err, &err_info)) {
1825       /* Attempt to get the packet failed. */
1826       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
1827                     cf_read_error_message(err, err_info), cf->filename);
1828       ret = PSP_FAILED;
1829       break;
1830     }
1831     /* Process the packet */
1832     if (!callback(cf, fdata, &pseudo_header, pd, callback_args)) {
1833       /* Callback failed.  We assume it reported the error appropriately. */
1834       ret = PSP_FAILED;
1835       break;
1836     }
1837   }
1838
1839   /* We're done printing the packets; destroy the progress bar if
1840      it was created. */
1841   if (progbar != NULL)
1842     destroy_progress_dlg(progbar);
1843
1844   return ret;
1845 }
1846
1847 static gboolean
1848 retap_packet(capture_file *cf _U_, frame_data *fdata,
1849              union wtap_pseudo_header *pseudo_header, const guint8 *pd,
1850              void *argsp)
1851 {
1852   column_info *cinfo = argsp;
1853   epan_dissect_t *edt;
1854
1855   /* If we have tap listeners, allocate a protocol tree root node, so that
1856      we'll construct a protocol tree against which a filter expression can
1857      be evaluated. */
1858   edt = epan_dissect_new(num_tap_filters != 0, FALSE);
1859   tap_queue_init(edt);
1860   epan_dissect_run(edt, pseudo_header, pd, fdata, cinfo);
1861   tap_push_tapped_queue(edt);
1862   epan_dissect_free(edt);
1863
1864   return TRUE;
1865 }
1866
1867 cf_read_status_t
1868 cf_retap_packets(capture_file *cf, gboolean do_columns)
1869 {
1870   packet_range_t range;
1871
1872   /* Reset the tap listeners. */
1873   reset_tap_listeners();
1874
1875   /* Iterate through the list of packets, dissecting all packets and
1876      re-running the taps. */
1877   packet_range_init(&range);
1878   packet_range_process_init(&range);
1879   switch (process_specified_packets(cf, &range, "Refiltering statistics on",
1880                                     "all packets", TRUE, retap_packet,
1881                                     do_columns ? &cf->cinfo : NULL)) {
1882   case PSP_FINISHED:
1883     /* Completed successfully. */
1884     return CF_OK;
1885
1886   case PSP_STOPPED:
1887     /* Well, the user decided to abort the refiltering.
1888        Return CF_READ_ABORTED so our caller knows they did that. */
1889     return CF_READ_ABORTED;
1890
1891   case PSP_FAILED:
1892     /* Error while retapping. */
1893     return CF_READ_ERROR;
1894   }
1895
1896   g_assert_not_reached();
1897   return CF_READ_OK;
1898 }
1899
1900 typedef struct {
1901   print_args_t *print_args;
1902   gboolean      print_header_line;
1903   char         *header_line_buf;
1904   int           header_line_buf_len;
1905   gboolean      print_formfeed;
1906   gboolean      print_separator;
1907   char         *line_buf;
1908   int           line_buf_len;
1909   gint         *col_widths;
1910 } print_callback_args_t;
1911
1912 static gboolean
1913 print_packet(capture_file *cf, frame_data *fdata,
1914              union wtap_pseudo_header *pseudo_header, const guint8 *pd,
1915              void *argsp)
1916 {
1917   print_callback_args_t *args = argsp;
1918   epan_dissect_t *edt;
1919   int             i;
1920   char           *cp;
1921   int             line_len;
1922   int             column_len;
1923   int             cp_off;
1924   gboolean        proto_tree_needed;
1925   char            bookmark_name[9+10+1];        /* "__frameNNNNNNNNNN__\0" */
1926   char            bookmark_title[6+10+1];       /* "Frame NNNNNNNNNN__\0" */
1927
1928   /* Create the protocol tree, and make it visible, if we're printing
1929      the dissection or the hex data.
1930      XXX - do we need it if we're just printing the hex data? */
1931   proto_tree_needed =
1932       args->print_args->print_dissections != print_dissections_none || args->print_args->print_hex;
1933   edt = epan_dissect_new(proto_tree_needed, proto_tree_needed);
1934
1935   /* Fill in the column information if we're printing the summary
1936      information. */
1937   if (args->print_args->print_summary) {
1938     epan_dissect_run(edt, pseudo_header, pd, fdata, &cf->cinfo);
1939     epan_dissect_fill_in_columns(edt);
1940   } else
1941     epan_dissect_run(edt, pseudo_header, pd, fdata, NULL);
1942
1943   if (args->print_formfeed) {
1944     if (!new_page(args->print_args->stream))
1945       goto fail;
1946   } else {
1947       if (args->print_separator) {
1948         if (!print_line(args->print_args->stream, 0, ""))
1949           goto fail;
1950       }
1951   }
1952
1953   /*
1954    * We generate bookmarks, if the output format supports them.
1955    * The name is "__frameN__".
1956    */
1957   g_snprintf(bookmark_name, sizeof bookmark_name, "__frame%u__", fdata->num);
1958
1959   if (args->print_args->print_summary) {
1960     if (args->print_header_line) {
1961       if (!print_line(args->print_args->stream, 0, args->header_line_buf))
1962         goto fail;
1963       args->print_header_line = FALSE;  /* we might not need to print any more */
1964     }
1965     cp = &args->line_buf[0];
1966     line_len = 0;
1967     for (i = 0; i < cf->cinfo.num_cols; i++) {
1968       /* Find the length of the string for this column. */
1969       column_len = strlen(cf->cinfo.col_data[i]);
1970       if (args->col_widths[i] > column_len)
1971          column_len = args->col_widths[i];
1972
1973       /* Make sure there's room in the line buffer for the column; if not,
1974          double its length. */
1975       line_len += column_len + 1;       /* "+1" for space */
1976       if (line_len > args->line_buf_len) {
1977         cp_off = cp - args->line_buf;
1978         args->line_buf_len = 2 * line_len;
1979         args->line_buf = g_realloc(args->line_buf, args->line_buf_len + 1);
1980         cp = args->line_buf + cp_off;
1981       }
1982
1983       /* Right-justify the packet number column. */
1984       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1985         sprintf(cp, "%*s", args->col_widths[i], cf->cinfo.col_data[i]);
1986       else
1987         sprintf(cp, "%-*s", args->col_widths[i], cf->cinfo.col_data[i]);
1988       cp += column_len;
1989       if (i != cf->cinfo.num_cols - 1)
1990         *cp++ = ' ';
1991     }
1992     *cp = '\0';
1993
1994     /*
1995      * Generate a bookmark, using the summary line as the title.
1996      */
1997     if (!print_bookmark(args->print_args->stream, bookmark_name,
1998                         args->line_buf))
1999       goto fail;
2000
2001     if (!print_line(args->print_args->stream, 0, args->line_buf))
2002       goto fail;
2003   } else {
2004     /*
2005      * Generate a bookmark, using "Frame N" as the title, as we're not
2006      * printing the summary line.
2007      */
2008     g_snprintf(bookmark_title, sizeof bookmark_title, "Frame %u", fdata->num);
2009     if (!print_bookmark(args->print_args->stream, bookmark_name,
2010                         bookmark_title))
2011       goto fail;
2012   } /* if (print_summary) */
2013
2014   if (args->print_args->print_dissections != print_dissections_none) {
2015     if (args->print_args->print_summary) {
2016       /* Separate the summary line from the tree with a blank line. */
2017       if (!print_line(args->print_args->stream, 0, ""))
2018         goto fail;
2019     }
2020
2021     /* Print the information in that tree. */
2022     if (!proto_tree_print(args->print_args, edt, args->print_args->stream))
2023       goto fail;
2024
2025     /* Print a blank line if we print anything after this (aka more than one packet). */
2026     args->print_separator = TRUE;
2027
2028     /* Print a header line if we print any more packet summaries */
2029     args->print_header_line = TRUE;
2030   }
2031
2032   if (args->print_args->print_hex) {
2033     /* Print the full packet data as hex. */
2034     if (!print_hex_data(args->print_args->stream, edt))
2035       goto fail;
2036
2037     /* Print a blank line if we print anything after this (aka more than one packet). */
2038     args->print_separator = TRUE;
2039
2040     /* Print a header line if we print any more packet summaries */
2041     args->print_header_line = TRUE;
2042   } /* if (args->print_args->print_dissections != print_dissections_none) */
2043
2044   epan_dissect_free(edt);
2045
2046   /* do we want to have a formfeed between each packet from now on? */
2047   if(args->print_args->print_formfeed) {
2048     args->print_formfeed = TRUE;
2049   }
2050
2051   return TRUE;
2052
2053 fail:
2054   epan_dissect_free(edt);
2055   return FALSE;
2056 }
2057
2058 cf_print_status_t
2059 cf_print_packets(capture_file *cf, print_args_t *print_args)
2060 {
2061   int         i;
2062   print_callback_args_t callback_args;
2063   gint        data_width;
2064   char        *cp;
2065   int         cp_off;
2066   int         column_len;
2067   int         line_len;
2068   psp_return_t ret;
2069
2070   callback_args.print_args = print_args;
2071   callback_args.print_header_line = TRUE;
2072   callback_args.header_line_buf = NULL;
2073   callback_args.header_line_buf_len = 256;
2074   callback_args.print_formfeed = FALSE;
2075   callback_args.print_separator = FALSE;
2076   callback_args.line_buf = NULL;
2077   callback_args.line_buf_len = 256;
2078   callback_args.col_widths = NULL;
2079
2080   if (!print_preamble(print_args->stream, cf->filename)) {
2081     destroy_print_stream(print_args->stream);
2082     return CF_PRINT_WRITE_ERROR;
2083   }
2084
2085   if (print_args->print_summary) {
2086     /* We're printing packet summaries.  Allocate the header line buffer
2087        and get the column widths. */
2088     callback_args.header_line_buf = g_malloc(callback_args.header_line_buf_len + 1);
2089
2090     /* Find the widths for each of the columns - maximum of the
2091        width of the title and the width of the data - and construct
2092        a buffer with a line containing the column titles. */
2093     callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * cf->cinfo.num_cols);
2094     cp = &callback_args.header_line_buf[0];
2095     line_len = 0;
2096     for (i = 0; i < cf->cinfo.num_cols; i++) {
2097       /* Don't pad the last column. */
2098       if (i == cf->cinfo.num_cols - 1)
2099         callback_args.col_widths[i] = 0;
2100       else {
2101         callback_args.col_widths[i] = strlen(cf->cinfo.col_title[i]);
2102         data_width = get_column_char_width(get_column_format(i));
2103         if (data_width > callback_args.col_widths[i])
2104           callback_args.col_widths[i] = data_width;
2105       }
2106
2107       /* Find the length of the string for this column. */
2108       column_len = strlen(cf->cinfo.col_title[i]);
2109       if (callback_args.col_widths[i] > column_len)
2110         column_len = callback_args.col_widths[i];
2111
2112       /* Make sure there's room in the line buffer for the column; if not,
2113          double its length. */
2114       line_len += column_len + 1;       /* "+1" for space */
2115       if (line_len > callback_args.header_line_buf_len) {
2116         cp_off = cp - callback_args.header_line_buf;
2117         callback_args.header_line_buf_len = 2 * line_len;
2118         callback_args.header_line_buf = g_realloc(callback_args.header_line_buf,
2119                                                   callback_args.header_line_buf_len + 1);
2120         cp = callback_args.header_line_buf + cp_off;
2121       }
2122
2123       /* Right-justify the packet number column. */
2124 /*      if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2125         sprintf(cp, "%*s", callback_args.col_widths[i], cf->cinfo.col_title[i]);
2126       else*/
2127         sprintf(cp, "%-*s", callback_args.col_widths[i], cf->cinfo.col_title[i]);
2128       cp += column_len;
2129       if (i != cf->cinfo.num_cols - 1)
2130         *cp++ = ' ';
2131     }
2132     *cp = '\0';
2133
2134     /* Now start out the main line buffer with the same length as the
2135        header line buffer. */
2136     callback_args.line_buf_len = callback_args.header_line_buf_len;
2137     callback_args.line_buf = g_malloc(callback_args.line_buf_len + 1);
2138   } /* if (print_summary) */
2139
2140   /* Iterate through the list of packets, printing the packets we were
2141      told to print. */
2142   ret = process_specified_packets(cf, &print_args->range, "Printing",
2143                                   "selected packets", TRUE, print_packet,
2144                                   &callback_args);
2145
2146   if (callback_args.header_line_buf != NULL)
2147     g_free(callback_args.header_line_buf);
2148   if (callback_args.line_buf != NULL)
2149     g_free(callback_args.line_buf);
2150   if (callback_args.col_widths != NULL)
2151     g_free(callback_args.col_widths);
2152
2153   switch (ret) {
2154
2155   case PSP_FINISHED:
2156     /* Completed successfully. */
2157     break;
2158
2159   case PSP_STOPPED:
2160     /* Well, the user decided to abort the printing.
2161
2162        XXX - note that what got generated before they did that
2163        will get printed if we're piping to a print program; we'd
2164        have to write to a file and then hand that to the print
2165        program to make it actually not print anything. */
2166     break;
2167
2168   case PSP_FAILED:
2169     /* Error while printing.
2170
2171        XXX - note that what got generated before they did that
2172        will get printed if we're piping to a print program; we'd
2173        have to write to a file and then hand that to the print
2174        program to make it actually not print anything. */
2175     destroy_print_stream(print_args->stream);
2176     return CF_PRINT_WRITE_ERROR;
2177   }
2178
2179   if (!print_finale(print_args->stream)) {
2180     destroy_print_stream(print_args->stream);
2181     return CF_PRINT_WRITE_ERROR;
2182   }
2183
2184   if (!destroy_print_stream(print_args->stream))
2185     return CF_PRINT_WRITE_ERROR;
2186
2187   return CF_PRINT_OK;
2188 }
2189
2190 static gboolean
2191 write_pdml_packet(capture_file *cf _U_, frame_data *fdata,
2192                   union wtap_pseudo_header *pseudo_header, const guint8 *pd,
2193                   void *argsp)
2194 {
2195   FILE *fh = argsp;
2196   epan_dissect_t *edt;
2197
2198   /* Create the protocol tree, but don't fill in the column information. */
2199   edt = epan_dissect_new(TRUE, TRUE);
2200   epan_dissect_run(edt, pseudo_header, pd, fdata, NULL);
2201
2202   /* Write out the information in that tree. */
2203   proto_tree_write_pdml(edt, fh);
2204
2205   epan_dissect_free(edt);
2206
2207   return !ferror(fh);
2208 }
2209
2210 cf_print_status_t
2211 cf_write_pdml_packets(capture_file *cf, print_args_t *print_args)
2212 {
2213   FILE        *fh;
2214   psp_return_t ret;
2215
2216   fh = eth_fopen(print_args->file, "w");
2217   if (fh == NULL)
2218     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2219
2220   write_pdml_preamble(fh);
2221   if (ferror(fh)) {
2222     fclose(fh);
2223     return CF_PRINT_WRITE_ERROR;
2224   }
2225
2226   /* Iterate through the list of packets, printing the packets we were
2227      told to print. */
2228   ret = process_specified_packets(cf, &print_args->range, "Writing PDML",
2229                                   "selected packets", TRUE,
2230                                   write_pdml_packet, fh);
2231
2232   switch (ret) {
2233
2234   case PSP_FINISHED:
2235     /* Completed successfully. */
2236     break;
2237
2238   case PSP_STOPPED:
2239     /* Well, the user decided to abort the printing. */
2240     break;
2241
2242   case PSP_FAILED:
2243     /* Error while printing. */
2244     fclose(fh);
2245     return CF_PRINT_WRITE_ERROR;
2246   }
2247
2248   write_pdml_finale(fh);
2249   if (ferror(fh)) {
2250     fclose(fh);
2251     return CF_PRINT_WRITE_ERROR;
2252   }
2253
2254   /* XXX - check for an error */
2255   fclose(fh);
2256
2257   return CF_PRINT_OK;
2258 }
2259
2260 static gboolean
2261 write_psml_packet(capture_file *cf, frame_data *fdata,
2262                   union wtap_pseudo_header *pseudo_header, const guint8 *pd,
2263                   void *argsp)
2264 {
2265   FILE *fh = argsp;
2266   epan_dissect_t *edt;
2267
2268   /* Fill in the column information, but don't create the protocol tree. */
2269   edt = epan_dissect_new(FALSE, FALSE);
2270   epan_dissect_run(edt, pseudo_header, pd, fdata, &cf->cinfo);
2271   epan_dissect_fill_in_columns(edt);
2272
2273   /* Write out the information in that tree. */
2274   proto_tree_write_psml(edt, fh);
2275
2276   epan_dissect_free(edt);
2277
2278   return !ferror(fh);
2279 }
2280
2281 cf_print_status_t
2282 cf_write_psml_packets(capture_file *cf, print_args_t *print_args)
2283 {
2284   FILE        *fh;
2285   psp_return_t ret;
2286
2287   fh = eth_fopen(print_args->file, "w");
2288   if (fh == NULL)
2289     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2290
2291   write_psml_preamble(fh);
2292   if (ferror(fh)) {
2293     fclose(fh);
2294     return CF_PRINT_WRITE_ERROR;
2295   }
2296
2297   /* Iterate through the list of packets, printing the packets we were
2298      told to print. */
2299   ret = process_specified_packets(cf, &print_args->range, "Writing PSML",
2300                                   "selected packets", TRUE,
2301                                   write_psml_packet, fh);
2302
2303   switch (ret) {
2304
2305   case PSP_FINISHED:
2306     /* Completed successfully. */
2307     break;
2308
2309   case PSP_STOPPED:
2310     /* Well, the user decided to abort the printing. */
2311     break;
2312
2313   case PSP_FAILED:
2314     /* Error while printing. */
2315     fclose(fh);
2316     return CF_PRINT_WRITE_ERROR;
2317   }
2318
2319   write_psml_finale(fh);
2320   if (ferror(fh)) {
2321     fclose(fh);
2322     return CF_PRINT_WRITE_ERROR;
2323   }
2324
2325   /* XXX - check for an error */
2326   fclose(fh);
2327
2328   return CF_PRINT_OK;
2329 }
2330
2331 static gboolean
2332 write_csv_packet(capture_file *cf, frame_data *fdata,
2333                  union wtap_pseudo_header *pseudo_header, const guint8 *pd,
2334                  void *argsp)
2335 {
2336   FILE *fh = argsp;
2337   epan_dissect_t *edt;
2338
2339   /* Fill in the column information, but don't create the protocol tree. */
2340   edt = epan_dissect_new(FALSE, FALSE);
2341   epan_dissect_run(edt, pseudo_header, pd, fdata, &cf->cinfo);
2342   epan_dissect_fill_in_columns(edt);
2343
2344   /* Write out the information in that tree. */
2345   proto_tree_write_csv(edt, fh);
2346
2347   epan_dissect_free(edt);
2348
2349   return !ferror(fh);
2350 }
2351
2352 cf_print_status_t
2353 cf_write_csv_packets(capture_file *cf, print_args_t *print_args)
2354 {
2355   FILE        *fh;
2356   psp_return_t ret;
2357
2358   fh = eth_fopen(print_args->file, "w");
2359   if (fh == NULL)
2360     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2361
2362   write_csv_preamble(fh);
2363   if (ferror(fh)) {
2364     fclose(fh);
2365     return CF_PRINT_WRITE_ERROR;
2366   }
2367
2368   /* Iterate through the list of packets, printing the packets we were
2369      told to print. */
2370   ret = process_specified_packets(cf, &print_args->range, "Writing CSV",
2371                                   "selected packets", TRUE,
2372                                   write_csv_packet, fh);
2373
2374   switch (ret) {
2375
2376   case PSP_FINISHED:
2377     /* Completed successfully. */
2378     break;
2379
2380   case PSP_STOPPED:
2381     /* Well, the user decided to abort the printing. */
2382     break;
2383
2384   case PSP_FAILED:
2385     /* Error while printing. */
2386     fclose(fh);
2387     return CF_PRINT_WRITE_ERROR;
2388   }
2389
2390   write_csv_finale(fh);
2391   if (ferror(fh)) {
2392     fclose(fh);
2393     return CF_PRINT_WRITE_ERROR;
2394   }
2395
2396   /* XXX - check for an error */
2397   fclose(fh);
2398
2399   return CF_PRINT_OK;
2400 }
2401
2402 static gboolean
2403 write_carrays_packet(capture_file *cf _U_, frame_data *fdata,
2404                      union wtap_pseudo_header *pseudo_header _U_, 
2405                      const guint8 *pd, void *argsp)
2406 {
2407   FILE *fh = argsp;
2408
2409   proto_tree_write_carrays(pd, fdata->cap_len, fdata->num, fh);
2410   return !ferror(fh);
2411 }
2412
2413 cf_print_status_t
2414 cf_write_carrays_packets(capture_file *cf, print_args_t *print_args)
2415 {
2416   FILE        *fh;
2417   psp_return_t ret;
2418
2419   fh = eth_fopen(print_args->file, "w");
2420
2421   if (fh == NULL)
2422     return CF_PRINT_OPEN_ERROR; /* attempt to open destination failed */
2423
2424   write_carrays_preamble(fh);
2425
2426   if (ferror(fh)) {
2427     fclose(fh);
2428     return CF_PRINT_WRITE_ERROR;
2429   }
2430
2431   /* Iterate through the list of packets, printing the packets we were
2432      told to print. */
2433   ret = process_specified_packets(cf, &print_args->range, 
2434                                   "Writing C Arrays",
2435                                   "selected packets", TRUE,
2436                                   write_carrays_packet, fh);
2437   switch (ret) {
2438   case PSP_FINISHED:
2439     /* Completed successfully. */
2440     break;
2441   case PSP_STOPPED:
2442     /* Well, the user decided to abort the printing. */
2443     break;
2444   case PSP_FAILED:
2445     /* Error while printing. */
2446     fclose(fh);
2447     return CF_PRINT_WRITE_ERROR;
2448   }
2449
2450   write_carrays_finale(fh);
2451
2452   if (ferror(fh)) {
2453     fclose(fh);
2454     return CF_PRINT_WRITE_ERROR;
2455   }
2456
2457   fclose(fh);
2458   return CF_PRINT_OK;
2459 }
2460
2461 /* Scan through the packet list and change all columns that use the
2462    "command-line-specified" time stamp format to use the current
2463    value of that format. */
2464 void
2465 cf_change_time_formats(capture_file *cf)
2466 {
2467   frame_data *fdata;
2468   progdlg_t  *progbar = NULL;
2469   gboolean    stop_flag;
2470   int         count;
2471   int         row;
2472   int         i;
2473   float       progbar_val;
2474   GTimeVal    start_time;
2475   gchar       status_str[100];
2476   int         progbar_nextstep;
2477   int         progbar_quantum;
2478   int         first, last;
2479   gboolean    sorted_by_frame_column;
2480
2481
2482   /* adjust timestamp precision if auto is selected */
2483   cf_timestamp_auto_precision(cf);
2484
2485   /* Are there any columns with time stamps in the "command-line-specified"
2486      format?
2487
2488      XXX - we have to force the "column is writable" flag on, as it
2489      might be off from the last frame that was dissected. */
2490   col_set_writable(&cf->cinfo, TRUE);
2491   if (!check_col(&cf->cinfo, COL_CLS_TIME)) {
2492     /* No, there aren't any columns in that format, so we have no work
2493        to do. */
2494     return;
2495   }
2496   first = cf->cinfo.col_first[COL_CLS_TIME];
2497   g_assert(first >= 0);
2498   last = cf->cinfo.col_last[COL_CLS_TIME];
2499
2500   /* Freeze the packet list while we redo it, so we don't get any
2501      screen updates while it happens. */
2502   packet_list_freeze();
2503
2504   /* Update the progress bar when it gets to this value. */
2505   progbar_nextstep = 0;
2506   /* When we reach the value that triggers a progress bar update,
2507      bump that value by this amount. */
2508   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2509   /* Count of packets at which we've looked. */
2510   count = 0;
2511   /* Progress so far. */
2512   progbar_val = 0.0;
2513
2514   /*  If the rows are currently sorted by the frame column then we know
2515    *  the row number of each packet: it's the row number of the previously
2516    *  displayed packet + 1.
2517    *
2518    *  Otherwise, if the display is sorted by a different column then we have
2519    *  to use the O(N) packet_list_find_row_from_data() (thus making the job
2520    *  of changing the time display format O(N**2)).
2521    *
2522    *  (XXX - In fact it's still O(N**2) because gtk_clist_set_text() takes
2523    *  the row number and walks that many elements down the clist to find
2524    *  the appropriate element.)
2525    */
2526   sorted_by_frame_column = FALSE;
2527   for (i = 0; i < cf->cinfo.num_cols; i++) {
2528     if (cf->cinfo.col_fmt[i] == COL_NUMBER)
2529     {
2530       sorted_by_frame_column = (i == packet_list_get_sort_column());
2531       break;
2532     }
2533   }
2534
2535   stop_flag = FALSE;
2536   g_get_current_time(&start_time);
2537
2538   /* Iterate through the list of packets, checking whether the packet
2539      is in a row of the summary list and, if so, whether there are
2540      any columns that show the time in the "command-line-specified"
2541      format and, if so, update that row. */
2542   for (fdata = cf->plist, row = -1; fdata != NULL; fdata = fdata->next) {
2543     /* Create the progress bar if necessary.
2544        We check on every iteration of the loop, so that it takes no
2545        longer than the standard time to create it (otherwise, for a
2546        large file, we might take considerably longer than that standard
2547        time in order to get to the next progress bar step). */
2548     if (progbar == NULL)
2549       progbar = delayed_create_progress_dlg("Changing", "time display",
2550         TRUE, &stop_flag, &start_time, progbar_val);
2551
2552     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
2553        when we update it, we have to run the GTK+ main loop to get it
2554        to repaint what's pending, and doing so may involve an "ioctl()"
2555        to see if there's any pending input from an X server, and doing
2556        that for every packet can be costly, especially on a big file. */
2557     if (count >= progbar_nextstep) {
2558       /* let's not divide by zero. I should never be started
2559        * with count == 0, so let's assert that
2560        */
2561       g_assert(cf->count > 0);
2562
2563       progbar_val = (gfloat) count / cf->count;
2564
2565       if (progbar != NULL) {
2566         g_snprintf(status_str, sizeof(status_str),
2567                    "%4u of %u packets", count, cf->count);
2568         update_progress_dlg(progbar, progbar_val, status_str);
2569       }
2570
2571       progbar_nextstep += progbar_quantum;
2572     }
2573
2574     if (stop_flag) {
2575       /* Well, the user decided to abort the redisplay.  Just stop.
2576
2577          XXX - this leaves the time field in the old format in
2578          frames we haven't yet processed.  So it goes; should we
2579          simply not offer them the option of stopping? */
2580       break;
2581     }
2582
2583     count++;
2584
2585     /* Find what row this packet is in. */
2586     if (!sorted_by_frame_column) {
2587       /* This function is O(N), so we try to avoid using it... */
2588       row = packet_list_find_row_from_data(fdata);
2589     } else {
2590       /* ...which we do by maintaining a count of packets that are
2591          being displayed (i.e., that have passed the display filter),
2592          and using the current value of that count as the row number
2593          (which is why we can only do it when the display is sorted
2594          by the frame number). */
2595       if (fdata->flags.passed_dfilter)
2596         row++;
2597       else
2598         continue;
2599     }
2600
2601     if (row != -1) {
2602       /* This packet is in the summary list, on row "row". */
2603
2604       for (i = first; i <= last; i++) {
2605         if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
2606           /* This is one of the columns that shows the time in
2607              "command-line-specified" format; update it. */
2608           cf->cinfo.col_buf[i][0] = '\0';
2609           col_set_cls_time(fdata, &cf->cinfo, i);
2610           packet_list_set_text(row, i, cf->cinfo.col_data[i]);
2611         }
2612       }
2613     }
2614   }
2615
2616   /* We're done redisplaying the packets; destroy the progress bar if it
2617      was created. */
2618   if (progbar != NULL)
2619     destroy_progress_dlg(progbar);
2620
2621   /* Set the column widths of those columns that show the time in
2622      "command-line-specified" format. */
2623   for (i = first; i <= last; i++) {
2624     if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
2625       packet_list_set_cls_time_width(i);
2626     }
2627   }
2628
2629   /* Unfreeze the packet list. */
2630   packet_list_thaw();
2631 }
2632
2633 typedef struct {
2634         const char      *string;
2635         size_t          string_len;
2636         capture_file    *cf;
2637         gboolean        frame_matched;
2638 } match_data;
2639
2640 gboolean
2641 cf_find_packet_protocol_tree(capture_file *cf, const char *string)
2642 {
2643   match_data            mdata;
2644
2645   mdata.string = string;
2646   mdata.string_len = strlen(string);
2647   return find_packet(cf, match_protocol_tree, &mdata);
2648 }
2649
2650 static gboolean
2651 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
2652 {
2653   match_data            *mdata = criterion;
2654   epan_dissect_t        *edt;
2655
2656   /* Construct the protocol tree, including the displayed text */
2657   edt = epan_dissect_new(TRUE, TRUE);
2658   /* We don't need the column information */
2659   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
2660
2661   /* Iterate through all the nodes, seeing if they have text that matches. */
2662   mdata->cf = cf;
2663   mdata->frame_matched = FALSE;
2664   proto_tree_children_foreach(edt->tree, match_subtree_text, mdata);
2665   epan_dissect_free(edt);
2666   return mdata->frame_matched;
2667 }
2668
2669 static void
2670 match_subtree_text(proto_node *node, gpointer data)
2671 {
2672   match_data    *mdata = (match_data*) data;
2673   const gchar   *string = mdata->string;
2674   size_t        string_len = mdata->string_len;
2675   capture_file  *cf = mdata->cf;
2676   field_info    *fi = PITEM_FINFO(node);
2677   gchar         label_str[ITEM_LABEL_LENGTH];
2678   gchar         *label_ptr;
2679   size_t        label_len;
2680   guint32       i;
2681   guint8        c_char;
2682   size_t        c_match = 0;
2683
2684   if (mdata->frame_matched) {
2685     /* We already had a match; don't bother doing any more work. */
2686     return;
2687   }
2688
2689   /* Don't match invisible entries. */
2690   if (PROTO_ITEM_IS_HIDDEN(node))
2691     return;
2692
2693   /* was a free format label produced? */
2694   if (fi->rep) {
2695     label_ptr = fi->rep->representation;
2696   } else {
2697     /* no, make a generic label */
2698     label_ptr = label_str;
2699     proto_item_fill_label(fi, label_str);
2700   }
2701
2702   /* Does that label match? */
2703   label_len = strlen(label_ptr);
2704   for (i = 0; i < label_len; i++) {
2705     c_char = label_ptr[i];
2706     if (cf->case_type)
2707       c_char = toupper(c_char);
2708     if (c_char == string[c_match]) {
2709       c_match++;
2710       if (c_match == string_len) {
2711         /* No need to look further; we have a match */
2712         mdata->frame_matched = TRUE;
2713         return;
2714       }
2715     } else
2716       c_match = 0;
2717   }
2718
2719   /* Recurse into the subtree, if it exists */
2720   if (node->first_child != NULL)
2721     proto_tree_children_foreach(node, match_subtree_text, mdata);
2722 }
2723
2724 gboolean
2725 cf_find_packet_summary_line(capture_file *cf, const char *string)
2726 {
2727   match_data            mdata;
2728
2729   mdata.string = string;
2730   mdata.string_len = strlen(string);
2731   return find_packet(cf, match_summary_line, &mdata);
2732 }
2733
2734 static gboolean
2735 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
2736 {
2737   match_data            *mdata = criterion;
2738   const gchar           *string = mdata->string;
2739   size_t                string_len = mdata->string_len;
2740   epan_dissect_t        *edt;
2741   const char            *info_column;
2742   size_t                info_column_len;
2743   gboolean              frame_matched = FALSE;
2744   gint                  colx;
2745   guint32               i;
2746   guint8                c_char;
2747   size_t                c_match = 0;
2748
2749   /* Don't bother constructing the protocol tree */
2750   edt = epan_dissect_new(FALSE, FALSE);
2751   /* Get the column information */
2752   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
2753
2754   /* Find the Info column */
2755   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
2756     if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
2757       /* Found it.  See if we match. */
2758       info_column = edt->pi.cinfo->col_data[colx];
2759       info_column_len = strlen(info_column);
2760       for (i = 0; i < info_column_len; i++) {
2761         c_char = info_column[i];
2762         if (cf->case_type)
2763           c_char = toupper(c_char);
2764         if (c_char == string[c_match]) {
2765           c_match++;
2766           if (c_match == string_len) {
2767             frame_matched = TRUE;
2768             break;
2769           }
2770         } else
2771           c_match = 0;
2772       }
2773       break;
2774     }
2775   }
2776   epan_dissect_free(edt);
2777   return frame_matched;
2778 }
2779
2780 typedef struct {
2781         const guint8 *data;
2782         size_t data_len;
2783 } cbs_t;        /* "Counted byte string" */
2784
2785 gboolean
2786 cf_find_packet_data(capture_file *cf, const guint8 *string, size_t string_size)
2787 {
2788   cbs_t info;
2789
2790   info.data = string;
2791   info.data_len = string_size;
2792
2793   /* String or hex search? */
2794   if (cf->string) {
2795     /* String search - what type of string? */
2796     switch (cf->scs_type) {
2797
2798     case SCS_ASCII_AND_UNICODE:
2799       return find_packet(cf, match_ascii_and_unicode, &info);
2800
2801     case SCS_ASCII:
2802       return find_packet(cf, match_ascii, &info);
2803
2804     case SCS_UNICODE:
2805       return find_packet(cf, match_unicode, &info);
2806
2807     default:
2808       g_assert_not_reached();
2809       return FALSE;
2810     }
2811   } else
2812     return find_packet(cf, match_binary, &info);
2813 }
2814
2815 static gboolean
2816 match_ascii_and_unicode(capture_file *cf, frame_data *fdata, void *criterion)
2817 {
2818   cbs_t         *info = criterion;
2819   const char    *ascii_text = info->data;
2820   size_t        textlen = info->data_len;
2821   gboolean      frame_matched;
2822   guint32       buf_len;
2823   guint32       i;
2824   guint8        c_char;
2825   size_t        c_match = 0;
2826
2827   frame_matched = FALSE;
2828   buf_len = fdata->pkt_len;
2829   for (i = 0; i < buf_len; i++) {
2830     c_char = cf->pd[i];
2831     if (cf->case_type)
2832       c_char = toupper(c_char);
2833     if (c_char != 0) {
2834       if (c_char == ascii_text[c_match]) {
2835         c_match++;
2836         if (c_match == textlen) {
2837           frame_matched = TRUE;
2838           cf->search_pos = i; /* Save the position of the last character
2839                                for highlighting the field. */
2840           break;
2841         }
2842       } else
2843         c_match = 0;
2844     }
2845   }
2846   return frame_matched;
2847 }
2848
2849 static gboolean
2850 match_ascii(capture_file *cf, frame_data *fdata, void *criterion)
2851 {
2852   cbs_t         *info = criterion;
2853   const char    *ascii_text = info->data;
2854   size_t        textlen = info->data_len;
2855   gboolean      frame_matched;
2856   guint32       buf_len;
2857   guint32       i;
2858   guint8        c_char;
2859   size_t        c_match = 0;
2860
2861   frame_matched = FALSE;
2862   buf_len = fdata->pkt_len;
2863   for (i = 0; i < buf_len; i++) {
2864     c_char = cf->pd[i];
2865     if (cf->case_type)
2866       c_char = toupper(c_char);
2867     if (c_char == ascii_text[c_match]) {
2868       c_match++;
2869       if (c_match == textlen) {
2870         frame_matched = TRUE;
2871         cf->search_pos = i; /* Save the position of the last character
2872                                for highlighting the field. */
2873         break;
2874       }
2875     } else
2876       c_match = 0;
2877   }
2878   return frame_matched;
2879 }
2880
2881 static gboolean
2882 match_unicode(capture_file *cf, frame_data *fdata, void *criterion)
2883 {
2884   cbs_t         *info = criterion;
2885   const char    *ascii_text = info->data;
2886   size_t        textlen = info->data_len;
2887   gboolean      frame_matched;
2888   guint32       buf_len;
2889   guint32       i;
2890   guint8        c_char;
2891   size_t        c_match = 0;
2892
2893   frame_matched = FALSE;
2894   buf_len = fdata->pkt_len;
2895   for (i = 0; i < buf_len; i++) {
2896     c_char = cf->pd[i];
2897     if (cf->case_type)
2898       c_char = toupper(c_char);
2899     if (c_char == ascii_text[c_match]) {
2900       c_match++;
2901       i++;
2902       if (c_match == textlen) {
2903         frame_matched = TRUE;
2904         cf->search_pos = i; /* Save the position of the last character
2905                                for highlighting the field. */
2906         break;
2907       }
2908     } else
2909       c_match = 0;
2910   }
2911   return frame_matched;
2912 }
2913
2914 static gboolean
2915 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
2916 {
2917   cbs_t         *info = criterion;
2918   const guint8  *binary_data = info->data;
2919   size_t        datalen = info->data_len;
2920   gboolean      frame_matched;
2921   guint32       buf_len;
2922   guint32       i;
2923   size_t        c_match = 0;
2924
2925   frame_matched = FALSE;
2926   buf_len = fdata->pkt_len;
2927   for (i = 0; i < buf_len; i++) {
2928     if (cf->pd[i] == binary_data[c_match]) {
2929       c_match++;
2930       if (c_match == datalen) {
2931         frame_matched = TRUE;
2932         cf->search_pos = i; /* Save the position of the last character
2933                                for highlighting the field. */
2934         break;
2935       }
2936     } else
2937       c_match = 0;
2938   }
2939   return frame_matched;
2940 }
2941
2942 gboolean
2943 cf_find_packet_dfilter(capture_file *cf, dfilter_t *sfcode)
2944 {
2945   return find_packet(cf, match_dfilter, sfcode);
2946 }
2947
2948 static gboolean
2949 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
2950 {
2951   dfilter_t             *sfcode = criterion;
2952   epan_dissect_t        *edt;
2953   gboolean              frame_matched;
2954
2955   edt = epan_dissect_new(TRUE, FALSE);
2956   epan_dissect_prime_dfilter(edt, sfcode);
2957   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
2958   frame_matched = dfilter_apply_edt(sfcode, edt);
2959   epan_dissect_free(edt);
2960   return frame_matched;
2961 }
2962
2963 static gboolean
2964 find_packet(capture_file *cf,
2965             gboolean (*match_function)(capture_file *, frame_data *, void *),
2966             void *criterion)
2967 {
2968   frame_data *start_fd;
2969   frame_data *fdata;
2970   frame_data *new_fd = NULL;
2971   progdlg_t  *progbar = NULL;
2972   gboolean    stop_flag;
2973   int         count;
2974   int         err;
2975   gchar      *err_info;
2976   int         row;
2977   float       progbar_val;
2978   GTimeVal    start_time;
2979   gchar       status_str[100];
2980   int         progbar_nextstep;
2981   int         progbar_quantum;
2982   char       *title;
2983
2984   start_fd = cf->current_frame;
2985   if (start_fd != NULL)  {
2986     /* Iterate through the list of packets, starting at the packet we've
2987        picked, calling a routine to run the filter on the packet, see if
2988        it matches, and stop if so.  */
2989     count = 0;
2990     fdata = start_fd;
2991
2992     /* Update the progress bar when it gets to this value. */
2993     progbar_nextstep = 0;
2994     /* When we reach the value that triggers a progress bar update,
2995        bump that value by this amount. */
2996     progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2997     /* Progress so far. */
2998     progbar_val = 0.0;
2999
3000     stop_flag = FALSE;
3001     g_get_current_time(&start_time);
3002
3003     fdata = start_fd;
3004     title = cf->sfilter?cf->sfilter:"";
3005     for (;;) {
3006       /* Create the progress bar if necessary.
3007          We check on every iteration of the loop, so that it takes no
3008          longer than the standard time to create it (otherwise, for a
3009          large file, we might take considerably longer than that standard
3010          time in order to get to the next progress bar step). */
3011       if (progbar == NULL)
3012          progbar = delayed_create_progress_dlg("Searching", title,
3013            FALSE, &stop_flag, &start_time, progbar_val);
3014
3015       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
3016          when we update it, we have to run the GTK+ main loop to get it
3017          to repaint what's pending, and doing so may involve an "ioctl()"
3018          to see if there's any pending input from an X server, and doing
3019          that for every packet can be costly, especially on a big file. */
3020       if (count >= progbar_nextstep) {
3021         /* let's not divide by zero. I should never be started
3022          * with count == 0, so let's assert that
3023          */
3024         g_assert(cf->count > 0);
3025
3026         progbar_val = (gfloat) count / cf->count;
3027
3028         if (progbar != NULL) {
3029           g_snprintf(status_str, sizeof(status_str),
3030                      "%4u of %u packets", count, cf->count);
3031           update_progress_dlg(progbar, progbar_val, status_str);
3032         }
3033
3034         progbar_nextstep += progbar_quantum;
3035       }
3036
3037       if (stop_flag) {
3038         /* Well, the user decided to abort the search.  Go back to the
3039            frame where we started. */
3040         new_fd = start_fd;
3041         break;
3042       }
3043
3044       /* Go past the current frame. */
3045       if (cf->sbackward) {
3046         /* Go on to the previous frame. */
3047         fdata = fdata->prev;
3048         if (fdata == NULL) {
3049           /*
3050            * XXX - other apps have a bit more of a detailed message
3051            * for this, and instead of offering "OK" and "Cancel",
3052            * they offer things such as "Continue" and "Cancel";
3053            * we need an API for popping up alert boxes with
3054            * {Verb} and "Cancel".
3055            */
3056
3057           if (prefs.gui_find_wrap)
3058           {
3059               simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
3060                             "%sBeginning of capture exceeded!%s\n\n"
3061                             "Search is continued from the end of the capture.",
3062                             simple_dialog_primary_start(), simple_dialog_primary_end());
3063               fdata = cf->plist_end;    /* wrap around */
3064           }
3065           else
3066           {
3067               simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
3068                             "%sBeginning of capture exceeded!%s\n\n"
3069                             "Try searching forwards.",
3070                             simple_dialog_primary_start(), simple_dialog_primary_end());
3071               fdata = start_fd;        /* stay on previous packet */
3072           }
3073         }
3074       } else {
3075         /* Go on to the next frame. */
3076         fdata = fdata->next;
3077         if (fdata == NULL) {
3078           if (prefs.gui_find_wrap)
3079           {
3080               simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
3081                             "%sEnd of capture exceeded!%s\n\n"
3082                             "Search is continued from the start of the capture.",
3083                             simple_dialog_primary_start(), simple_dialog_primary_end());
3084               fdata = cf->plist;        /* wrap around */
3085           }
3086           else
3087           {
3088               simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
3089                             "%sEnd of capture exceeded!%s\n\n"
3090                             "Try searching backwards.",
3091                             simple_dialog_primary_start(), simple_dialog_primary_end());
3092               fdata = start_fd;     /* stay on previous packet */
3093           }
3094         }
3095       }
3096
3097       count++;
3098
3099       /* Is this packet in the display? */
3100       if (fdata->flags.passed_dfilter) {
3101         /* Yes.  Load its data. */
3102         if (!wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
3103                         cf->pd, fdata->cap_len, &err, &err_info)) {
3104           /* Read error.  Report the error, and go back to the frame
3105              where we started. */
3106           simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3107                         cf_read_error_message(err, err_info), cf->filename);
3108           new_fd = start_fd;
3109           break;
3110         }
3111
3112         /* Does it match the search criterion? */
3113         if ((*match_function)(cf, fdata, criterion)) {
3114           new_fd = fdata;
3115           break;        /* found it! */
3116         }
3117       }
3118
3119       if (fdata == start_fd) {
3120         /* We're back to the frame we were on originally, and that frame
3121            doesn't match the search filter.  The search failed. */
3122         break;
3123       }
3124     }
3125
3126     /* We're done scanning the packets; destroy the progress bar if it
3127        was created. */
3128     if (progbar != NULL)
3129       destroy_progress_dlg(progbar);
3130   }
3131
3132   if (new_fd != NULL) {
3133     /* We found a frame.  Find what row it's in. */
3134     row = packet_list_find_row_from_data(new_fd);
3135     g_assert(row != -1);
3136
3137     /* Select that row, make it the focus row, and make it visible. */
3138     packet_list_set_selected_row(row);
3139     return TRUE;        /* success */
3140   } else
3141     return FALSE;       /* failure */
3142 }
3143
3144 gboolean
3145 cf_goto_frame(capture_file *cf, guint fnumber)
3146 {
3147   frame_data *fdata;
3148   int row;
3149
3150   for (fdata = cf->plist; fdata != NULL && fdata->num < fnumber; fdata = fdata->next)
3151     ;
3152
3153   if (fdata == NULL) {
3154     /* we didn't find a packet with that packet number */
3155     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3156                   "There is no packet with the packet number %u.", fnumber);
3157     return FALSE;       /* we failed to go to that packet */
3158   }
3159   if (!fdata->flags.passed_dfilter) {
3160     /* that packet currently isn't displayed */
3161     /* XXX - add it to the set of displayed packets? */
3162     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3163                   "The packet number %u isn't currently being displayed.", fnumber);
3164     return FALSE;       /* we failed to go to that packet */
3165   }
3166
3167   /* We found that packet, and it's currently being displayed.
3168      Find what row it's in. */
3169   row = packet_list_find_row_from_data(fdata);
3170   g_assert(row != -1);
3171
3172   /* Select that row, make it the focus row, and make it visible. */
3173   packet_list_set_selected_row(row);
3174   return TRUE;  /* we got to that packet */
3175 }
3176
3177 gboolean
3178 cf_goto_top_frame(capture_file *cf)
3179 {
3180   frame_data *fdata;
3181   int row;
3182   frame_data *lowest_fdata = NULL;
3183
3184   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
3185     if (fdata->flags.passed_dfilter) {
3186         lowest_fdata = fdata;
3187         break;
3188     }
3189   }
3190
3191   if (lowest_fdata == NULL) {
3192       return FALSE;
3193   }
3194
3195   /* We found that packet, and it's currently being displayed.
3196      Find what row it's in. */
3197   row = packet_list_find_row_from_data(lowest_fdata);
3198   g_assert(row != -1);
3199
3200   /* Select that row, make it the focus row, and make it visible. */
3201   packet_list_set_selected_row(row);
3202   return TRUE;  /* we got to that packet */
3203 }
3204
3205 gboolean
3206 cf_goto_bottom_frame(capture_file *cf)
3207 {
3208   frame_data *fdata;
3209   int row;
3210   frame_data *highest_fdata = NULL;
3211
3212   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
3213     if (fdata->flags.passed_dfilter) {
3214         highest_fdata = fdata;
3215     }
3216   }
3217
3218   if (highest_fdata == NULL) {
3219       return FALSE;
3220   }
3221
3222   /* We found that packet, and it's currently being displayed.
3223      Find what row it's in. */
3224   row = packet_list_find_row_from_data(highest_fdata);
3225   g_assert(row != -1);
3226
3227   /* Select that row, make it the focus row, and make it visible. */
3228   packet_list_set_selected_row(row);
3229   return TRUE;  /* we got to that packet */
3230 }
3231
3232 /*
3233  * Go to frame specified by currently selected protocol tree item.
3234  */
3235 gboolean
3236 cf_goto_framenum(capture_file *cf)
3237 {
3238   header_field_info       *hfinfo;
3239   guint32                 framenum;
3240
3241   if (cf->finfo_selected) {
3242     hfinfo = cf->finfo_selected->hfinfo;
3243     g_assert(hfinfo);
3244     if (hfinfo->type == FT_FRAMENUM) {
3245       framenum = fvalue_get_uinteger(&cf->finfo_selected->value);
3246       if (framenum != 0)
3247         return cf_goto_frame(cf, framenum);
3248       }
3249   }
3250
3251   return FALSE;
3252 }
3253
3254 /* Select the packet on a given row. */
3255 void
3256 cf_select_packet(capture_file *cf, int row)
3257 {
3258   frame_data *fdata;
3259   int err;
3260   gchar *err_info;
3261
3262   /* Get the frame data struct pointer for this frame */
3263   fdata = (frame_data *)packet_list_get_row_data(row);
3264
3265   if (fdata == NULL) {
3266     /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
3267        the first entry is added to it by "real_insert_row()", that row
3268        is selected (see "real_insert_row()", in "gtk/gtkclist.c", in both
3269        our version and the vanilla GTK+ version).
3270
3271        This means that a "select-row" signal is emitted; this causes
3272        "packet_list_select_cb()" to be called, which causes "cf_select_packet()"
3273        to be called.
3274
3275        "cf_select_packet()" fetches, above, the data associated with the
3276        row that was selected; however, as "gtk_clist_append()", which
3277        called "real_insert_row()", hasn't yet returned, we haven't yet
3278        associated any data with that row, so we get back a null pointer.
3279
3280        We can't assume that there's only one frame in the frame list,
3281        either, as we may be filtering the display.
3282
3283        We therefore assume that, if "row" is 0, i.e. the first row
3284        is being selected, and "cf->first_displayed" equals
3285        "cf->last_displayed", i.e. there's only one frame being
3286        displayed, that frame is the frame we want.
3287
3288        This means we have to set "cf->first_displayed" and
3289        "cf->last_displayed" before adding the row to the
3290        GtkCList; see the comment in "add_packet_to_packet_list()". */
3291
3292        if (row == 0 && cf->first_displayed == cf->last_displayed)
3293          fdata = cf->first_displayed;
3294   }
3295
3296   /* If fdata _still_ isn't set simply give up. */
3297   if (fdata == NULL) {
3298     return;
3299   }
3300
3301   /* Get the data in that frame. */
3302   if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
3303                        cf->pd, fdata->cap_len, &err, &err_info)) {
3304     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3305                   cf_read_error_message(err, err_info), cf->filename);
3306     return;
3307   }
3308
3309   /* Record that this frame is the current frame. */
3310   cf->current_frame = fdata;
3311
3312   /* Create the logical protocol tree. */
3313   if (cf->edt != NULL) {
3314     epan_dissect_free(cf->edt);
3315     cf->edt = NULL;
3316   }
3317   /* We don't need the columns here. */
3318   cf->edt = epan_dissect_new(TRUE, TRUE);
3319
3320   epan_dissect_run(cf->edt, &cf->pseudo_header, cf->pd, cf->current_frame,
3321           NULL);
3322
3323   dfilter_macro_build_ftv_cache(cf->edt->tree);
3324
3325   cf_callback_invoke(cf_cb_packet_selected, cf);
3326 }
3327
3328 /* Unselect the selected packet, if any. */
3329 void
3330 cf_unselect_packet(capture_file *cf)
3331 {
3332   /* Destroy the epan_dissect_t for the unselected packet. */
3333   if (cf->edt != NULL) {
3334     epan_dissect_free(cf->edt);
3335     cf->edt = NULL;
3336   }
3337
3338   /* No packet is selected. */
3339   cf->current_frame = NULL;
3340
3341   cf_callback_invoke(cf_cb_packet_unselected, cf);
3342
3343   /* No protocol tree means no selected field. */
3344   cf_unselect_field(cf);
3345 }
3346
3347 /* Unset the selected protocol tree field, if any. */
3348 void
3349 cf_unselect_field(capture_file *cf)
3350 {
3351   cf->finfo_selected = NULL;
3352
3353   cf_callback_invoke(cf_cb_field_unselected, cf);
3354 }
3355
3356 /*
3357  * Mark a particular frame.
3358  */
3359 void
3360 cf_mark_frame(capture_file *cf, frame_data *frame)
3361 {
3362   if (! frame->flags.marked) {
3363     frame->flags.marked = TRUE;
3364     if (cf->count > cf->marked_count)
3365       cf->marked_count++;
3366   }
3367 }
3368
3369 /*
3370  * Unmark a particular frame.
3371  */
3372 void
3373 cf_unmark_frame(capture_file *cf, frame_data *frame)
3374 {
3375   if (frame->flags.marked) {
3376     frame->flags.marked = FALSE;
3377     if (cf->marked_count > 0)
3378       cf->marked_count--;
3379   }
3380 }
3381
3382 typedef struct {
3383   wtap_dumper *pdh;
3384   const char  *fname;
3385 } save_callback_args_t;
3386
3387 /*
3388  * Save a capture to a file, in a particular format, saving either
3389  * all packets, all currently-displayed packets, or all marked packets.
3390  *
3391  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
3392  * up a message box for the failure.
3393  */
3394 static gboolean
3395 save_packet(capture_file *cf _U_, frame_data *fdata,
3396             union wtap_pseudo_header *pseudo_header, const guint8 *pd,
3397             void *argsp)
3398 {
3399   save_callback_args_t *args = argsp;
3400   struct wtap_pkthdr hdr;
3401   int           err;
3402
3403   /* init the wtap header for saving */
3404   hdr.ts.secs    = fdata->abs_ts.secs;
3405   hdr.ts.nsecs   = fdata->abs_ts.nsecs;
3406   hdr.caplen     = fdata->cap_len;
3407   hdr.len        = fdata->pkt_len;
3408   hdr.pkt_encap  = fdata->lnk_t;
3409
3410   /* and save the packet */
3411   if (!wtap_dump(args->pdh, &hdr, pseudo_header, pd, &err)) {
3412     cf_write_failure_alert_box(args->fname, err);
3413     return FALSE;
3414   }
3415   return TRUE;
3416 }
3417
3418 /*
3419  * Can this capture file be saved in any format except by copying the raw data?
3420  */
3421 gboolean
3422 cf_can_save_as(capture_file *cf)
3423 {
3424   int ft;
3425
3426   for (ft = 0; ft < WTAP_NUM_FILE_TYPES; ft++) {
3427     /* To save a file with Wiretap, Wiretap has to handle that format,
3428        and its code to handle that format must be able to write a file
3429        with this file's encapsulation type. */
3430     if (wtap_dump_can_open(ft) && wtap_dump_can_write_encap(ft, cf->lnk_t)) {
3431       /* OK, we can write it out in this type. */
3432       return TRUE;
3433     }
3434   }
3435
3436   /* No, we couldn't save it in any format. */
3437   return FALSE;
3438 }
3439
3440 cf_status_t
3441 cf_save(capture_file *cf, const char *fname, packet_range_t *range, guint save_format, gboolean compressed)
3442 {
3443   gchar        *from_filename;
3444   int           err;
3445   gboolean      do_copy;
3446   wtap_dumper  *pdh;
3447   save_callback_args_t callback_args;
3448
3449   cf_callback_invoke(cf_cb_file_safe_started, (gpointer) fname);
3450
3451   /* don't write over an existing file. */
3452   /* this should've been already checked by our caller, just to be sure... */
3453   if (file_exists(fname)) {
3454     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3455       "%sCapture file: \"%s\" already exists!%s\n\n"
3456       "Please choose a different filename.",
3457       simple_dialog_primary_start(), fname, simple_dialog_primary_end());
3458     goto fail;
3459   }
3460
3461   packet_range_process_init(range);
3462
3463
3464   if (packet_range_process_all(range) && save_format == cf->cd_t) {
3465     /* We're not filtering packets, and we're saving it in the format
3466        it's already in, so we can just move or copy the raw data. */
3467
3468     if (cf->is_tempfile) {
3469       /* The file being saved is a temporary file from a live
3470          capture, so it doesn't need to stay around under that name;
3471          first, try renaming the capture buffer file to the new name. */
3472 #ifndef _WIN32
3473       if (eth_rename(cf->filename, fname) == 0) {
3474         /* That succeeded - there's no need to copy the source file. */
3475         from_filename = NULL;
3476         do_copy = FALSE;
3477       } else {
3478         if (errno == EXDEV) {
3479           /* They're on different file systems, so we have to copy the
3480              file. */
3481           do_copy = TRUE;
3482           from_filename = cf->filename;
3483         } else {
3484           /* The rename failed, but not because they're on different
3485              file systems - put up an error message.  (Or should we
3486              just punt and try to copy?  The only reason why I'd
3487              expect the rename to fail and the copy to succeed would
3488              be if we didn't have permission to remove the file from
3489              the temporary directory, and that might be fixable - but
3490              is it worth requiring the user to go off and fix it?) */
3491           simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3492                                 file_rename_error_message(errno), fname);
3493           goto fail;
3494         }
3495       }
3496 #else
3497       do_copy = TRUE;
3498       from_filename = cf->filename;
3499 #endif
3500     } else {
3501       /* It's a permanent file, so we should copy it, and not remove the
3502          original. */
3503       do_copy = TRUE;
3504       from_filename = cf->filename;
3505     }
3506
3507     if (do_copy) {
3508       /* Copy the file, if we haven't moved it. */
3509       if (!copy_binary_file(from_filename, fname))
3510         goto fail;
3511     }
3512   } else {
3513     /* Either we're filtering packets, or we're saving in a different
3514        format; we can't do that by copying or moving the capture file,
3515        we have to do it by writing the packets out in Wiretap. */
3516     pdh = wtap_dump_open(fname, save_format, cf->lnk_t, cf->snap,
3517                 compressed, &err);
3518     if (pdh == NULL) {
3519       cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
3520       goto fail;
3521     }
3522
3523     /* XXX - we let the user save a subset of the packets.
3524
3525        If we do that, should we make that file the current file?  If so,
3526        it means we can no longer get at the other packets.  What does
3527        NetMon do? */
3528
3529     /* Iterate through the list of packets, processing the packets we were
3530        told to process.
3531
3532        XXX - we've already called "packet_range_process_init(range)", but
3533        "process_specified_packets()" will do it again.  Fortunately,
3534        that's harmless in this case, as we haven't done anything to
3535        "range" since we initialized it. */
3536     callback_args.pdh = pdh;
3537     callback_args.fname = fname;
3538     switch (process_specified_packets(cf, range, "Saving", "selected packets",
3539                                       TRUE, save_packet, &callback_args)) {
3540
3541     case PSP_FINISHED:
3542       /* Completed successfully. */
3543       break;
3544
3545     case PSP_STOPPED:
3546       /* The user decided to abort the saving.
3547          XXX - remove the output file? */
3548       break;
3549
3550     case PSP_FAILED:
3551       /* Error while saving. */
3552       wtap_dump_close(pdh, &err);
3553       goto fail;
3554     }
3555
3556     if (!wtap_dump_close(pdh, &err)) {
3557       cf_close_failure_alert_box(fname, err);
3558       goto fail;
3559     }
3560   }
3561
3562   cf_callback_invoke(cf_cb_file_safe_finished, NULL);
3563
3564   if (packet_range_process_all(range)) {
3565     /* We saved the entire capture, not just some packets from it.
3566        Open and read the file we saved it to.
3567
3568        XXX - this is somewhat of a waste; we already have the
3569        packets, all this gets us is updated file type information
3570        (which we could just stuff into "cf"), and having the new
3571        file be the one we have opened and from which we're reading
3572        the data, and it means we have to spend time opening and
3573        reading the file, which could be a significant amount of
3574        time if the file is large. */
3575     cf->user_saved = TRUE;
3576
3577     if ((cf_open(cf, fname, FALSE, &err)) == CF_OK) {
3578       /* XXX - report errors if this fails?
3579          What should we return if it fails or is aborted? */
3580       switch (cf_read(cf)) {
3581
3582       case CF_READ_OK:
3583       case CF_READ_ERROR:
3584         /* Just because we got an error, that doesn't mean we were unable
3585            to read any of the file; we handle what we could get from the
3586            file. */
3587         break;
3588
3589       case CF_READ_ABORTED:
3590         /* The user bailed out of re-reading the capture file; the
3591            capture file has been closed - just return (without
3592            changing any menu settings; "cf_close()" set them
3593            correctly for the "no capture file open" state). */
3594         break;
3595       }
3596       cf_callback_invoke(cf_cb_file_safe_reload_finished, NULL);
3597     }
3598   }
3599   return CF_OK;
3600
3601 fail:
3602   cf_callback_invoke(cf_cb_file_safe_failed, NULL);
3603   return CF_ERROR;
3604 }
3605
3606 static void
3607 cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
3608                           gboolean for_writing, int file_type)
3609 {
3610   if (err < 0) {
3611     /* Wiretap error. */
3612     switch (err) {
3613
3614     case WTAP_ERR_NOT_REGULAR_FILE:
3615       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3616                     "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
3617                     filename);
3618       break;
3619
3620     case WTAP_ERR_RANDOM_OPEN_PIPE:
3621       /* Seen only when opening a capture file for reading. */
3622       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3623                     "The file \"%s\" is a pipe or FIFO; Wireshark can't read pipe or FIFO files.",
3624                     filename);
3625       break;
3626
3627     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3628       /* Seen only when opening a capture file for reading. */
3629       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3630                     "The file \"%s\" isn't a capture file in a format Wireshark understands.",
3631                     filename);
3632       break;
3633
3634     case WTAP_ERR_UNSUPPORTED:
3635       /* Seen only when opening a capture file for reading. */
3636       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3637                     "The file \"%s\" isn't a capture file in a format Wireshark understands.\n"
3638                     "(%s)",
3639                     filename, err_info);
3640       g_free(err_info);
3641       break;
3642
3643     case WTAP_ERR_CANT_WRITE_TO_PIPE:
3644       /* Seen only when opening a capture file for writing. */
3645       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3646                     "The file \"%s\" is a pipe, and %s capture files can't be "
3647                     "written to a pipe.",
3648                     filename, wtap_file_type_string(file_type));
3649       break;
3650
3651     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3652       /* Seen only when opening a capture file for writing. */
3653       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3654                     "Wireshark doesn't support writing capture files in that format.");
3655       break;
3656
3657     case WTAP_ERR_UNSUPPORTED_ENCAP:
3658       if (for_writing) {
3659         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3660                       "Wireshark can't save this capture in that format.");
3661       } else {
3662         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3663                       "The file \"%s\" is a capture for a network type that Wireshark doesn't support.\n"
3664                       "(%s)",
3665                       filename, err_info);
3666         g_free(err_info);
3667       }
3668       break;
3669
3670     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3671       if (for_writing) {
3672         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3673                       "Wireshark can't save this capture in that format.");
3674       } else {
3675         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3676                       "The file \"%s\" is a capture for a network type that Wireshark doesn't support.",
3677                       filename);
3678       }
3679       break;
3680
3681     case WTAP_ERR_BAD_RECORD:
3682       /* Seen only when opening a capture file for reading. */
3683       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3684                     "The file \"%s\" appears to be damaged or corrupt.\n"
3685                     "(%s)",
3686                     filename, err_info);
3687       g_free(err_info);
3688       break;
3689
3690     case WTAP_ERR_CANT_OPEN:
3691       if (for_writing) {
3692         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3693                       "The file \"%s\" could not be created for some unknown reason.",
3694                       filename);
3695       } else {
3696         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3697                       "The file \"%s\" could not be opened for some unknown reason.",
3698                       filename);
3699       }
3700       break;
3701
3702     case WTAP_ERR_SHORT_READ:
3703       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3704                     "The file \"%s\" appears to have been cut short"
3705                     " in the middle of a packet or other data.",
3706                     filename);
3707       break;
3708
3709     case WTAP_ERR_SHORT_WRITE:
3710       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3711                     "A full header couldn't be written to the file \"%s\".",
3712                     filename);
3713       break;
3714
3715     case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
3716       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3717                     "Gzip compression not supported by this file type.");
3718       break;
3719
3720     default:
3721       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3722                     "The file \"%s\" could not be %s: %s.",
3723                     filename,
3724                     for_writing ? "created" : "opened",
3725                     wtap_strerror(err));
3726       break;
3727     }
3728   } else {
3729     /* OS error. */
3730     open_failure_alert_box(filename, err, for_writing);
3731   }
3732 }
3733
3734 static const char *
3735 file_rename_error_message(int err)
3736 {
3737   const char *errmsg;
3738   static char errmsg_errno[1024+1];
3739
3740   switch (err) {
3741
3742   case ENOENT:
3743     errmsg = "The path to the file \"%s\" doesn't exist.";
3744     break;
3745
3746   case EACCES:
3747     errmsg = "You don't have permission to move the capture file to \"%s\".";
3748     break;
3749
3750   default:
3751     g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3752                     "The file \"%%s\" could not be moved: %s.",
3753                                 wtap_strerror(err));
3754     errmsg = errmsg_errno;
3755     break;
3756   }
3757   return errmsg;
3758 }
3759
3760 char *
3761 cf_read_error_message(int err, const gchar *err_info)
3762 {
3763   static char errmsg_errno[1024+1];
3764
3765   switch (err) {
3766
3767   case WTAP_ERR_UNSUPPORTED_ENCAP:
3768       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3769                "The file \"%%s\" has a packet with a network type that Wireshark doesn't support.\n(%s)",
3770                err_info);
3771       break;
3772
3773   case WTAP_ERR_BAD_RECORD:
3774     g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3775              "An error occurred while reading from the file \"%%s\": %s.\n(%s)",
3776              wtap_strerror(err), err_info);
3777     break;
3778
3779   default:
3780     g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3781              "An error occurred while reading from the file \"%%s\": %s.",
3782              wtap_strerror(err));
3783     break;
3784   }
3785   return errmsg_errno;
3786 }
3787
3788 static void
3789 cf_write_failure_alert_box(const char *filename, int err)
3790 {
3791   if (err < 0) {
3792     /* Wiretap error. */
3793     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3794                   "An error occurred while writing to the file \"%s\": %s.",
3795                   filename, wtap_strerror(err));
3796   } else {
3797     /* OS error. */
3798     write_failure_alert_box(filename, err);
3799   }
3800 }
3801
3802 /* Check for write errors - if the file is being written to an NFS server,
3803    a write error may not show up until the file is closed, as NFS clients
3804    might not send writes to the server until the "write()" call finishes,
3805    so that the write may fail on the server but the "write()" may succeed. */
3806 static void
3807 cf_close_failure_alert_box(const char *filename, int err)
3808 {
3809   if (err < 0) {
3810     /* Wiretap error. */
3811     switch (err) {
3812
3813     case WTAP_ERR_CANT_CLOSE:
3814       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3815                     "The file \"%s\" couldn't be closed for some unknown reason.",
3816                     filename);
3817       break;
3818
3819     case WTAP_ERR_SHORT_WRITE:
3820       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3821                     "Not all the packets could be written to the file \"%s\".",
3822                     filename);
3823       break;
3824
3825     default:
3826       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3827                     "An error occurred while closing the file \"%s\": %s.",
3828                     filename, wtap_strerror(err));
3829       break;
3830     }
3831   } else {
3832     /* OS error.
3833        We assume that a close error from the OS is really a write error. */
3834     write_failure_alert_box(filename, err);
3835   }
3836 }
3837
3838 /* Reload the current capture file. */
3839 void
3840 cf_reload(capture_file *cf) {
3841   gchar *filename;
3842   gboolean is_tempfile;
3843   int err;
3844
3845   /* If the file could be opened, "cf_open()" calls "cf_close()"
3846      to get rid of state for the old capture file before filling in state
3847      for the new capture file.  "cf_close()" will remove the file if
3848      it's a temporary file; we don't want that to happen (for one thing,
3849      it'd prevent subsequent reopens from working).  Remember whether it's
3850      a temporary file, mark it as not being a temporary file, and then
3851      reopen it as the type of file it was.
3852
3853      Also, "cf_close()" will free "cf->filename", so we must make
3854      a copy of it first. */
3855   filename = g_strdup(cf->filename);
3856   is_tempfile = cf->is_tempfile;
3857   cf->is_tempfile = FALSE;
3858   if (cf_open(cf, filename, is_tempfile, &err) == CF_OK) {
3859     switch (cf_read(cf)) {
3860
3861     case CF_READ_OK:
3862     case CF_READ_ERROR:
3863       /* Just because we got an error, that doesn't mean we were unable
3864          to read any of the file; we handle what we could get from the
3865          file. */
3866       break;
3867
3868     case CF_READ_ABORTED:
3869       /* The user bailed out of re-reading the capture file; the
3870          capture file has been closed - just free the capture file name
3871          string and return (without changing the last containing
3872          directory). */
3873       g_free(filename);
3874       return;
3875     }
3876   } else {
3877     /* The open failed, so "cf->is_tempfile" wasn't set to "is_tempfile".
3878        Instead, the file was left open, so we should restore "cf->is_tempfile"
3879        ourselves.
3880
3881        XXX - change the menu?  Presumably "cf_open()" will do that;
3882        make sure it does! */
3883     cf->is_tempfile = is_tempfile;
3884   }
3885   /* "cf_open()" made a copy of the file name we handed it, so
3886      we should free up our copy. */
3887   g_free(filename);
3888 }
3889
3890 /* Copies a file in binary mode, for those operating systems that care about
3891  * such things.
3892  * Returns TRUE on success, FALSE on failure. If a failure, it also
3893  * displays a simple dialog window with the error message.
3894  */
3895 static gboolean
3896 copy_binary_file(const char *from_filename, const char *to_filename)
3897 {
3898   int           from_fd, to_fd, nread, nwritten, err;
3899   guint8        pd[65536];
3900
3901   /* Copy the raw bytes of the file. */
3902   from_fd = eth_open(from_filename, O_RDONLY | O_BINARY, 0000 /* no creation so don't matter */);
3903   if (from_fd < 0) {
3904     open_failure_alert_box(from_filename, errno, FALSE);
3905     goto done;
3906   }
3907
3908   /* Use open() instead of creat() so that we can pass the O_BINARY
3909      flag, which is relevant on Win32; it appears that "creat()"
3910      may open the file in text mode, not binary mode, but we want
3911      to copy the raw bytes of the file, so we need the output file
3912      to be open in binary mode. */
3913   to_fd = eth_open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
3914   if (to_fd < 0) {
3915     open_failure_alert_box(to_filename, errno, TRUE);
3916     eth_close(from_fd);
3917     goto done;
3918   }
3919
3920   while ((nread = eth_read(from_fd, pd, sizeof pd)) > 0) {
3921     nwritten = eth_write(to_fd, pd, nread);
3922     if (nwritten < nread) {
3923       if (nwritten < 0)
3924         err = errno;
3925       else
3926         err = WTAP_ERR_SHORT_WRITE;
3927       write_failure_alert_box(to_filename, err);
3928       eth_close(from_fd);
3929       eth_close(to_fd);
3930       goto done;
3931     }
3932   }
3933   if (nread < 0) {
3934     err = errno;
3935     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3936                   "An error occurred while reading from the file \"%s\": %s.",
3937                   from_filename, strerror(err));
3938     eth_close(from_fd);
3939     eth_close(to_fd);
3940     goto done;
3941   }
3942   eth_close(from_fd);
3943   if (eth_close(to_fd) < 0) {
3944     write_failure_alert_box(to_filename, errno);
3945     goto done;
3946   }
3947
3948   return TRUE;
3949
3950 done:
3951   return FALSE;
3952 }