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