From Greg Morris: if a search reaches the end or beginning of the list,
[obnox/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * $Id: file.c,v 1.365 2004/02/22 22:22:47 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
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 #ifdef HAVE_IO_H
36 #include <io.h>
37 #endif
38
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include <errno.h>
44 #include <signal.h>
45
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif
49
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53
54 #ifdef NEED_SNPRINTF_H
55 # include "snprintf.h"
56 #endif
57
58 #ifdef NEED_STRERROR_H
59 #include "strerror.h"
60 #endif
61
62 #include <epan/epan.h>
63 #include <epan/filesystem.h>
64
65 #include "color.h"
66 #include "column.h"
67 #include <epan/packet.h>
68 #include "range.h"
69 #include "print.h"
70 #include "file.h"
71 #include "menu.h"
72 #include "util.h"
73 #include "alert_box.h"
74 #include "simple_dialog.h"
75 #include "progress_dlg.h"
76 #include "ui_util.h"
77 #include "statusbar.h"
78 #include "prefs.h"
79 #include <epan/dfilter/dfilter.h>
80 #include <epan/conversation.h>
81 #include "globals.h"
82 #include <epan/epan_dissect.h>
83 #include "tap.h"
84 #include "tap_dfilter_dlg.h"
85 #include "packet-data.h"
86
87 #ifdef HAVE_LIBPCAP
88 gboolean auto_scroll_live;
89 #endif
90
91 static guint32 firstsec, firstusec;
92 static guint32 prevsec, prevusec;
93 static guint32 cum_bytes = 0;
94
95 static void read_packet(capture_file *cf, long offset);
96
97 static void rescan_packets(capture_file *cf, const char *action, const char *action_item,
98         gboolean refilter, gboolean redissect);
99
100 static gboolean match_protocol_tree(capture_file *cf, frame_data *fdata,
101         void *criterion);
102 static void match_subtree_text(proto_node *node, gpointer data);
103 static gboolean match_summary_line(capture_file *cf, frame_data *fdata,
104         void *criterion);
105 static gboolean match_ascii_and_unicode(capture_file *cf, frame_data *fdata,
106         void *criterion);
107 static gboolean match_ascii(capture_file *cf, frame_data *fdata,
108         void *criterion);
109 static gboolean match_unicode(capture_file *cf, frame_data *fdata,
110         void *criterion);
111 static gboolean match_binary(capture_file *cf, frame_data *fdata,
112         void *criterion);
113 static gboolean match_dfilter(capture_file *cf, frame_data *fdata,
114         void *criterion);
115 static gboolean find_packet(capture_file *cf,
116         gboolean (*match_function)(capture_file *, frame_data *, void *),
117         void *criterion);
118
119 static void cf_open_failure_alert_box(const char *filename, int err,
120                                       gchar *err_info, gboolean for_writing,
121                                       int file_type);
122 static char *file_rename_error_message(int err);
123 static void cf_write_failure_alert_box(const char *filename, int err);
124 static void cf_close_failure_alert_box(const char *filename, int err);
125 static   gboolean copy_binary_file(char *from_filename, char *to_filename);
126
127 /* Update the progress bar this many times when reading a file. */
128 #define N_PROGBAR_UPDATES       100
129
130 /* Number of "frame_data" structures per memory chunk.
131    XXX - is this the right number? */
132 #define FRAME_DATA_CHUNK_SIZE   1024
133
134 typedef struct {
135         int             level;
136         FILE            *fh;
137         GSList          *src_list;
138         gboolean        print_all_levels;
139         gboolean        print_hex_for_data;
140         char_enc        encoding;
141         gint            format;         /* text or PostScript */
142 } print_data;
143
144 int
145 cf_open(char *fname, gboolean is_tempfile, capture_file *cf)
146 {
147   wtap       *wth;
148   int         err;
149   gchar       *err_info;
150   int         fd;
151   struct stat cf_stat;
152
153   wth = wtap_open_offline(fname, &err, &err_info, TRUE);
154   if (wth == NULL)
155     goto fail;
156
157   /* Find the size of the file. */
158   fd = wtap_fd(wth);
159   if (fstat(fd, &cf_stat) < 0) {
160     err = errno;
161     wtap_close(wth);
162     goto fail;
163   }
164
165   /* The open succeeded.  Close whatever capture file we had open,
166      and fill in the information for this file. */
167   cf_close(cf);
168
169   /* Initialize all data structures used for dissection. */
170   init_dissection();
171
172   /* We're about to start reading the file. */
173   cf->state = FILE_READ_IN_PROGRESS;
174
175   cf->wth = wth;
176   cf->filed = fd;
177   cf->f_len = cf_stat.st_size;
178
179   /* Set the file name because we need it to set the follow stream filter.
180      XXX - is that still true?  We need it for other reasons, though,
181      in any case. */
182   cf->filename = g_strdup(fname);
183
184   /* Indicate whether it's a permanent or temporary file. */
185   cf->is_tempfile = is_tempfile;
186
187   /* If it's a temporary capture buffer file, mark it as not saved. */
188   cf->user_saved = !is_tempfile;
189
190   cf->cd_t      = wtap_file_type(cf->wth);
191   cf->count     = 0;
192   cf->displayed_count = 0;
193   cf->marked_count = 0;
194   cf->drops_known = FALSE;
195   cf->drops     = 0;
196   cf->esec      = 0;
197   cf->eusec     = 0;
198   cf->snap      = wtap_snapshot_length(cf->wth);
199   if (cf->snap == 0) {
200     /* Snapshot length not known. */
201     cf->has_snap = FALSE;
202     cf->snap = WTAP_MAX_PACKET_SIZE;
203   } else
204     cf->has_snap = TRUE;
205   firstsec = 0, firstusec = 0;
206   prevsec = 0, prevusec = 0;
207
208   cf->plist_chunk = g_mem_chunk_new("frame_data_chunk",
209         sizeof(frame_data),
210         FRAME_DATA_CHUNK_SIZE * sizeof(frame_data),
211         G_ALLOC_AND_FREE);
212   g_assert(cf->plist_chunk);
213
214   return (0);
215
216 fail:
217   cf_open_failure_alert_box(fname, err, err_info, FALSE, 0);
218   return (err);
219 }
220
221 /* Reset everything to a pristine state */
222 void
223 cf_close(capture_file *cf)
224 {
225   /* Die if we're in the middle of reading a file. */
226   g_assert(cf->state != FILE_READ_IN_PROGRESS);
227
228   /* Destroy all windows, which refer to the
229      capture file we're closing. */
230   destroy_cfile_wins();
231
232   if (cf->wth) {
233     wtap_close(cf->wth);
234     cf->wth = NULL;
235   }
236   /* We have no file open... */
237   if (cf->filename != NULL) {
238     /* If it's a temporary file, remove it. */
239     if (cf->is_tempfile)
240       unlink(cf->filename);
241     g_free(cf->filename);
242     cf->filename = NULL;
243   }
244   /* ...which means we have nothing to save. */
245   cf->user_saved = FALSE;
246
247   if (cf->plist_chunk != NULL) {
248     g_mem_chunk_destroy(cf->plist_chunk);
249     cf->plist_chunk = NULL;
250   }
251   if (cf->rfcode != NULL) {
252     dfilter_free(cf->rfcode);
253     cf->rfcode = NULL;
254   }
255   cf->plist = NULL;
256   cf->plist_end = NULL;
257   unselect_packet(cf);  /* nothing to select */
258   cf->first_displayed = NULL;
259   cf->last_displayed = NULL;
260
261   /* No frame selected, no field in that frame selected. */
262   cf->current_frame = NULL;
263   cf->finfo_selected = NULL;
264
265   /* Clear the packet list. */
266   packet_list_freeze();
267   packet_list_clear();
268   packet_list_thaw();
269
270   cf->f_len = 0;
271   cf->count = 0;
272   cf->esec  = 0;
273   cf->eusec = 0;
274
275   /* Clear any file-related status bar messages.
276      XXX - should be "clear *ALL* file-related status bar messages;
277      will there ever be more than one on the stack? */
278   statusbar_pop_file_msg();
279
280   /* Restore the standard title bar message. */
281   set_main_window_name("The Ethereal Network Analyzer");
282
283   /* Disable all menu items that make sense only if you have a capture. */
284   set_menus_for_capture_file(FALSE);
285   set_menus_for_unsaved_capture_file(FALSE);
286   set_menus_for_captured_packets(FALSE);
287   set_menus_for_selected_packet(cf);
288   set_menus_for_capture_in_progress(FALSE);
289   set_menus_for_selected_tree_row(cf);
290
291   /* We have no file open. */
292   cf->state = FILE_CLOSED;
293 }
294
295 /* Set the file name in the status line, in the name for the main window,
296    and in the name for the main window's icon. */
297 static void
298 set_display_filename(capture_file *cf)
299 {
300   gchar  *name_ptr;
301   size_t  msg_len;
302   static const gchar done_fmt_nodrops[] = " File: %s %s %02u:%02u:%02u";
303   static const gchar done_fmt_drops[] = " File: %s %s %02u:%02u:%02u Drops: %u";
304   gchar  *done_msg;
305   gchar  *win_name_fmt = "%s - Ethereal";
306   gchar  *win_name;
307   gchar  *size_str;
308
309   name_ptr = cf_get_display_name(cf);
310         
311   if (!cf->is_tempfile) {
312     /* Add this filename to the list of recent files in the "Recent Files" submenu */
313     add_menu_recent_capture_file(cf->filename);
314   }
315
316   if (cf->f_len/1024/1024 > 10) {
317     size_str = g_strdup_printf("%ld MB", cf->f_len/1024/1024);
318   } else if (cf->f_len/1024 > 10) {
319     size_str = g_strdup_printf("%ld KB", cf->f_len/1024);
320   } else {
321     size_str = g_strdup_printf("%ld bytes", cf->f_len);
322   }
323
324   if (cf->drops_known) {
325     done_msg = g_strdup_printf(done_fmt_drops, name_ptr, size_str, 
326         cf->esec/3600, cf->esec%3600/60, cf->esec%60, cf->drops);
327   } else {
328     done_msg = g_strdup_printf(done_fmt_nodrops, name_ptr, size_str,
329         cf->esec/3600, cf->esec%3600/60, cf->esec%60);
330   }
331   statusbar_push_file_msg(done_msg);
332   g_free(done_msg);
333
334   msg_len = strlen(name_ptr) + strlen(win_name_fmt) + 1;
335   win_name = g_malloc(msg_len);
336   snprintf(win_name, msg_len, win_name_fmt, name_ptr);
337   set_main_window_name(win_name);
338   g_free(win_name);
339 }
340
341 read_status_t
342 cf_read(capture_file *cf)
343 {
344   int        err;
345   gchar      *err_info;
346   gchar      *name_ptr, *load_msg, *load_fmt = "%s";
347   char       *errmsg;
348   char        errmsg_errno[1024+1];
349   gchar       err_str[2048+1];
350   long        data_offset;
351   progdlg_t  *progbar = NULL;
352   gboolean    stop_flag;
353   /*
354    * XXX - should be "off_t", but Wiretap would need more work to handle
355    * the full size of "off_t" on platforms where it's more than a "long"
356    * as well.
357    */
358   long        file_pos;
359   float       prog_val;
360   int         fd;
361   struct stat cf_stat;
362   GTimeVal    start_time;
363   gchar       status_str[100];
364   int         progbar_nextstep;
365   int         progbar_quantum;
366
367   cum_bytes=0;
368   reset_tap_listeners();
369   tap_dfilter_dlg_update();
370   name_ptr = get_basename(cf->filename);
371
372   load_msg = g_strdup_printf(" Loading: %s", name_ptr);
373   statusbar_push_file_msg(load_msg);
374   g_free(load_msg);
375
376   load_msg = g_strdup_printf(load_fmt, name_ptr);
377
378   /* Update the progress bar when it gets to this value. */
379   progbar_nextstep = 0;
380   /* When we reach the value that triggers a progress bar update,
381      bump that value by this amount. */
382   progbar_quantum = cf->f_len/N_PROGBAR_UPDATES;
383
384 #ifndef O_BINARY
385 #define O_BINARY        0
386 #endif
387
388   packet_list_freeze();
389
390   stop_flag = FALSE;
391   g_get_current_time(&start_time);
392
393   while ((wtap_read(cf->wth, &err, &err_info, &data_offset))) {
394     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
395        when we update it, we have to run the GTK+ main loop to get it
396        to repaint what's pending, and doing so may involve an "ioctl()"
397        to see if there's any pending input from an X server, and doing
398        that for every packet can be costly, especially on a big file. */
399     if (data_offset >= progbar_nextstep) {
400         file_pos = lseek(cf->filed, 0, SEEK_CUR);
401         prog_val = (gfloat) file_pos / (gfloat) cf->f_len;
402         if (prog_val > 1.0) {
403           /* The file probably grew while we were reading it.
404              Update "cf->f_len", and try again. */
405           fd = wtap_fd(cf->wth);
406           if (fstat(fd, &cf_stat) >= 0) {
407             cf->f_len = cf_stat.st_size;
408             prog_val = (gfloat) file_pos / (gfloat) cf->f_len;
409           }
410           /* If it's still > 1, either the "fstat()" failed (in which
411              case there's not much we can do about it), or the file
412              *shrank* (in which case there's not much we can do about
413              it); just clip the progress value at 1.0. */
414           if (prog_val > 1.0)
415             prog_val = 1.0;
416         }
417         if (progbar == NULL) {
418           /* Create the progress bar if necessary */
419           progbar = delayed_create_progress_dlg("Loading", load_msg,
420             &stop_flag, &start_time, prog_val);
421           if (progbar != NULL)
422             g_free(load_msg);
423         }
424         if (progbar != NULL) {
425           g_snprintf(status_str, sizeof(status_str),
426                      "%luKB of %luKB", file_pos / 1024, cf->f_len / 1024);
427           update_progress_dlg(progbar, prog_val, status_str);
428         }
429         progbar_nextstep += progbar_quantum;
430     }
431
432     if (stop_flag) {
433       /* Well, the user decided to abort the read.  Destroy the progress
434          bar, close the capture file, and return READ_ABORTED so our caller
435          can do whatever is appropriate when that happens. */
436       destroy_progress_dlg(progbar);
437       cf->state = FILE_READ_ABORTED;    /* so that we're allowed to close it */
438       packet_list_thaw();               /* undo our freeze */
439       cf_close(cf);
440       return (READ_ABORTED);
441     }
442     read_packet(cf, data_offset);
443   }
444
445   /* We're done reading the file; destroy the progress bar if it was created. */
446   if (progbar == NULL)
447     g_free(load_msg);
448   else
449     destroy_progress_dlg(progbar);
450
451   /* We're done reading sequentially through the file. */
452   cf->state = FILE_READ_DONE;
453
454   /* Close the sequential I/O side, to free up memory it requires. */
455   wtap_sequential_close(cf->wth);
456
457   /* Allow the protocol dissectors to free up memory that they
458    * don't need after the sequential run-through of the packets. */
459   postseq_cleanup_all_protocols();
460
461   /* Set the file encapsulation type now; we don't know what it is until
462      we've looked at all the packets, as we don't know until then whether
463      there's more than one type (and thus whether it's
464      WTAP_ENCAP_PER_PACKET). */
465   cf->lnk_t = wtap_file_encap(cf->wth);
466
467   cf->current_frame = cf->first_displayed;
468   packet_list_thaw();
469
470   statusbar_pop_file_msg();
471   set_display_filename(cf);
472
473   /* Enable menu items that make sense if you have a capture file you've
474      finished reading. */
475   set_menus_for_capture_file(TRUE);
476   set_menus_for_unsaved_capture_file(!cf->user_saved);
477
478   /* Enable menu items that make sense if you have some captured packets. */
479   set_menus_for_captured_packets(TRUE);
480
481   /* If we have any displayed packets to select, select the first of those
482      packets by making the first row the selected row. */
483   if (cf->first_displayed != NULL)
484     packet_list_select_row(0);
485
486   if (err != 0) {
487     /* Put up a message box noting that the read failed somewhere along
488        the line.  Don't throw out the stuff we managed to read, though,
489        if any. */
490     switch (err) {
491
492     case WTAP_ERR_UNSUPPORTED_ENCAP:
493       errmsg = "The capture file is for a network type that Ethereal doesn't support.";
494       break;
495
496     case WTAP_ERR_CANT_READ:
497       errmsg = "An attempt to read from the file failed for"
498                " some unknown reason.";
499       break;
500
501     case WTAP_ERR_SHORT_READ:
502       errmsg = "The capture file appears to have been cut short"
503                " in the middle of a packet.";
504       break;
505
506     case WTAP_ERR_BAD_RECORD:
507       snprintf(errmsg_errno, sizeof(errmsg_errno),
508                "The capture file appears to be damaged or corrupt.\n(%s)",
509                err_info);
510       errmsg = errmsg_errno;
511       break;
512
513     default:
514       snprintf(errmsg_errno, sizeof(errmsg_errno),
515                "An error occurred while reading the"
516                " capture file: %s.", wtap_strerror(err));
517       errmsg = errmsg_errno;
518       break;
519     }
520     snprintf(err_str, sizeof err_str, errmsg);
521     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, err_str);
522     return (READ_ERROR);
523   } else
524     return (READ_SUCCESS);
525 }
526
527 #ifdef HAVE_LIBPCAP
528 int
529 cf_start_tail(char *fname, gboolean is_tempfile, capture_file *cf)
530 {
531   int     err;
532
533   err = cf_open(fname, is_tempfile, cf);
534   if (err == 0) {
535     /* Disable menu items that make no sense if you're currently running
536        a capture. */
537     set_menus_for_capture_in_progress(TRUE);
538
539     /* Enable menu items that make sense if you have some captured
540        packets (yes, I know, we don't have any *yet*). */
541     set_menus_for_captured_packets(TRUE);
542
543     statusbar_push_file_msg(" <live capture in progress>");
544   }
545   return err;
546 }
547
548 read_status_t
549 cf_continue_tail(capture_file *cf, int to_read, int *err)
550 {
551   long data_offset = 0;
552   gchar *err_info;
553
554   *err = 0;
555
556   packet_list_freeze();
557
558   while (to_read != 0 && (wtap_read(cf->wth, err, &err_info, &data_offset))) {
559     if (cf->state == FILE_READ_ABORTED) {
560       /* Well, the user decided to exit Ethereal.  Break out of the
561          loop, and let the code below (which is called even if there
562          aren't any packets left to read) exit. */
563       break;
564     }
565     read_packet(cf, data_offset);
566     to_read--;
567   }
568
569   packet_list_thaw();
570
571   /* XXX - this cheats and looks inside the packet list to find the final
572      row number. */
573   if (auto_scroll_live && cf->plist_end != NULL)
574     packet_list_moveto_end();
575
576   if (cf->state == FILE_READ_ABORTED) {
577     /* Well, the user decided to exit Ethereal.  Return READ_ABORTED
578        so that our caller can kill off the capture child process;
579        this will cause an EOF on the pipe from the child, so
580        "cf_finish_tail()" will be called, and it will clean up
581        and exit. */
582     return READ_ABORTED;
583   } else if (*err != 0) {
584     /* We got an error reading the capture file.
585        XXX - pop up a dialog box? */
586     return (READ_ERROR);
587   } else
588     return (READ_SUCCESS);
589 }
590
591 read_status_t
592 cf_finish_tail(capture_file *cf, int *err)
593 {
594   gchar *err_info;
595   long data_offset;
596   int         fd;
597   struct stat cf_stat;
598
599   packet_list_freeze();
600
601   while ((wtap_read(cf->wth, err, &err_info, &data_offset))) {
602     if (cf->state == FILE_READ_ABORTED) {
603       /* Well, the user decided to abort the read.  Break out of the
604          loop, and let the code below (which is called even if there
605          aren't any packets left to read) exit. */
606       break;
607     }
608     read_packet(cf, data_offset);
609   }
610
611   if (cf->state == FILE_READ_ABORTED) {
612     /* Well, the user decided to abort the read.  We're only called
613        when the child capture process closes the pipe to us (meaning
614        it's probably exited), so we can just close the capture
615        file; we return READ_ABORTED so our caller can do whatever
616        is appropriate when that happens. */
617     cf_close(cf);
618     return READ_ABORTED;
619   }
620
621   packet_list_thaw();
622   if (auto_scroll_live && cf->plist_end != NULL)
623     /* XXX - this cheats and looks inside the packet list to find the final
624        row number. */
625     packet_list_moveto_end();
626
627   /* We're done reading sequentially through the file. */
628   cf->state = FILE_READ_DONE;
629
630   /* we have to update the f_len field */
631   /* Find the size of the file. */
632   fd = wtap_fd(cf->wth);
633   if (fstat(fd, &cf_stat) >= 0) {
634       cf->f_len = cf_stat.st_size;
635   }
636
637   /* We're done reading sequentially through the file; close the
638      sequential I/O side, to free up memory it requires. */
639   wtap_sequential_close(cf->wth);
640
641   /* Allow the protocol dissectors to free up memory that they
642    * don't need after the sequential run-through of the packets. */
643   postseq_cleanup_all_protocols();
644
645   /* Set the file encapsulation type now; we don't know what it is until
646      we've looked at all the packets, as we don't know until then whether
647      there's more than one type (and thus whether it's
648      WTAP_ENCAP_PER_PACKET). */
649   cf->lnk_t = wtap_file_encap(cf->wth);
650
651   /* Pop the "<live capture in progress>" message off the status bar. */
652   statusbar_pop_file_msg();
653
654   set_display_filename(cf);
655
656   /* Enable menu items that make sense if you're not currently running
657      a capture. */
658   set_menus_for_capture_in_progress(FALSE);
659
660   /* Enable menu items that make sense if you have a capture file
661      you've finished reading. */
662   set_menus_for_capture_file(TRUE);
663   set_menus_for_unsaved_capture_file(!cf->user_saved);
664
665   if (*err != 0) {
666     /* We got an error reading the capture file.
667        XXX - pop up a dialog box? */
668     return (READ_ERROR);
669   } else {
670     return (READ_SUCCESS);
671   }
672 }
673 #endif /* HAVE_LIBPCAP */
674
675 gchar *
676 cf_get_display_name(capture_file *cf)
677 {
678   gchar *displayname;
679
680   /* Return a name to use in displays */
681   if (!cf->is_tempfile) {
682     /* Get the last component of the file name, and use that. */
683     if (cf->filename){
684       displayname = get_basename(cf->filename);
685       
686       /* Add this filename to the list of recent files in the "Recent Files" submenu */
687       add_menu_recent_capture_file(cf->filename);
688     } else {
689       displayname="(No file)";
690     }
691   } else {
692     /* The file we read is a temporary file from a live capture;
693        we don't mention its name. */
694     displayname = "(Untitled)";
695   }
696   return displayname;
697 }
698
699 typedef struct {
700   color_filter_t *colorf;
701   epan_dissect_t *edt;
702 } apply_color_filter_args;
703
704 /*
705  * If no color filter has been applied, apply this one.
706  * (The "if no color filter has been applied" is to handle the case where
707  * more than one color filter matches the packet.)
708  */
709 static void
710 apply_color_filter(gpointer filter_arg, gpointer argp)
711 {
712   color_filter_t *colorf = filter_arg;
713   apply_color_filter_args *args = argp;
714
715   if (colorf->c_colorfilter != NULL && args->colorf == NULL) {
716     if (dfilter_apply_edt(colorf->c_colorfilter, args->edt))
717       args->colorf = colorf;
718   }
719 }
720
721 static int
722 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
723         union wtap_pseudo_header *pseudo_header, const guchar *buf,
724         gboolean refilter)
725 {
726   apply_color_filter_args args;
727   gint          row;
728   gboolean      create_proto_tree = FALSE;
729   epan_dissect_t *edt;
730
731   /* just add some value here until we know if it is being displayed or not */
732   fdata->cum_bytes  = cum_bytes + fdata->pkt_len;
733
734   /* We don't yet have a color filter to apply. */
735   args.colorf = NULL;
736
737   /* If we don't have the time stamp of the first packet in the
738      capture, it's because this is the first packet.  Save the time
739      stamp of this packet as the time stamp of the first packet. */
740   if (!firstsec && !firstusec) {
741     firstsec  = fdata->abs_secs;
742     firstusec = fdata->abs_usecs;
743   }
744   /* if this frames is marked as a reference time frame, reset
745      firstsec and firstusec to this frame */
746   if(fdata->flags.ref_time){
747     firstsec  = fdata->abs_secs;
748     firstusec = fdata->abs_usecs;
749   }
750
751   /* If we don't have the time stamp of the previous displayed packet,
752      it's because this is the first displayed packet.  Save the time
753      stamp of this packet as the time stamp of the previous displayed
754      packet. */
755   if (!prevsec && !prevusec) {
756     prevsec  = fdata->abs_secs;
757     prevusec = fdata->abs_usecs;
758   }
759
760   /* Get the time elapsed between the first packet and this packet. */
761   compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
762      fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
763
764   /* If it's greater than the current elapsed time, set the elapsed time
765      to it (we check for "greater than" so as not to be confused by
766      time moving backwards). */
767   if ((gint32)cf->esec < fdata->rel_secs
768   || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
769     cf->esec = fdata->rel_secs;
770     cf->eusec = fdata->rel_usecs;
771   }
772
773   /* Get the time elapsed between the previous displayed packet and
774      this packet. */
775   compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
776         fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
777
778   /* If either
779
780         we have a display filter and are re-applying it;
781
782         we have a list of color filters;
783
784         we have tap listeners;
785
786      allocate a protocol tree root node, so that we'll construct
787      a protocol tree against which a filter expression can be
788      evaluated. */
789   if ((cf->dfcode != NULL && refilter) || filter_list != NULL
790         || num_tap_filters != 0)
791           create_proto_tree = TRUE;
792
793   /* Dissect the frame. */
794   edt = epan_dissect_new(create_proto_tree, FALSE);
795
796   if (cf->dfcode != NULL && refilter) {
797       epan_dissect_prime_dfilter(edt, cf->dfcode);
798   }
799   if (filter_list) {
800       filter_list_prime_edt(edt);
801   }
802   tap_queue_init(edt);
803   epan_dissect_run(edt, pseudo_header, buf, fdata, &cf->cinfo);
804   tap_push_tapped_queue(edt);
805
806   /* If we have a display filter, apply it if we're refiltering, otherwise
807      leave the "passed_dfilter" flag alone.
808
809      If we don't have a display filter, set "passed_dfilter" to 1. */
810   if (cf->dfcode != NULL) {
811     if (refilter) {
812       if (cf->dfcode != NULL)
813         fdata->flags.passed_dfilter = dfilter_apply_edt(cf->dfcode, edt) ? 1 : 0;
814       else
815         fdata->flags.passed_dfilter = 1;
816     }
817   } else
818     fdata->flags.passed_dfilter = 1;
819
820   /* If we have color filters, and the frame is to be displayed, apply
821      the color filters. */
822   if (fdata->flags.passed_dfilter) {
823     if (filter_list != NULL) {
824       args.edt = edt;
825       g_slist_foreach(filter_list, apply_color_filter, &args);
826     }
827   }
828
829
830   if( (fdata->flags.passed_dfilter) 
831    || (edt->pi.fd->flags.ref_time) ){
832     /* This frame either passed the display filter list or is marked as
833        a time reference frame.  All time reference frames are displayed
834        even if they dont pass the display filter */
835     /* if this was a TIME REF frame we should reset the cul bytes field */
836     if(edt->pi.fd->flags.ref_time){
837       cum_bytes = fdata->pkt_len;
838       fdata->cum_bytes  = cum_bytes;
839     }
840
841     /* increase cum_bytes with this packets length */
842     cum_bytes += fdata->pkt_len;
843
844     epan_dissect_fill_in_columns(edt);
845
846     /* If we haven't yet seen the first frame, this is it.
847
848        XXX - we must do this before we add the row to the display,
849        as, if the display's GtkCList's selection mode is
850        GTK_SELECTION_BROWSE, when the first entry is added to it,
851        "select_packet()" will be called, and it will fetch the row
852        data for the 0th row, and will get a null pointer rather than
853        "fdata", as "gtk_clist_append()" won't yet have returned and
854        thus "gtk_clist_set_row_data()" won't yet have been called.
855
856        We thus need to leave behind bread crumbs so that
857        "select_packet()" can find this frame.  See the comment
858        in "select_packet()". */
859     if (cf->first_displayed == NULL)
860       cf->first_displayed = fdata;
861
862     /* This is the last frame we've seen so far. */
863     cf->last_displayed = fdata;
864
865     row = packet_list_append(cf->cinfo.col_data, fdata);
866
867     /* If the packet matches a color filter,
868      * store matching color_filter_t object in frame data. */
869     if (filter_list != NULL && (args.colorf != NULL)) {
870       /* add the matching colorfilter to the frame data */
871       fdata->color_filter = args.colorf;
872       /* If packet is marked, use colors from preferences */
873       if (fdata->flags.marked) {
874           packet_list_set_colors(row, &prefs.gui_marked_fg, &prefs.gui_marked_bg);
875       } else /* if (filter_list != NULL && (args.colorf != NULL)) */ {
876           packet_list_set_colors(row, &(args.colorf->fg_color),
877               &(args.colorf->bg_color));
878       }
879     } else {
880       /* No color filter match */
881       fdata->color_filter = NULL;
882       if (fdata->flags.marked) {
883           packet_list_set_colors(row, &prefs.gui_marked_fg, &prefs.gui_marked_bg);
884       }
885     }
886
887     /* Set the time of the previous displayed frame to the time of this
888        frame. */
889     prevsec = fdata->abs_secs;
890     prevusec = fdata->abs_usecs;
891
892     cf->displayed_count++;
893   } else {
894     /* This frame didn't pass the display filter, so it's not being added
895        to the clist, and thus has no row. */
896     row = -1;
897   }
898   epan_dissect_free(edt);
899   return row;
900 }
901
902 static void
903 read_packet(capture_file *cf, long offset)
904 {
905   const struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
906   union wtap_pseudo_header *pseudo_header = wtap_pseudoheader(cf->wth);
907   const guchar *buf = wtap_buf_ptr(cf->wth);
908   frame_data   *fdata;
909   int           passed;
910   frame_data   *plist_end;
911   epan_dissect_t *edt;
912
913   /* Allocate the next list entry, and add it to the list. */
914   fdata = g_mem_chunk_alloc(cf->plist_chunk);
915
916   fdata->next = NULL;
917   fdata->prev = NULL;
918   fdata->pfd  = NULL;
919   fdata->pkt_len  = phdr->len;
920   fdata->cap_len  = phdr->caplen;
921   fdata->file_off = offset;
922   fdata->lnk_t = phdr->pkt_encap;
923   fdata->abs_secs  = phdr->ts.tv_sec;
924   fdata->abs_usecs = phdr->ts.tv_usec;
925   fdata->flags.encoding = CHAR_ASCII;
926   fdata->flags.visited = 0;
927   fdata->flags.marked = 0;
928   fdata->flags.ref_time = 0;
929
930   passed = TRUE;
931   if (cf->rfcode) {
932     edt = epan_dissect_new(TRUE, FALSE);
933     epan_dissect_prime_dfilter(edt, cf->rfcode);
934     epan_dissect_run(edt, pseudo_header, buf, fdata, NULL);
935     passed = dfilter_apply_edt(cf->rfcode, edt);
936     epan_dissect_free(edt);
937   }
938   if (passed) {
939     plist_end = cf->plist_end;
940     fdata->prev = plist_end;
941     if (plist_end != NULL)
942       plist_end->next = fdata;
943     else
944       cf->plist = fdata;
945     cf->plist_end = fdata;
946
947     cf->count++;
948     fdata->num = cf->count;
949     add_packet_to_packet_list(fdata, cf, pseudo_header, buf, TRUE);
950   } else {
951     /* XXX - if we didn't have read filters, or if we could avoid
952        allocating the "frame_data" structure until we knew whether
953        the frame passed the read filter, we could use a G_ALLOC_ONLY
954        memory chunk...
955
956        ...but, at least in one test I did, where I just made the chunk
957        a G_ALLOC_ONLY chunk and read in a huge capture file, it didn't
958        seem to save a noticeable amount of time or space. */
959     g_mem_chunk_free(cf->plist_chunk, fdata);
960   }
961 }
962
963 int
964 filter_packets(capture_file *cf, gchar *dftext)
965 {
966   dfilter_t *dfcode;
967   char      *filter_new = dftext ? dftext : "";
968   char      *filter_old = cf->dfilter ? cf->dfilter : "";
969
970
971   /* if new filter equals old one, do nothing */
972   if (strcmp(filter_new, filter_old) == 0) {
973     return 1;
974   }
975
976   if (dftext == NULL) {
977     /* The new filter is an empty filter (i.e., display all packets). */
978     dfcode = NULL;
979   } else {
980     /*
981      * We have a filter; make a copy of it (as we'll be saving it),
982      * and try to compile it.
983      */
984     dftext = g_strdup(dftext);
985     if (!dfilter_compile(dftext, &dfcode)) {
986       /* The attempt failed; report an error. */
987       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, 
988           "%s%s%s\n"
989           "\n"
990           "The display filter \"%s\" is not a valid display filter.\n"
991           "See the help for a description of the display filter syntax.",
992           simple_dialog_primary_start(), dfilter_error_msg,
993           simple_dialog_primary_end(), dftext);
994       g_free(dftext);
995       return 0;
996     }
997
998     /* Was it empty? */
999     if (dfcode == NULL) {
1000       /* Yes - free the filter text, and set it to null. */
1001       g_free(dftext);
1002       dftext = NULL;
1003     }
1004   }
1005
1006   /* We have a valid filter.  Replace the current filter. */
1007   if (cf->dfilter != NULL)
1008     g_free(cf->dfilter);
1009   cf->dfilter = dftext;
1010   if (cf->dfcode != NULL)
1011     dfilter_free(cf->dfcode);
1012   cf->dfcode = dfcode;
1013
1014   /* Now rescan the packet list, applying the new filter, but not
1015      throwing away information constructed on a previous pass. */
1016   if (dftext == NULL) {
1017     rescan_packets(cf, "Resetting", "Filter", TRUE, FALSE);
1018   } else {
1019     rescan_packets(cf, "Filtering", dftext, TRUE, FALSE);
1020   }
1021   return 1;
1022 }
1023
1024 void
1025 colorize_packets(capture_file *cf)
1026 {
1027   rescan_packets(cf, "Colorizing", "all packets", FALSE, FALSE);
1028 }
1029
1030 void
1031 reftime_packets(capture_file *cf)
1032 {
1033   rescan_packets(cf, "Updating Reftime", "all packets", FALSE, FALSE);
1034 }
1035
1036 void
1037 redissect_packets(capture_file *cf)
1038 {
1039   rescan_packets(cf, "Reprocessing", "all packets", TRUE, TRUE);
1040 }
1041
1042 /* Rescan the list of packets, reconstructing the CList.
1043
1044    "action" describes why we're doing this; it's used in the progress
1045    dialog box.
1046
1047    "action_item" describes what we're doing; it's used in the progress
1048    dialog box.
1049
1050    "refilter" is TRUE if we need to re-evaluate the filter expression.
1051
1052    "redissect" is TRUE if we need to make the dissectors reconstruct
1053    any state information they have (because a preference that affects
1054    some dissector has changed, meaning some dissector might construct
1055    its state differently from the way it was constructed the last time). */
1056 static void
1057 rescan_packets(capture_file *cf, const char *action, const char *action_item,
1058                 gboolean refilter, gboolean redissect)
1059 {
1060   frame_data *fdata;
1061   progdlg_t  *progbar = NULL;
1062   gboolean    stop_flag;
1063   int         count;
1064   int         err;
1065   gchar      *err_info;
1066   frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1067   int         selected_row, prev_row, preceding_row, following_row;
1068   gboolean    selected_frame_seen;
1069   int         row;
1070   float       prog_val;
1071   GTimeVal    start_time;
1072   gchar       status_str[100];
1073   int         progbar_nextstep;
1074   int         progbar_quantum;
1075
1076   cum_bytes=0;
1077   reset_tap_listeners();
1078   /* Which frame, if any, is the currently selected frame?
1079      XXX - should the selected frame or the focus frame be the "current"
1080      frame, that frame being the one from which "Find Frame" searches
1081      start? */
1082   selected_frame = cf->current_frame;
1083
1084   /* We don't yet know what row that frame will be on, if any, after we
1085      rebuild the clist, however. */
1086   selected_row = -1;
1087
1088   if (redissect) {
1089     /* We need to re-initialize all the state information that protocols
1090        keep, because some preference that controls a dissector has changed,
1091        which might cause the state information to be constructed differently
1092        by that dissector. */
1093
1094     /* Initialize all data structures used for dissection. */
1095     init_dissection();
1096   }
1097
1098   /* Freeze the packet list while we redo it, so we don't get any
1099      screen updates while it happens. */
1100   packet_list_freeze();
1101
1102   /* Clear it out. */
1103   packet_list_clear();
1104
1105   /* We don't yet know which will be the first and last frames displayed. */
1106   cf->first_displayed = NULL;
1107   cf->last_displayed = NULL;
1108
1109   /* We currently don't display any packets */
1110   cf->displayed_count = 0;
1111
1112   /* Iterate through the list of frames.  Call a routine for each frame
1113      to check whether it should be displayed and, if so, add it to
1114      the display list. */
1115   firstsec = 0;
1116   firstusec = 0;
1117   prevsec = 0;
1118   prevusec = 0;
1119
1120   /* Update the progress bar when it gets to this value. */
1121   progbar_nextstep = 0;
1122   /* When we reach the value that triggers a progress bar update,
1123      bump that value by this amount. */
1124   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1125   /* Count of packets at which we've looked. */
1126   count = 0;
1127
1128   stop_flag = FALSE;
1129   g_get_current_time(&start_time);
1130
1131   row = -1;             /* no previous row yet */
1132   prev_row = -1;
1133   prev_frame = NULL;
1134
1135   preceding_row = -1;
1136   preceding_frame = NULL;
1137   following_row = -1;
1138   following_frame = NULL;
1139
1140   selected_frame_seen = FALSE;
1141
1142   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1143     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1144        when we update it, we have to run the GTK+ main loop to get it
1145        to repaint what's pending, and doing so may involve an "ioctl()"
1146        to see if there's any pending input from an X server, and doing
1147        that for every packet can be costly, especially on a big file. */
1148     if (count >= progbar_nextstep) {
1149       /* let's not divide by zero. I should never be started
1150        * with count == 0, so let's assert that
1151        */
1152       g_assert(cf->count > 0);
1153       prog_val = (gfloat) count / cf->count;
1154
1155       if (progbar == NULL)
1156         /* Create the progress bar if necessary */
1157         progbar = delayed_create_progress_dlg(action, action_item, &stop_flag,
1158           &start_time, prog_val);
1159
1160       if (progbar != NULL) {
1161         g_snprintf(status_str, sizeof(status_str),
1162                   "%4u of %u frames", count, cf->count);
1163         update_progress_dlg(progbar, prog_val, status_str);
1164       }
1165
1166       progbar_nextstep += progbar_quantum;
1167     }
1168
1169     if (stop_flag) {
1170       /* Well, the user decided to abort the filtering.  Just stop.
1171
1172          XXX - go back to the previous filter?  Users probably just
1173          want not to wait for a filtering operation to finish;
1174          unless we cancel by having no filter, reverting to the
1175          previous filter will probably be even more expensive than
1176          continuing the filtering, as it involves going back to the
1177          beginning and filtering, and even with no filter we currently
1178          have to re-generate the entire clist, which is also expensive.
1179
1180          I'm not sure what Network Monitor does, but it doesn't appear
1181          to give you an unfiltered display if you cancel. */
1182       break;
1183     }
1184
1185     count++;
1186
1187     if (redissect) {
1188       /* Since all state for the frame was destroyed, mark the frame
1189        * as not visited, free the GSList referring to the state
1190        * data (the per-frame data itself was freed by
1191        * "init_dissection()"), and null out the GSList pointer. */
1192       fdata->flags.visited = 0;
1193       if (fdata->pfd) {
1194         g_slist_free(fdata->pfd);
1195         fdata->pfd = NULL;
1196       }
1197     }
1198
1199     if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1200         cf->pd, fdata->cap_len, &err, &err_info)) {
1201         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
1202                       cf_read_error_message(err, err_info), cf->filename);
1203         break;
1204     }
1205
1206     /* If the previous frame is displayed, and we haven't yet seen the
1207        selected frame, remember that frame - it's the closest one we've
1208        yet seen before the selected frame. */
1209     if (prev_row != -1 && !selected_frame_seen) {
1210       preceding_row = prev_row;
1211       preceding_frame = prev_frame;
1212     }
1213     row = add_packet_to_packet_list(fdata, cf, &cf->pseudo_header, cf->pd,
1214                                         refilter);
1215
1216     /* If this frame is displayed, and this is the first frame we've
1217        seen displayed after the selected frame, remember this frame -
1218        it's the closest one we've yet seen at or after the selected
1219        frame. */
1220     if (row != -1 && selected_frame_seen && following_row == -1) {
1221       following_row = row;
1222       following_frame = fdata;
1223     }
1224     if (fdata == selected_frame) {
1225       selected_row = row;
1226       selected_frame_seen = TRUE;
1227     }
1228
1229     /* Remember this row/frame - it'll be the previous row/frame
1230        on the next pass through the loop. */
1231     prev_row = row;
1232     prev_frame = fdata;
1233   }
1234
1235   if (redissect) {
1236     /* Clear out what remains of the visited flags and per-frame data
1237        pointers.
1238
1239        XXX - that may cause various forms of bogosity when dissecting
1240        these frames, as they won't have been seen by this sequential
1241        pass, but the only alternative I see is to keep scanning them
1242        even though the user requested that the scan stop, and that
1243        would leave the user stuck with an Ethereal grinding on
1244        until it finishes.  Should we just stick them with that? */
1245     for (; fdata != NULL; fdata = fdata->next) {
1246       fdata->flags.visited = 0;
1247       if (fdata->pfd) {
1248         g_slist_free(fdata->pfd);
1249         fdata->pfd = NULL;
1250       }
1251     }
1252   }
1253
1254   /* We're done filtering the packets; destroy the progress bar if it
1255      was created. */
1256   if (progbar != NULL)
1257     destroy_progress_dlg(progbar);
1258
1259   /* Unfreeze the packet list. */
1260   packet_list_thaw();
1261
1262   if (selected_row == -1) {
1263     /* The selected frame didn't pass the filter. */
1264     if (selected_frame == NULL) {
1265       /* That's because there *was* no selected frame.  Make the first
1266          displayed frame the current frame. */
1267       selected_row = 0;
1268     } else {
1269       /* Find the nearest displayed frame to the selected frame (whether
1270          it's before or after that frame) and make that the current frame.
1271          If the next and previous displayed frames are equidistant from the
1272          selected frame, choose the next one. */
1273       g_assert(following_frame == NULL ||
1274                following_frame->num >= selected_frame->num);
1275       g_assert(preceding_frame == NULL ||
1276                preceding_frame->num <= selected_frame->num);
1277       if (following_frame == NULL) {
1278         /* No frame after the selected frame passed the filter, so we
1279            have to select the last displayed frame before the selected
1280            frame. */
1281         selected_row = preceding_row;
1282       } else if (preceding_frame == NULL) {
1283         /* No frame before the selected frame passed the filter, so we
1284            have to select the first displayed frame after the selected
1285            frame. */
1286         selected_row = following_row;
1287       } else {
1288         /* Choose the closer of the last displayed frame before the
1289            selected frame and the first displayed frame after the
1290            selected frame; in case of a tie, choose the first displayed
1291            frame after the selected frame. */
1292         if (following_frame->num - selected_frame->num <=
1293             selected_frame->num - preceding_frame->num) {
1294           selected_row = following_row;
1295         } else {
1296           /* The previous frame is closer to the selected frame than the
1297              next frame. */
1298           selected_row = preceding_row;
1299         }
1300       }
1301     }
1302   }
1303
1304   if (selected_row == -1) {
1305     /* There are no frames displayed at all. */
1306     unselect_packet(cf);
1307   } else {
1308     /* Either the frame that was selected passed the filter, or we've
1309        found the nearest displayed frame to that frame.  Select it, make
1310        it the focus row, and make it visible. */
1311     packet_list_set_selected_row(selected_row);
1312   }
1313 }
1314
1315 typedef enum {
1316   PSP_FINISHED,
1317   PSP_STOPPED,
1318   PSP_FAILED
1319 } psp_return_t;
1320
1321 psp_return_t
1322 process_specified_packets(capture_file *cf, packet_range_t *range,
1323     const char *string1, const char *string2,
1324     gboolean (*callback)(capture_file *, frame_data *,
1325                          union wtap_pseudo_header *, const guint8 *, void *),
1326     void *callback_args)
1327 {
1328   frame_data *fdata;
1329   int         err;
1330   gchar      *err_info;
1331   union wtap_pseudo_header pseudo_header;
1332   guint8      pd[WTAP_MAX_PACKET_SIZE+1];
1333   psp_return_t ret = PSP_FINISHED;
1334
1335   progdlg_t  *progbar = NULL;
1336   int         progbar_count;
1337   float       progbar_val;
1338   gboolean    progbar_stop_flag;
1339   GTimeVal    progbar_start_time;
1340   gchar       progbar_status_str[100];
1341   int         progbar_nextstep;
1342   int         progbar_quantum;
1343   range_process_e process_this;
1344
1345   /* Update the progress bar when it gets to this value. */
1346   progbar_nextstep = 0;
1347   /* When we reach the value that triggers a progress bar update,
1348      bump that value by this amount. */
1349   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1350   /* Count of packets at which we've looked. */
1351   progbar_count = 0;
1352
1353   progbar_stop_flag = FALSE;
1354   g_get_current_time(&progbar_start_time);
1355
1356   packet_range_process_init(range);
1357
1358   /* Iterate through the list of packets, printing the packets that
1359      were selected by the current display filter.  */
1360   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1361     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1362        when we update it, we have to run the GTK+ main loop to get it
1363        to repaint what's pending, and doing so may involve an "ioctl()"
1364        to see if there's any pending input from an X server, and doing
1365        that for every packet can be costly, especially on a big file. */
1366     if (progbar_count >= progbar_nextstep) {
1367       /* let's not divide by zero. I should never be started
1368        * with count == 0, so let's assert that
1369        */
1370       g_assert(cf->count > 0);
1371       progbar_val = (gfloat) progbar_count / cf->count;
1372
1373       if (progbar == NULL)
1374         /* Create the progress bar if necessary */
1375         progbar = delayed_create_progress_dlg(string1, string2,
1376                                               &progbar_stop_flag,
1377                                               &progbar_start_time,
1378                                               progbar_val);
1379
1380       if (progbar != NULL) {
1381         g_snprintf(progbar_status_str, sizeof(progbar_status_str),
1382                    "%4u of %u packets", progbar_count, cf->count);
1383         update_progress_dlg(progbar, progbar_val, progbar_status_str);
1384       }
1385
1386       progbar_nextstep += progbar_quantum;
1387     }
1388
1389     if (progbar_stop_flag) {
1390       /* Well, the user decided to abort the operation.  Just stop,
1391          and arrange to return TRUE to our caller, so they know it
1392          was stopped explicitly. */
1393       ret = PSP_STOPPED;
1394       break;
1395     }
1396
1397     progbar_count++;
1398
1399     /* do we have to process this packet? */
1400     process_this = packet_range_process_packet(range, fdata);
1401     if (process_this == range_process_next) {
1402         /* this packet uninteresting, continue with next one */
1403         continue;
1404     } else if (process_this == range_processing_finished) {
1405         /* all interesting packets processed, stop the loop */
1406         break;
1407     }
1408
1409     /* Get the packet */
1410     if (!wtap_seek_read(cf->wth, fdata->file_off, &pseudo_header,
1411                         pd, fdata->cap_len, &err, &err_info)) {
1412       /* Attempt to get the packet failed. */
1413       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
1414                     cf_read_error_message(err, err_info), cf->filename);
1415       ret = PSP_FAILED;
1416       break;
1417     }
1418     if (!callback(cf, fdata, &pseudo_header, pd, callback_args)) {
1419       /* Callback failed.  We assume it reported the error appropriately. */
1420       ret = PSP_FAILED;
1421       break;
1422     }
1423   }
1424
1425   /* We're done printing the packets; destroy the progress bar if
1426      it was created. */
1427   if (progbar != NULL)
1428     destroy_progress_dlg(progbar);
1429
1430   return ret;
1431 }
1432
1433 static gboolean
1434 retap_packet(capture_file *cf _U_, frame_data *fdata,
1435              union wtap_pseudo_header *pseudo_header, const guint8 *pd,
1436              void *argsp _U_)
1437 {
1438   epan_dissect_t *edt;
1439
1440   /* If we have tap listeners, allocate a protocol tree root node, so that
1441      we'll construct a protocol tree against which a filter expression can
1442      be evaluated. */
1443   edt = epan_dissect_new(num_tap_filters != 0, FALSE);
1444   tap_queue_init(edt);
1445   epan_dissect_run(edt, pseudo_header, pd, fdata, NULL);
1446   tap_push_tapped_queue(edt);
1447   epan_dissect_free(edt);
1448
1449   return TRUE;
1450 }
1451
1452 int
1453 retap_packets(capture_file *cf)
1454 {
1455   packet_range_t range;
1456
1457   /* Reset the tap listeners. */
1458   reset_tap_listeners();
1459
1460   /* Iterate through the list of packets, dissecting all packets and
1461      re-running the taps. */
1462   packet_range_init(&range);
1463   packet_range_process_init(&range);
1464   switch (process_specified_packets(cf, &range, "Refiltering statistics on",
1465                                     "all packets", retap_packet,
1466                                     NULL)) {
1467   case PSP_FINISHED:
1468     /* Completed successfully. */
1469     break;
1470
1471   case PSP_STOPPED:
1472     /* Well, the user decided to abort the refiltering.
1473        Return FALSE so our caller knows they did that. */
1474     return FALSE;
1475
1476   case PSP_FAILED:
1477     /* Error while retapping. */
1478     return FALSE;
1479   }
1480
1481   return TRUE;
1482 }
1483
1484 typedef struct {
1485   print_args_t *print_args;
1486   FILE         *print_fh;
1487   gboolean      print_separator;
1488   char         *line_buf;
1489   int           line_buf_len;
1490   gint         *col_widths;
1491 } print_callback_args_t;
1492
1493 static gboolean
1494 print_packet(capture_file *cf, frame_data *fdata,
1495              union wtap_pseudo_header *pseudo_header, const guint8 *pd,
1496              void *argsp)
1497 {
1498   print_callback_args_t *args = argsp;
1499   epan_dissect_t *edt;
1500   int             i;
1501   char           *cp;
1502   int             line_len;
1503   int             column_len;
1504   int             cp_off;
1505
1506   if (args->print_args->print_summary) {
1507     /* Fill in the column information, but don't bother creating
1508        the logical protocol tree. */
1509     edt = epan_dissect_new(FALSE, FALSE);
1510     epan_dissect_run(edt, pseudo_header, pd, fdata, &cf->cinfo);
1511     epan_dissect_fill_in_columns(edt);
1512     cp = &args->line_buf[0];
1513     line_len = 0;
1514     for (i = 0; i < cf->cinfo.num_cols; i++) {
1515       /* Find the length of the string for this column. */
1516       column_len = strlen(cf->cinfo.col_data[i]);
1517       if (args->col_widths[i] > column_len)
1518          column_len = args->col_widths[i];
1519
1520       /* Make sure there's room in the line buffer for the column; if not,
1521          double its length. */
1522       line_len += column_len + 1;       /* "+1" for space */
1523       if (line_len > args->line_buf_len) {
1524         cp_off = cp - args->line_buf;
1525         args->line_buf_len = 2 * line_len;
1526         args->line_buf = g_realloc(args->line_buf, args->line_buf_len + 1);
1527         cp = args->line_buf + cp_off;
1528       }
1529
1530       /* Right-justify the packet number column. */
1531       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1532         sprintf(cp, "%*s", args->col_widths[i], cf->cinfo.col_data[i]);
1533       else
1534         sprintf(cp, "%-*s", args->col_widths[i], cf->cinfo.col_data[i]);
1535       cp += column_len;
1536       if (i != cf->cinfo.num_cols - 1)
1537         *cp++ = ' ';
1538     }
1539     *cp = '\0';
1540     print_line(args->print_fh, 0, args->print_args->format, args->line_buf);
1541   } else {
1542     if (args->print_separator)
1543       print_line(args->print_fh, 0, args->print_args->format, "");
1544
1545     /* Create the logical protocol tree, complete with the display
1546        representation of the items; we don't need the columns here,
1547        however. */
1548     edt = epan_dissect_new(TRUE, TRUE);
1549     epan_dissect_run(edt, pseudo_header, pd, fdata, NULL);
1550
1551     /* Print the information in that tree. */
1552     proto_tree_print(args->print_args, edt, args->print_fh);
1553
1554     if (args->print_args->print_hex) {
1555       /* Print the full packet data as hex. */
1556       print_hex_data(args->print_fh, args->print_args->format, edt);
1557     }
1558
1559     /* Print a blank line if we print anything after this. */
1560     args->print_separator = TRUE;
1561   } /* if (print_summary) */
1562   epan_dissect_free(edt);
1563
1564   return !ferror(args->print_fh);
1565 }
1566
1567 pp_return_t
1568 print_packets(capture_file *cf, print_args_t *print_args)
1569 {
1570   int         i;
1571   print_callback_args_t callback_args;
1572   gint        data_width;
1573   char        *cp;
1574   int         cp_off;
1575   int         column_len;
1576   int         line_len;
1577   psp_return_t ret;
1578
1579   callback_args.print_fh = open_print_dest(print_args->to_file,
1580                                            print_args->dest);
1581   if (callback_args.print_fh == NULL)
1582     return PP_OPEN_ERROR;       /* attempt to open destination failed */
1583
1584   print_preamble(callback_args.print_fh, print_args->format);
1585   if (ferror(callback_args.print_fh)) {
1586     close_print_dest(print_args->to_file, callback_args.print_fh);
1587     return PP_WRITE_ERROR;
1588   }
1589
1590   callback_args.print_args = print_args;
1591   callback_args.print_separator = FALSE;
1592   callback_args.line_buf = NULL;
1593   callback_args.line_buf_len = 256;
1594   callback_args.col_widths = NULL;
1595   if (print_args->print_summary) {
1596     /* We're printing packet summaries.  Allocate the line buffer at
1597        its initial length. */
1598     callback_args.line_buf = g_malloc(callback_args.line_buf_len + 1);
1599
1600     /* Find the widths for each of the columns - maximum of the
1601        width of the title and the width of the data - and print
1602        the column titles. */
1603     callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * cf->cinfo.num_cols);
1604     cp = &callback_args.line_buf[0];
1605     line_len = 0;
1606     for (i = 0; i < cf->cinfo.num_cols; i++) {
1607       /* Don't pad the last column. */
1608       if (i == cf->cinfo.num_cols - 1)
1609         callback_args.col_widths[i] = 0;
1610       else {
1611         callback_args.col_widths[i] = strlen(cf->cinfo.col_title[i]);
1612         data_width = get_column_char_width(get_column_format(i));
1613         if (data_width > callback_args.col_widths[i])
1614           callback_args.col_widths[i] = data_width;
1615       }
1616
1617       /* Find the length of the string for this column. */
1618       column_len = strlen(cf->cinfo.col_title[i]);
1619       if (callback_args.col_widths[i] > column_len)
1620         column_len = callback_args.col_widths[i];
1621
1622       /* Make sure there's room in the line buffer for the column; if not,
1623          double its length. */
1624       line_len += column_len + 1;       /* "+1" for space */
1625       if (line_len > callback_args.line_buf_len) {
1626         cp_off = cp - callback_args.line_buf;
1627         callback_args.line_buf_len = 2 * line_len;
1628         callback_args.line_buf = g_realloc(callback_args.line_buf,
1629                                            callback_args.line_buf_len + 1);
1630         cp = callback_args.line_buf + cp_off;
1631       }
1632
1633       /* Right-justify the packet number column. */
1634       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1635         sprintf(cp, "%*s", callback_args.col_widths[i], cf->cinfo.col_title[i]);
1636       else
1637         sprintf(cp, "%-*s", callback_args.col_widths[i], cf->cinfo.col_title[i]);
1638       cp += column_len;
1639       if (i != cf->cinfo.num_cols - 1)
1640         *cp++ = ' ';
1641     }
1642     *cp = '\0';
1643     print_line(callback_args.print_fh, 0, print_args->format,
1644                callback_args.line_buf);
1645   } /* if (print_summary) */
1646
1647   /* Iterate through the list of packets, printing the packets we were
1648      told to print. */
1649   ret = process_specified_packets(cf, &print_args->range, "Printing",
1650                                   "selected packets", print_packet,
1651                                   &callback_args);
1652
1653   if (callback_args.col_widths != NULL)
1654     g_free(callback_args.col_widths);
1655   if (callback_args.line_buf != NULL)
1656     g_free(callback_args.line_buf);
1657
1658   switch (ret) {
1659
1660   case PSP_FINISHED:
1661     /* Completed successfully. */
1662     break;
1663
1664   case PSP_STOPPED:
1665     /* Well, the user decided to abort the printing.
1666
1667        XXX - note that what got generated before they did that
1668        will get printed if we're piping to a print program; we'd
1669        have to write to a file and then hand that to the print
1670        program to make it actually not print anything. */
1671     break;
1672
1673   case PSP_FAILED:
1674     /* Error while printing.
1675
1676        XXX - note that what got generated before they did that
1677        will get printed if we're piping to a print program; we'd
1678        have to write to a file and then hand that to the print
1679        program to make it actually not print anything. */
1680     close_print_dest(print_args->to_file, callback_args.print_fh);
1681     return PP_WRITE_ERROR;
1682   }
1683
1684   print_finale(callback_args.print_fh, print_args->format);
1685   if (ferror(callback_args.print_fh)) {
1686     close_print_dest(print_args->to_file, callback_args.print_fh);
1687     return PP_WRITE_ERROR;
1688   }
1689
1690   close_print_dest(print_args->to_file, callback_args.print_fh);
1691
1692   return PP_OK;
1693 }
1694
1695 /* Scan through the packet list and change all columns that use the
1696    "command-line-specified" time stamp format to use the current
1697    value of that format. */
1698 void
1699 change_time_formats(capture_file *cf)
1700 {
1701   frame_data *fdata;
1702   progdlg_t  *progbar = NULL;
1703   gboolean    stop_flag;
1704   int         count;
1705   int         row;
1706   int         i;
1707   float       prog_val;
1708   GTimeVal    start_time;
1709   gchar       status_str[100];
1710   int         progbar_nextstep;
1711   int         progbar_quantum;
1712   int         first, last;
1713   gboolean    sorted_by_frame_column;
1714
1715   /* Are there any columns with time stamps in the "command-line-specified"
1716      format?
1717
1718      XXX - we have to force the "column is writable" flag on, as it
1719      might be off from the last frame that was dissected. */
1720   col_set_writable(&cf->cinfo, TRUE);
1721   if (!check_col(&cf->cinfo, COL_CLS_TIME)) {
1722     /* No, there aren't any columns in that format, so we have no work
1723        to do. */
1724     return;
1725   }
1726   first = cf->cinfo.col_first[COL_CLS_TIME];
1727   g_assert(first >= 0);
1728   last = cf->cinfo.col_last[COL_CLS_TIME];
1729
1730   /* Freeze the packet list while we redo it, so we don't get any
1731      screen updates while it happens. */
1732   packet_list_freeze();
1733
1734   /* Update the progress bar when it gets to this value. */
1735   progbar_nextstep = 0;
1736   /* When we reach the value that triggers a progress bar update,
1737      bump that value by this amount. */
1738   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1739   /* Count of packets at which we've looked. */
1740   count = 0;
1741
1742   /*  If the rows are currently sorted by the frame column then we know
1743    *  the row number of each packet: it's the row number of the previously
1744    *  displayed packet + 1.
1745    *
1746    *  Otherwise, if the display is sorted by a different column then we have
1747    *  to use the O(N) packet_list_find_row_from_data() (thus making the job
1748    *  of changing the time display format O(N**2)).
1749    *
1750    *  (XXX - In fact it's still O(N**2) because gtk_clist_set_text() takes
1751    *  the row number and walks that many elements down the clist to find
1752    *  the appropriate element.)
1753    */
1754   sorted_by_frame_column = FALSE;
1755   for (i = 0; i < cf->cinfo.num_cols; i++) {
1756     if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1757     {
1758       sorted_by_frame_column = (i == packet_list_get_sort_column());
1759       break;
1760     }
1761   }
1762
1763   stop_flag = FALSE;
1764   g_get_current_time(&start_time);
1765
1766   /* Iterate through the list of packets, checking whether the packet
1767      is in a row of the summary list and, if so, whether there are
1768      any columns that show the time in the "command-line-specified"
1769      format and, if so, update that row. */
1770   for (fdata = cf->plist, row = -1; fdata != NULL; fdata = fdata->next) {
1771     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1772        when we update it, we have to run the GTK+ main loop to get it
1773        to repaint what's pending, and doing so may involve an "ioctl()"
1774        to see if there's any pending input from an X server, and doing
1775        that for every packet can be costly, especially on a big file. */
1776     if (count >= progbar_nextstep) {
1777       /* let's not divide by zero. I should never be started
1778        * with count == 0, so let's assert that
1779        */
1780       g_assert(cf->count > 0);
1781
1782       prog_val = (gfloat) count / cf->count;
1783
1784       if (progbar == NULL)
1785         /* Create the progress bar if necessary */
1786         progbar = delayed_create_progress_dlg("Changing", "time display", 
1787           &stop_flag, &start_time, prog_val);
1788
1789       if (progbar != NULL) {
1790         g_snprintf(status_str, sizeof(status_str),
1791                    "%4u of %u packets", count, cf->count);
1792         update_progress_dlg(progbar, prog_val, status_str);
1793       }
1794
1795       progbar_nextstep += progbar_quantum;
1796     }
1797
1798     if (stop_flag) {
1799       /* Well, the user decided to abort the redisplay.  Just stop.
1800
1801          XXX - this leaves the time field in the old format in
1802          frames we haven't yet processed.  So it goes; should we
1803          simply not offer them the option of stopping? */
1804       break;
1805     }
1806
1807     count++;
1808
1809     /* Find what row this packet is in. */
1810     if (!sorted_by_frame_column) {
1811       /* This function is O(N), so we try to avoid using it... */
1812       row = packet_list_find_row_from_data(fdata);
1813     } else {
1814       /* ...which we do by maintaining a count of packets that are
1815          being displayed (i.e., that have passed the display filter),
1816          and using the current value of that count as the row number
1817          (which is why we can only do it when the display is sorted
1818          by the frame number). */
1819       if (fdata->flags.passed_dfilter)
1820         row++;
1821       else
1822         continue;
1823     }
1824
1825     if (row != -1) {
1826       /* This packet is in the summary list, on row "row". */
1827
1828       for (i = first; i <= last; i++) {
1829         if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1830           /* This is one of the columns that shows the time in
1831              "command-line-specified" format; update it. */
1832           cf->cinfo.col_buf[i][0] = '\0';
1833           col_set_cls_time(fdata, &cf->cinfo, i);
1834           packet_list_set_text(row, i, cf->cinfo.col_data[i]);
1835         }
1836       }
1837     }
1838   }
1839
1840   /* We're done redisplaying the packets; destroy the progress bar if it
1841      was created. */
1842   if (progbar != NULL)
1843     destroy_progress_dlg(progbar);
1844
1845   /* Set the column widths of those columns that show the time in
1846      "command-line-specified" format. */
1847   for (i = first; i <= last; i++) {
1848     if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1849       packet_list_set_cls_time_width(i);
1850     }
1851   }
1852
1853   /* Unfreeze the packet list. */
1854   packet_list_thaw();
1855 }
1856
1857 typedef struct {
1858         const char      *string;
1859         size_t          string_len;
1860         capture_file    *cf;
1861         gboolean        frame_matched;
1862 } match_data;
1863
1864 gboolean
1865 find_packet_protocol_tree(capture_file *cf, const char *string)
1866 {
1867   match_data            mdata;
1868
1869   mdata.string = string;
1870   mdata.string_len = strlen(string);
1871   return find_packet(cf, match_protocol_tree, &mdata);
1872 }
1873
1874 static gboolean
1875 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
1876 {
1877   match_data            *mdata = criterion;
1878   epan_dissect_t        *edt;
1879
1880   /* Construct the protocol tree, including the displayed text */
1881   edt = epan_dissect_new(TRUE, TRUE);
1882   /* We don't need the column information */
1883   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1884
1885   /* Iterate through all the nodes, seeing if they have text that matches. */
1886   mdata->cf = cf;
1887   mdata->frame_matched = FALSE;
1888   proto_tree_children_foreach(edt->tree, match_subtree_text, mdata);
1889   epan_dissect_free(edt);
1890   return mdata->frame_matched;
1891 }
1892
1893 static void
1894 match_subtree_text(proto_node *node, gpointer data)
1895 {
1896   match_data    *mdata = (match_data*) data;
1897   const gchar   *string = mdata->string;
1898   size_t        string_len = mdata->string_len;
1899   capture_file  *cf = mdata->cf;
1900   field_info    *fi = PITEM_FINFO(node);
1901   gchar         label_str[ITEM_LABEL_LENGTH];
1902   gchar         *label_ptr;
1903   size_t        label_len;
1904   guint32       i;
1905   guint8        c_char;
1906   size_t        c_match = 0;
1907
1908   if (mdata->frame_matched) {
1909     /* We already had a match; don't bother doing any more work. */
1910     return;
1911   }
1912
1913   /* Don't match invisible entries. */
1914   if (!fi->visible)
1915     return;
1916
1917   /* was a free format label produced? */
1918   if (fi->rep) {
1919     label_ptr = fi->rep->representation;
1920   } else {
1921     /* no, make a generic label */
1922     label_ptr = label_str;
1923     proto_item_fill_label(fi, label_str);
1924   }
1925     
1926   /* Does that label match? */
1927   label_len = strlen(label_ptr);
1928   for (i = 0; i < label_len; i++) {
1929     c_char = label_ptr[i];
1930     if (cf->case_type)
1931       c_char = toupper(c_char);
1932     if (c_char == string[c_match]) {
1933       c_match++;
1934       if (c_match == string_len) {
1935         /* No need to look further; we have a match */
1936         mdata->frame_matched = TRUE;
1937         return;
1938       }
1939     } else
1940       c_match = 0;
1941   }
1942   
1943   /* Recurse into the subtree, if it exists */
1944   if (node->first_child != NULL)
1945     proto_tree_children_foreach(node, match_subtree_text, mdata);
1946 }
1947
1948 gboolean
1949 find_packet_summary_line(capture_file *cf, const char *string)
1950 {
1951   match_data            mdata;
1952
1953   mdata.string = string;
1954   mdata.string_len = strlen(string);
1955   return find_packet(cf, match_summary_line, &mdata);
1956 }
1957
1958 static gboolean
1959 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
1960 {
1961   match_data            *mdata = criterion;
1962   const gchar           *string = mdata->string;
1963   size_t                string_len = mdata->string_len;
1964   epan_dissect_t        *edt;
1965   const char            *info_column;
1966   size_t                info_column_len;
1967   gboolean              frame_matched = FALSE;
1968   gint                  colx;
1969   guint32               i;
1970   guint8                c_char;
1971   size_t                c_match = 0;
1972
1973   /* Don't bother constructing the protocol tree */
1974   edt = epan_dissect_new(FALSE, FALSE);
1975   /* Get the column information */
1976   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
1977
1978   /* Find the Info column */
1979   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
1980     if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
1981       /* Found it.  See if we match. */
1982       info_column = edt->pi.cinfo->col_data[colx];
1983       info_column_len = strlen(info_column);
1984       for (i = 0; i < info_column_len; i++) {
1985         c_char = info_column[i];
1986         if (cf->case_type)
1987           c_char = toupper(c_char);
1988         if (c_char == string[c_match]) {
1989           c_match++;
1990           if (c_match == string_len) {
1991             frame_matched = TRUE;
1992             break;
1993           }
1994         } else
1995           c_match = 0;
1996       }
1997       break;
1998     }
1999   }
2000   epan_dissect_free(edt);
2001   return frame_matched;
2002 }
2003
2004 typedef struct {
2005         const guint8 *data;
2006         size_t data_len;
2007 } cbs_t;        /* "Counted byte string" */
2008
2009 gboolean
2010 find_packet_data(capture_file *cf, const guint8 *string, size_t string_size)
2011 {
2012   cbs_t info;
2013
2014   info.data = string;
2015   info.data_len = string_size;
2016
2017   /* String or hex search? */
2018   if (cf->ascii) {
2019     /* String search - what type of string? */
2020     switch (cf->scs_type) {
2021
2022     case SCS_ASCII_AND_UNICODE:
2023       return find_packet(cf, match_ascii_and_unicode, &info);
2024
2025     case SCS_ASCII:
2026       return find_packet(cf, match_ascii, &info);
2027
2028     case SCS_UNICODE:
2029       return find_packet(cf, match_unicode, &info);
2030
2031     default:
2032       g_assert_not_reached();
2033       return FALSE;
2034     }
2035   } else
2036     return find_packet(cf, match_binary, &info);
2037 }
2038
2039 static gboolean
2040 match_ascii_and_unicode(capture_file *cf, frame_data *fdata, void *criterion)
2041 {
2042   cbs_t         *info = criterion;
2043   const char    *ascii_text = info->data;
2044   size_t        textlen = info->data_len;
2045   gboolean      frame_matched;
2046   guint32       buf_len;
2047   guint32       i;
2048   guint8        c_char;
2049   size_t        c_match = 0;
2050
2051   frame_matched = FALSE;
2052   buf_len = fdata->pkt_len;
2053   for (i = 0; i < buf_len; i++) {
2054     c_char = cf->pd[i];
2055     if (cf->case_type)
2056       c_char = toupper(c_char);
2057     if (c_char != 0) {
2058       if (c_char == ascii_text[c_match]) {
2059         c_match++;
2060         if (c_match == textlen) {
2061           frame_matched = TRUE;
2062           break;
2063         }
2064       } else
2065         c_match = 0;
2066     }
2067   }
2068   return frame_matched;
2069 }
2070
2071 static gboolean
2072 match_ascii(capture_file *cf, frame_data *fdata, void *criterion)
2073 {
2074   cbs_t         *info = criterion;
2075   const char    *ascii_text = info->data;
2076   size_t        textlen = info->data_len;
2077   gboolean      frame_matched;
2078   guint32       buf_len;
2079   guint32       i;
2080   guint8        c_char;
2081   size_t        c_match = 0;
2082
2083   frame_matched = FALSE;
2084   buf_len = fdata->pkt_len;
2085   for (i = 0; i < buf_len; i++) {
2086     c_char = cf->pd[i];
2087     if (cf->case_type)
2088       c_char = toupper(c_char);
2089     if (c_char == ascii_text[c_match]) {
2090       c_match++;
2091       if (c_match == textlen) {
2092         frame_matched = TRUE;
2093         break;
2094       }
2095     } else
2096       c_match = 0;
2097   }
2098   return frame_matched;
2099 }
2100
2101 static gboolean
2102 match_unicode(capture_file *cf, frame_data *fdata, void *criterion)
2103 {
2104   cbs_t         *info = criterion;
2105   const char    *ascii_text = info->data;
2106   size_t        textlen = info->data_len;
2107   gboolean      frame_matched;
2108   guint32       buf_len;
2109   guint32       i;
2110   guint8        c_char;
2111   size_t        c_match = 0;
2112
2113   frame_matched = FALSE;
2114   buf_len = fdata->pkt_len;
2115   for (i = 0; i < buf_len; i++) {
2116     c_char = cf->pd[i];
2117     if (cf->case_type)
2118       c_char = toupper(c_char);
2119     if (c_char == ascii_text[c_match]) {
2120       c_match++;
2121       i++;
2122       if (c_match == textlen) {
2123         frame_matched = TRUE;
2124         break;
2125       }
2126     } else
2127       c_match = 0;
2128   }
2129   return frame_matched;
2130 }
2131
2132 static gboolean
2133 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
2134 {
2135   cbs_t         *info = criterion;
2136   const guint8  *binary_data = info->data;
2137   size_t        datalen = info->data_len;
2138   gboolean      frame_matched;
2139   guint32       buf_len;
2140   guint32       i;
2141   size_t        c_match = 0;
2142
2143   frame_matched = FALSE;
2144   buf_len = fdata->pkt_len;
2145   for (i = 0; i < buf_len; i++) {
2146     if (cf->pd[i] == binary_data[c_match]) {
2147       c_match++;
2148       if (c_match == datalen) {
2149         frame_matched = TRUE;
2150         break;
2151       }
2152     } else
2153       c_match = 0;
2154   }
2155   return frame_matched;
2156 }
2157
2158 gboolean
2159 find_packet_dfilter(capture_file *cf, dfilter_t *sfcode)
2160 {
2161   return find_packet(cf, match_dfilter, sfcode);
2162 }
2163
2164 static gboolean
2165 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
2166 {
2167   dfilter_t             *sfcode = criterion;
2168   epan_dissect_t        *edt;
2169   gboolean              frame_matched;
2170
2171   edt = epan_dissect_new(TRUE, FALSE);
2172   epan_dissect_prime_dfilter(edt, sfcode);
2173   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
2174   frame_matched = dfilter_apply_edt(sfcode, edt);
2175   epan_dissect_free(edt);
2176   return frame_matched;
2177 }
2178
2179 static gboolean
2180 find_packet(capture_file *cf,
2181             gboolean (*match_function)(capture_file *, frame_data *, void *),
2182             void *criterion)
2183 {
2184   frame_data *start_fd;
2185   frame_data *fdata;
2186   frame_data *new_fd = NULL;
2187   progdlg_t  *progbar = NULL;
2188   gboolean    stop_flag;
2189   int         count;
2190   int         err;
2191   gchar      *err_info;
2192   int         row;
2193   float       prog_val;
2194   GTimeVal    start_time;
2195   gchar       status_str[100];
2196   int         progbar_nextstep;
2197   int         progbar_quantum;
2198
2199   start_fd = cf->current_frame;
2200   if (start_fd != NULL)  {
2201     /* Iterate through the list of packets, starting at the packet we've
2202        picked, calling a routine to run the filter on the packet, see if
2203        it matches, and stop if so.  */
2204     count = 0;
2205     fdata = start_fd;
2206
2207     progbar_nextstep = 0;
2208     /* When we reach the value that triggers a progress bar update,
2209        bump that value by this amount. */
2210     progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2211
2212     stop_flag = FALSE;
2213     g_get_current_time(&start_time);
2214
2215     fdata = start_fd;
2216     for (;;) {
2217       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
2218          when we update it, we have to run the GTK+ main loop to get it
2219          to repaint what's pending, and doing so may involve an "ioctl()"
2220          to see if there's any pending input from an X server, and doing
2221          that for every packet can be costly, especially on a big file. */
2222       if (count >= progbar_nextstep) {
2223         /* let's not divide by zero. I should never be started
2224          * with count == 0, so let's assert that
2225          */
2226         g_assert(cf->count > 0);
2227
2228         prog_val = (gfloat) count / cf->count;
2229
2230         /* Create the progress bar if necessary */
2231         if (progbar == NULL)
2232            progbar = delayed_create_progress_dlg("Searching", cf->sfilter, 
2233              &stop_flag, &start_time, prog_val);
2234
2235         if (progbar != NULL) {
2236           g_snprintf(status_str, sizeof(status_str),
2237                      "%4u of %u packets", count, cf->count);
2238           update_progress_dlg(progbar, prog_val, status_str);
2239         }
2240
2241         progbar_nextstep += progbar_quantum;
2242       }
2243
2244       if (stop_flag) {
2245         /* Well, the user decided to abort the search.  Go back to the
2246            frame where we started. */
2247         new_fd = start_fd;
2248         break;
2249       }
2250
2251       /* Go past the current frame. */
2252       if (cf->sbackward) {
2253         /* Go on to the previous frame. */
2254         fdata = fdata->prev;
2255         if (fdata == NULL) {
2256           /*
2257            * XXX - other apps have a bit more of a detailed message
2258            * for this, and instead of offering "OK" and "Cancel",
2259            * they offer things such as "Continue" and "Cancel";
2260            * we need an API for popping up alert boxes with
2261            * {Verb} and "Cancel".
2262            */
2263           simple_dialog(ESD_TYPE_CONFIRMATION, ESD_BTN_OK,
2264                         "We have reached the beginning of the file\n\n Click OK to continue the search from the end of the file.");
2265           fdata = cf->plist_end;        /* wrap around */
2266         }
2267       } else {
2268         /* Go on to the next frame. */
2269         fdata = fdata->next;
2270         if (fdata == NULL) {
2271           simple_dialog(ESD_TYPE_CONFIRMATION, ESD_BTN_OK,
2272                       "We have reached the end of the file\n\n Click OK to continue the search from the beginning of the file.");
2273           fdata = cf->plist;    /* wrap around */
2274         }
2275       }
2276
2277       count++;
2278
2279       /* Is this packet in the display? */
2280       if (fdata->flags.passed_dfilter) {
2281         /* Yes.  Load its data. */
2282         if (!wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
2283                         cf->pd, fdata->cap_len, &err, &err_info)) {
2284           /* Read error.  Report the error, and go back to the frame
2285              where we started. */
2286           simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2287                         cf_read_error_message(err, err_info), cf->filename);
2288           new_fd = start_fd;
2289           break;
2290         }
2291
2292         /* Does it match the search criterion? */
2293         if ((*match_function)(cf, fdata, criterion)) {
2294           new_fd = fdata;
2295           break;        /* found it! */
2296         }
2297       }
2298
2299       if (fdata == start_fd) {
2300         /* We're back to the frame we were on originally, and that frame
2301            doesn't match the search filter.  The search failed. */
2302         break;
2303       }
2304     }
2305
2306     /* We're done scanning the packets; destroy the progress bar if it
2307        was created. */
2308     if (progbar != NULL)
2309       destroy_progress_dlg(progbar);
2310   }
2311
2312   if (new_fd != NULL) {
2313     /* We found a frame.  Find what row it's in. */
2314     row = packet_list_find_row_from_data(new_fd);
2315     g_assert(row != -1);
2316
2317     /* Select that row, make it the focus row, and make it visible. */
2318     packet_list_set_selected_row(row);
2319     return TRUE;        /* success */
2320   } else
2321     return FALSE;       /* failure */
2322 }
2323
2324 gboolean
2325 goto_frame(capture_file *cf, guint fnumber)
2326 {
2327   frame_data *fdata;
2328   int row;
2329
2330   for (fdata = cf->plist; fdata != NULL && fdata->num < fnumber; fdata = fdata->next)
2331     ;
2332
2333   if (fdata == NULL) {
2334     /* we didn't find a packet with that packet number */
2335     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2336                   "There is no packet with that packet number.");
2337     return FALSE;       /* we failed to go to that packet */
2338   }
2339   if (!fdata->flags.passed_dfilter) {
2340     /* that packet currently isn't displayed */
2341     /* XXX - add it to the set of displayed packets? */
2342     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2343                   "That packet is not currently being displayed.");
2344     return FALSE;       /* we failed to go to that packet */
2345   }
2346
2347   /* We found that packet, and it's currently being displayed.
2348      Find what row it's in. */
2349   row = packet_list_find_row_from_data(fdata);
2350   g_assert(row != -1);
2351
2352   /* Select that row, make it the focus row, and make it visible. */
2353   packet_list_set_selected_row(row);
2354   return TRUE;  /* we got to that packet */
2355 }
2356
2357 gboolean
2358 goto_top_frame(capture_file *cf)
2359 {
2360   frame_data *fdata;
2361   int row;
2362   frame_data *lowest_fdata = NULL;
2363
2364   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
2365     if (fdata->flags.passed_dfilter) {
2366         lowest_fdata = fdata;
2367         break;
2368     }
2369   }
2370
2371   if (lowest_fdata == NULL) {
2372       return FALSE;
2373   }
2374
2375   /* We found that packet, and it's currently being displayed.
2376      Find what row it's in. */
2377   row = packet_list_find_row_from_data(lowest_fdata);
2378   g_assert(row != -1);
2379
2380   /* Select that row, make it the focus row, and make it visible. */
2381   packet_list_set_selected_row(row);
2382   return TRUE;  /* we got to that packet */
2383 }
2384
2385 gboolean
2386 goto_bottom_frame(capture_file *cf)
2387 {
2388   frame_data *fdata;
2389   int row;
2390   frame_data *highest_fdata = NULL;
2391
2392   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
2393     if (fdata->flags.passed_dfilter) {
2394         highest_fdata = fdata;
2395     }
2396   }
2397
2398   if (highest_fdata == NULL) {
2399       return FALSE;
2400   }
2401
2402   /* We found that packet, and it's currently being displayed.
2403      Find what row it's in. */
2404   row = packet_list_find_row_from_data(highest_fdata);
2405   g_assert(row != -1);
2406
2407   /* Select that row, make it the focus row, and make it visible. */
2408   packet_list_set_selected_row(row);
2409   return TRUE;  /* we got to that packet */
2410 }
2411
2412 /* Select the packet on a given row. */
2413 void
2414 select_packet(capture_file *cf, int row)
2415 {
2416   frame_data *fdata;
2417   int err;
2418   gchar *err_info;
2419
2420   /* Get the frame data struct pointer for this frame */
2421   fdata = (frame_data *)packet_list_get_row_data(row);
2422
2423   if (fdata == NULL) {
2424     /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
2425        the first entry is added to it by "real_insert_row()", that row
2426        is selected (see "real_insert_row()", in "gtk/gtkclist.c", in both
2427        our version and the vanilla GTK+ version).
2428
2429        This means that a "select-row" signal is emitted; this causes
2430        "packet_list_select_cb()" to be called, which causes "select_packet()"
2431        to be called.
2432
2433        "select_packet()" fetches, above, the data associated with the
2434        row that was selected; however, as "gtk_clist_append()", which
2435        called "real_insert_row()", hasn't yet returned, we haven't yet
2436        associated any data with that row, so we get back a null pointer.
2437
2438        We can't assume that there's only one frame in the frame list,
2439        either, as we may be filtering the display.
2440
2441        We therefore assume that, if "row" is 0, i.e. the first row
2442        is being selected, and "cf->first_displayed" equals
2443        "cf->last_displayed", i.e. there's only one frame being
2444        displayed, that frame is the frame we want.
2445
2446        This means we have to set "cf->first_displayed" and
2447        "cf->last_displayed" before adding the row to the
2448        GtkCList; see the comment in "add_packet_to_packet_list()". */
2449
2450        if (row == 0 && cf->first_displayed == cf->last_displayed)
2451          fdata = cf->first_displayed;
2452   }
2453
2454   /* Get the data in that frame. */
2455   if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
2456                        cf->pd, fdata->cap_len, &err, &err_info)) {
2457     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2458                   cf_read_error_message(err, err_info), cf->filename);
2459     return;
2460   }
2461
2462   /* Record that this frame is the current frame. */
2463   cf->current_frame = fdata;
2464
2465   /* Create the logical protocol tree. */
2466   if (cf->edt != NULL) {
2467     epan_dissect_free(cf->edt);
2468     cf->edt = NULL;
2469   }
2470   /* We don't need the columns here. */
2471   cf->edt = epan_dissect_new(TRUE, TRUE);
2472   epan_dissect_run(cf->edt, &cf->pseudo_header, cf->pd, cf->current_frame,
2473           NULL);
2474
2475   /* Display the GUI protocol tree and hex dump.
2476      XXX - why do we dump core if we call "proto_tree_draw()"
2477      before calling "add_byte_views()"? */
2478   add_main_byte_views(cf->edt);
2479   main_proto_tree_draw(cf->edt->tree);
2480
2481   /* A packet is selected. */
2482   set_menus_for_selected_packet(cf);
2483 }
2484
2485 /* Unselect the selected packet, if any. */
2486 void
2487 unselect_packet(capture_file *cf)
2488 {
2489   /* Destroy the epan_dissect_t for the unselected packet. */
2490   if (cf->edt != NULL) {
2491     epan_dissect_free(cf->edt);
2492     cf->edt = NULL;
2493   }
2494
2495   /* Clear out the display of that packet. */
2496   clear_tree_and_hex_views();
2497
2498   /* No packet is selected. */
2499   cf->current_frame = NULL;
2500   set_menus_for_selected_packet(cf);
2501
2502   /* No protocol tree means no selected field. */
2503   unselect_field(cf);
2504 }
2505
2506 /* Unset the selected protocol tree field, if any. */
2507 void
2508 unselect_field(capture_file *cf)
2509 {
2510   statusbar_pop_field_msg();
2511   cf->finfo_selected = NULL;
2512   set_menus_for_selected_tree_row(cf);
2513 }
2514
2515 /*
2516  * Mark a particular frame.
2517  */
2518 void
2519 mark_frame(capture_file *cf, frame_data *frame)
2520 {
2521   frame->flags.marked = TRUE;
2522   cf->marked_count++;
2523 }
2524
2525 /*
2526  * Unmark a particular frame.
2527  */
2528 void
2529 unmark_frame(capture_file *cf, frame_data *frame)
2530 {
2531   frame->flags.marked = FALSE;
2532   cf->marked_count--;
2533 }
2534
2535 typedef struct {
2536   wtap_dumper *pdh;
2537   const char  *fname;
2538 } save_callback_args_t;
2539
2540 /*
2541  * Save a capture to a file, in a particular format, saving either
2542  * all packets, all currently-displayed packets, or all marked packets.
2543  *
2544  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
2545  * up a message box for the failure.
2546  */
2547 static gboolean
2548 save_packet(capture_file *cf _U_, frame_data *fdata,
2549             union wtap_pseudo_header *pseudo_header, const guint8 *pd,
2550             void *argsp)
2551 {
2552   save_callback_args_t *args = argsp;
2553   struct wtap_pkthdr hdr;
2554   int           err;
2555
2556   /* init the wtap header for saving */
2557   hdr.ts.tv_sec  = fdata->abs_secs;
2558   hdr.ts.tv_usec = fdata->abs_usecs;
2559   hdr.caplen     = fdata->cap_len;
2560   hdr.len        = fdata->pkt_len;
2561   hdr.pkt_encap  = fdata->lnk_t;
2562
2563   /* and save the packet */
2564   if (!wtap_dump(args->pdh, &hdr, pseudo_header, pd, &err)) {
2565     cf_write_failure_alert_box(args->fname, err);
2566     return FALSE;
2567   }
2568   return TRUE;
2569 }
2570
2571 gboolean
2572 cf_save(char *fname, capture_file *cf, packet_range_t *range, guint save_format)
2573 {
2574   gchar        *from_filename;
2575   gchar        *name_ptr, *save_msg, *save_fmt = " Saving: %s...";
2576   size_t        msg_len;
2577   int           err;
2578   gboolean      do_copy;
2579   wtap_dumper  *pdh;
2580   struct stat   infile, outfile;
2581   save_callback_args_t callback_args;
2582
2583   name_ptr = get_basename(fname);
2584   msg_len = strlen(name_ptr) + strlen(save_fmt) + 2;
2585   save_msg = g_malloc(msg_len);
2586   snprintf(save_msg, msg_len, save_fmt, name_ptr);
2587   statusbar_push_file_msg(save_msg);
2588   g_free(save_msg);
2589
2590   /*
2591    * Check that the from file is not the same as to file
2592    * We do it here so we catch all cases ...
2593    * Unfortunately, the file requester gives us an absolute file
2594    * name and the read file name may be relative (if supplied on
2595    * the command line). From Joerg Mayer.
2596    *
2597    * This is a bit tricky on win32. The st_ino field is documented as:
2598    * "The inode, and therefore st_ino, has no meaning in the FAT, ..."
2599    * but it *is* set to zero if stat() returns without an error,
2600    * so this is working, but maybe not quite the way expected. ULFL
2601    */
2602    infile.st_ino = 1;   /* These prevent us from getting equality         */
2603    outfile.st_ino = 2;  /* If one or other of the files is not accessible */
2604    stat(cf->filename, &infile);
2605    stat(fname, &outfile);
2606    if (infile.st_ino == outfile.st_ino) {
2607     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2608       "%sCapture file: \"%s\" already exists!%s\n\n"
2609       "Please choose a different filename.",
2610       simple_dialog_primary_start(), fname, simple_dialog_primary_end());
2611     goto fail;
2612   }
2613
2614   packet_range_process_init(range);
2615
2616   /* Used to be :
2617    * if (!save_filtered && !save_marked && !save_manual_range && 
2618    *     !save_marked_range && !save_curr && save_format == cf->cd_t) {
2619    */ 
2620         
2621   if (packet_range_process_all(range) && save_format == cf->cd_t) {
2622     /* We're not filtering packets, and we're saving it in the format
2623        it's already in, so we can just move or copy the raw data. */
2624
2625     if (cf->is_tempfile) {
2626       /* The file being saved is a temporary file from a live
2627          capture, so it doesn't need to stay around under that name;
2628          first, try renaming the capture buffer file to the new name. */
2629 #ifndef WIN32
2630       if (rename(cf->filename, fname) == 0) {
2631         /* That succeeded - there's no need to copy the source file. */
2632         from_filename = NULL;
2633         do_copy = FALSE;
2634       } else {
2635         if (errno == EXDEV) {
2636           /* They're on different file systems, so we have to copy the
2637              file. */
2638           do_copy = TRUE;
2639           from_filename = cf->filename;
2640         } else {
2641           /* The rename failed, but not because they're on different
2642              file systems - put up an error message.  (Or should we
2643              just punt and try to copy?  The only reason why I'd
2644              expect the rename to fail and the copy to succeed would
2645              be if we didn't have permission to remove the file from
2646              the temporary directory, and that might be fixable - but
2647              is it worth requiring the user to go off and fix it?) */
2648           simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2649                                 file_rename_error_message(errno), fname);
2650           goto fail;
2651         }
2652       }
2653 #else
2654       do_copy = TRUE;
2655       from_filename = cf->filename;
2656 #endif
2657     } else {
2658       /* It's a permanent file, so we should copy it, and not remove the
2659          original. */
2660       do_copy = TRUE;
2661       from_filename = cf->filename;
2662     }
2663
2664     if (do_copy) {
2665       /* Copy the file, if we haven't moved it. */
2666       if (!copy_binary_file(from_filename, fname))
2667         goto fail;
2668     }
2669   } else {
2670     /* Either we're filtering packets, or we're saving in a different
2671        format; we can't do that by copying or moving the capture file,
2672        we have to do it by writing the packets out in Wiretap. */
2673     pdh = wtap_dump_open(fname, save_format, cf->lnk_t, cf->snap, &err);
2674     if (pdh == NULL) {
2675       cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
2676       goto fail;
2677     }
2678
2679     /* XXX - we let the user save a subset of the packets.
2680
2681        If we do that, should we make that file the current file?  If so,
2682        it means we can no longer get at the other packets.  What does
2683        NetMon do? */
2684
2685     /* Iterate through the list of packets, processing the packets we were
2686        told to process.
2687
2688        XXX - we've already called "packet_range_process_init(range)", but
2689        "process_specified_packets()" will do it again.  Fortunately,
2690        that's harmless in this case, as we haven't done anything to
2691        "range" since we initialized it. */
2692     callback_args.pdh = pdh;
2693     callback_args.fname = fname;
2694     switch (process_specified_packets(cf, range, "Saving",
2695                                       "selected packets", save_packet,
2696                                       &callback_args)) {
2697
2698     case PSP_FINISHED:
2699       /* Completed successfully. */
2700       break;
2701
2702     case PSP_STOPPED:
2703       /* The user decided to abort the saving.
2704          XXX - remove the output file? */
2705       break;
2706
2707     case PSP_FAILED:
2708       /* Error while saving. */
2709       wtap_dump_close(pdh, &err);
2710       goto fail;
2711     }
2712
2713     if (!wtap_dump_close(pdh, &err)) {
2714       cf_close_failure_alert_box(fname, err);
2715       goto fail;
2716     }
2717   }
2718
2719   /* Pop the "Saving:" message off the status bar. */
2720   statusbar_pop_file_msg();
2721
2722   if (packet_range_process_all(range)) {
2723     /* We saved the entire capture, not just some packets from it.
2724        Open and read the file we saved it to.
2725
2726        XXX - this is somewhat of a waste; we already have the
2727        packets, all this gets us is updated file type information
2728        (which we could just stuff into "cf"), and having the new
2729        file be the one we have opened and from which we're reading
2730        the data, and it means we have to spend time opening and
2731        reading the file, which could be a significant amount of
2732        time if the file is large. */
2733     cf->user_saved = TRUE;
2734
2735     if ((err = cf_open(fname, FALSE, cf)) == 0) {
2736       /* XXX - report errors if this fails?
2737          What should we return if it fails or is aborted? */
2738       switch (cf_read(cf)) {
2739
2740       case READ_SUCCESS:
2741       case READ_ERROR:
2742         /* Just because we got an error, that doesn't mean we were unable
2743            to read any of the file; we handle what we could get from the
2744            file. */
2745         break;
2746
2747       case READ_ABORTED:
2748         /* The user bailed out of re-reading the capture file; the
2749            capture file has been closed - just return (without
2750            changing any menu settings; "cf_close()" set them
2751            correctly for the "no capture file open" state). */
2752         break;
2753       }
2754       set_menus_for_unsaved_capture_file(FALSE);
2755     }
2756   }
2757   return TRUE;
2758
2759 fail:
2760   /* Pop the "Saving:" message off the status bar. */
2761   statusbar_pop_file_msg();
2762   return FALSE;
2763 }
2764
2765 static void
2766 cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
2767                           gboolean for_writing, int file_type)
2768 {
2769   if (err < 0) {
2770     /* Wiretap error. */
2771     switch (err) {
2772
2773     case WTAP_ERR_NOT_REGULAR_FILE:
2774       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2775                     "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
2776                     filename);
2777       break;
2778
2779     case WTAP_ERR_RANDOM_OPEN_PIPE:
2780       /* Seen only when opening a capture file for reading. */
2781       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2782                     "The file \"%s\" is a pipe or FIFO; Ethereal cannot read pipe or FIFO files.",
2783                     filename);
2784       break;
2785
2786     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2787       /* Seen only when opening a capture file for reading. */
2788       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2789                     "The file \"%s\" is not a capture file in a format Ethereal understands.",
2790                     filename);
2791       break;
2792
2793     case WTAP_ERR_UNSUPPORTED:
2794       /* Seen only when opening a capture file for reading. */
2795       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2796                     "The file \"%s\" is not a capture file in a format Ethereal understands.\n"
2797                     "(%s)",
2798                     filename, err_info);
2799       g_free(err_info);
2800       break;
2801
2802     case WTAP_ERR_CANT_WRITE_TO_PIPE:
2803       /* Seen only when opening a capture file for writing. */
2804       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2805                     "The file \"%s\" is a pipe, and %s capture files cannot be "
2806                     "written to a pipe.",
2807                     filename, wtap_file_type_string(file_type));
2808       break;
2809
2810     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2811       /* Seen only when opening a capture file for writing. */
2812       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2813                     "Ethereal does not support writing capture files in that format.");
2814       break;
2815
2816     case WTAP_ERR_UNSUPPORTED_ENCAP:
2817       if (for_writing) {
2818         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2819                       "Ethereal cannot save this capture in that format.");
2820       } else {
2821         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2822                       "The file \"%s\" is a capture for a network type that Ethereal doesn't support.\n"
2823                       "(%s)",
2824                       filename, err_info);
2825         g_free(err_info);
2826       }
2827       break;
2828
2829     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2830       if (for_writing) {
2831         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2832                       "Ethereal cannot save this capture in that format.");
2833       } else {
2834         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2835                       "The file \"%s\" is a capture for a network type that Ethereal doesn't support.",
2836                       filename);
2837       }
2838       break;
2839
2840     case WTAP_ERR_BAD_RECORD:
2841       /* Seen only when opening a capture file for reading. */
2842       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2843                     "The file \"%s\" appears to be damaged or corrupt.\n"
2844                     "(%s)",
2845                     filename, err_info);
2846       g_free(err_info);
2847       break;
2848
2849     case WTAP_ERR_CANT_OPEN:
2850       if (for_writing) {
2851         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2852                       "The file \"%s\" could not be created for some unknown reason.",
2853                       filename);
2854       } else {
2855         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2856                       "The file \"%s\" could not be opened for some unknown reason.",
2857                       filename);
2858       }
2859       break;
2860
2861     case WTAP_ERR_SHORT_READ:
2862       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2863                     "The file \"%s\" appears to have been cut short"
2864                     " in the middle of a packet or other data.",
2865                     filename);
2866       break;
2867
2868     case WTAP_ERR_SHORT_WRITE:
2869       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2870                     "A full header couldn't be written to the file \"%s\".",
2871                     filename);
2872       break;
2873
2874     default:
2875       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2876                     "The file \"%s\" could not be %s: %s.",
2877                     filename,
2878                     for_writing ? "created" : "opened",
2879                     wtap_strerror(err));
2880       break;
2881     }
2882   } else {
2883     /* OS error. */
2884     open_failure_alert_box(filename, err, for_writing);
2885   }
2886 }
2887
2888 static char *
2889 file_rename_error_message(int err)
2890 {
2891   char *errmsg;
2892   static char errmsg_errno[1024+1];
2893
2894   switch (err) {
2895
2896   case ENOENT:
2897     errmsg = "The path to the file \"%s\" does not exist.";
2898     break;
2899
2900   case EACCES:
2901     errmsg = "You do not have permission to move the capture file to \"%s\".";
2902     break;
2903
2904   default:
2905     snprintf(errmsg_errno, sizeof(errmsg_errno),
2906                     "The file \"%%s\" could not be moved: %s.",
2907                                 wtap_strerror(err));
2908     errmsg = errmsg_errno;
2909     break;
2910   }
2911   return errmsg;
2912 }
2913
2914 char *
2915 cf_read_error_message(int err, gchar *err_info)
2916 {
2917   static char errmsg_errno[1024+1];
2918
2919   switch (err) {
2920
2921   case WTAP_ERR_UNSUPPORTED:
2922   case WTAP_ERR_UNSUPPORTED_ENCAP:
2923   case WTAP_ERR_BAD_RECORD:
2924     snprintf(errmsg_errno, sizeof(errmsg_errno),
2925              "An error occurred while reading from the file \"%%s\": %s.\n(%s)",
2926              wtap_strerror(err), err_info);
2927     break;
2928
2929   default:
2930     snprintf(errmsg_errno, sizeof(errmsg_errno),
2931              "An error occurred while reading from the file \"%%s\": %s.",
2932              wtap_strerror(err));
2933     break;
2934   }
2935   return errmsg_errno;
2936 }
2937
2938 static void
2939 cf_write_failure_alert_box(const char *filename, int err)
2940 {
2941   if (err < 0) {
2942     /* Wiretap error. */
2943     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2944                   "An error occurred while writing to the file \"%s\": %s.",
2945                   filename, wtap_strerror(err));
2946   } else {
2947     /* OS error. */
2948     write_failure_alert_box(filename, err);
2949   }
2950 }
2951
2952 /* Check for write errors - if the file is being written to an NFS server,
2953    a write error may not show up until the file is closed, as NFS clients
2954    might not send writes to the server until the "write()" call finishes,
2955    so that the write may fail on the server but the "write()" may succeed. */
2956 static void
2957 cf_close_failure_alert_box(const char *filename, int err)
2958 {
2959   if (err < 0) {
2960     /* Wiretap error. */
2961     switch (err) {
2962
2963     case WTAP_ERR_CANT_CLOSE:
2964       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2965                     "The file \"%s\" couldn't be closed for some unknown reason.",
2966                     filename);
2967       break;
2968
2969     case WTAP_ERR_SHORT_WRITE:
2970       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2971                     "Not all the packets could be written to the file \"%s\".",
2972                     filename);
2973       break;
2974
2975     default:
2976       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2977                     "An error occurred while closing the file \"%s\": %s.",
2978                     filename, wtap_strerror(err));
2979       break;
2980     }
2981   } else {
2982     /* OS error.
2983        We assume that a close error from the OS is really a write error. */
2984     write_failure_alert_box(filename, err);
2985   }
2986 }
2987
2988
2989 /* Copies a file in binary mode, for those operating systems that care about
2990  * such things.
2991  * Returns TRUE on success, FALSE on failure. If a failure, it also
2992  * displays a simple dialog window with the error message.
2993  */
2994 static gboolean
2995 copy_binary_file(char *from_filename, char *to_filename)
2996 {
2997   int           from_fd, to_fd, nread, nwritten, err;
2998   guint8        pd[65536];
2999
3000   /* Copy the raw bytes of the file. */
3001   from_fd = open(from_filename, O_RDONLY | O_BINARY);
3002   if (from_fd < 0) {
3003     open_failure_alert_box(from_filename, errno, FALSE);
3004     goto done;
3005   }
3006
3007   /* Use open() instead of creat() so that we can pass the O_BINARY
3008      flag, which is relevant on Win32; it appears that "creat()"
3009      may open the file in text mode, not binary mode, but we want
3010      to copy the raw bytes of the file, so we need the output file
3011      to be open in binary mode. */
3012   to_fd = open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
3013   if (to_fd < 0) {
3014     open_failure_alert_box(to_filename, errno, TRUE);
3015     close(from_fd);
3016     goto done;
3017   }
3018
3019   while ((nread = read(from_fd, pd, sizeof pd)) > 0) {
3020     nwritten = write(to_fd, pd, nread);
3021     if (nwritten < nread) {
3022       if (nwritten < 0)
3023         err = errno;
3024       else
3025         err = WTAP_ERR_SHORT_WRITE;
3026       write_failure_alert_box(to_filename, err);
3027       close(from_fd);
3028       close(to_fd);
3029       goto done;
3030     }
3031   }
3032   if (nread < 0) {
3033     err = errno;
3034     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3035                   "An error occurred while reading from the file \"%s\": %s.",
3036                   from_filename, strerror(err));
3037     close(from_fd);
3038     close(to_fd);
3039     goto done;
3040   }
3041   close(from_fd);
3042   if (close(to_fd) < 0) {
3043     write_failure_alert_box(to_filename, errno);
3044     goto done;
3045   }
3046
3047   return TRUE;
3048
3049 done:
3050   return FALSE;
3051 }