e02d2074b6026f367d82970c13e014dcc5981313
[obnox/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * $Id: file.c,v 1.367 2004/02/23 22:48:50 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 gboolean
964 filter_packets(capture_file *cf, gchar *dftext, gboolean force)
965 {
966   dfilter_t *dfcode;
967   char      *filter_new = dftext ? dftext : "";
968   char      *filter_old = cf->dfilter ? cf->dfilter : "";
969
970   /* if new filter equals old one, do nothing unless told to do so */
971   if (!force && strcmp(filter_new, filter_old) == 0) {
972     return TRUE;
973   }
974
975   if (dftext == NULL) {
976     /* The new filter is an empty filter (i.e., display all packets). */
977     dfcode = NULL;
978   } else {
979     /*
980      * We have a filter; make a copy of it (as we'll be saving it),
981      * and try to compile it.
982      */
983     dftext = g_strdup(dftext);
984     if (!dfilter_compile(dftext, &dfcode)) {
985       /* The attempt failed; report an error. */
986       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, 
987           "%s%s%s\n"
988           "\n"
989           "The display filter \"%s\" is not a valid display filter.\n"
990           "See the help for a description of the display filter syntax.",
991           simple_dialog_primary_start(), dfilter_error_msg,
992           simple_dialog_primary_end(), dftext);
993       g_free(dftext);
994       return FALSE;
995     }
996
997     /* Was it empty? */
998     if (dfcode == NULL) {
999       /* Yes - free the filter text, and set it to null. */
1000       g_free(dftext);
1001       dftext = NULL;
1002     }
1003   }
1004
1005   /* We have a valid filter.  Replace the current filter. */
1006   if (cf->dfilter != NULL)
1007     g_free(cf->dfilter);
1008   cf->dfilter = dftext;
1009   if (cf->dfcode != NULL)
1010     dfilter_free(cf->dfcode);
1011   cf->dfcode = dfcode;
1012
1013   /* Now rescan the packet list, applying the new filter, but not
1014      throwing away information constructed on a previous pass. */
1015   if (dftext == NULL) {
1016     rescan_packets(cf, "Resetting", "Filter", TRUE, FALSE);
1017   } else {
1018     rescan_packets(cf, "Filtering", dftext, TRUE, FALSE);
1019   }
1020   return TRUE;
1021 }
1022
1023 void
1024 colorize_packets(capture_file *cf)
1025 {
1026   rescan_packets(cf, "Colorizing", "all packets", FALSE, FALSE);
1027 }
1028
1029 void
1030 reftime_packets(capture_file *cf)
1031 {
1032   rescan_packets(cf, "Updating Reftime", "all packets", FALSE, FALSE);
1033 }
1034
1035 void
1036 redissect_packets(capture_file *cf)
1037 {
1038   rescan_packets(cf, "Reprocessing", "all packets", TRUE, TRUE);
1039 }
1040
1041 /* Rescan the list of packets, reconstructing the CList.
1042
1043    "action" describes why we're doing this; it's used in the progress
1044    dialog box.
1045
1046    "action_item" describes what we're doing; it's used in the progress
1047    dialog box.
1048
1049    "refilter" is TRUE if we need to re-evaluate the filter expression.
1050
1051    "redissect" is TRUE if we need to make the dissectors reconstruct
1052    any state information they have (because a preference that affects
1053    some dissector has changed, meaning some dissector might construct
1054    its state differently from the way it was constructed the last time). */
1055 static void
1056 rescan_packets(capture_file *cf, const char *action, const char *action_item,
1057                 gboolean refilter, gboolean redissect)
1058 {
1059   frame_data *fdata;
1060   progdlg_t  *progbar = NULL;
1061   gboolean    stop_flag;
1062   int         count;
1063   int         err;
1064   gchar      *err_info;
1065   frame_data *selected_frame, *preceding_frame, *following_frame, *prev_frame;
1066   int         selected_row, prev_row, preceding_row, following_row;
1067   gboolean    selected_frame_seen;
1068   int         row;
1069   float       prog_val;
1070   GTimeVal    start_time;
1071   gchar       status_str[100];
1072   int         progbar_nextstep;
1073   int         progbar_quantum;
1074
1075   cum_bytes=0;
1076   reset_tap_listeners();
1077   /* Which frame, if any, is the currently selected frame?
1078      XXX - should the selected frame or the focus frame be the "current"
1079      frame, that frame being the one from which "Find Frame" searches
1080      start? */
1081   selected_frame = cf->current_frame;
1082
1083   /* We don't yet know what row that frame will be on, if any, after we
1084      rebuild the clist, however. */
1085   selected_row = -1;
1086
1087   if (redissect) {
1088     /* We need to re-initialize all the state information that protocols
1089        keep, because some preference that controls a dissector has changed,
1090        which might cause the state information to be constructed differently
1091        by that dissector. */
1092
1093     /* Initialize all data structures used for dissection. */
1094     init_dissection();
1095   }
1096
1097   /* Freeze the packet list while we redo it, so we don't get any
1098      screen updates while it happens. */
1099   packet_list_freeze();
1100
1101   /* Clear it out. */
1102   packet_list_clear();
1103
1104   /* We don't yet know which will be the first and last frames displayed. */
1105   cf->first_displayed = NULL;
1106   cf->last_displayed = NULL;
1107
1108   /* We currently don't display any packets */
1109   cf->displayed_count = 0;
1110
1111   /* Iterate through the list of frames.  Call a routine for each frame
1112      to check whether it should be displayed and, if so, add it to
1113      the display list. */
1114   firstsec = 0;
1115   firstusec = 0;
1116   prevsec = 0;
1117   prevusec = 0;
1118
1119   /* Update the progress bar when it gets to this value. */
1120   progbar_nextstep = 0;
1121   /* When we reach the value that triggers a progress bar update,
1122      bump that value by this amount. */
1123   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1124   /* Count of packets at which we've looked. */
1125   count = 0;
1126
1127   stop_flag = FALSE;
1128   g_get_current_time(&start_time);
1129
1130   row = -1;             /* no previous row yet */
1131   prev_row = -1;
1132   prev_frame = NULL;
1133
1134   preceding_row = -1;
1135   preceding_frame = NULL;
1136   following_row = -1;
1137   following_frame = NULL;
1138
1139   selected_frame_seen = FALSE;
1140
1141   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1142     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1143        when we update it, we have to run the GTK+ main loop to get it
1144        to repaint what's pending, and doing so may involve an "ioctl()"
1145        to see if there's any pending input from an X server, and doing
1146        that for every packet can be costly, especially on a big file. */
1147     if (count >= progbar_nextstep) {
1148       /* let's not divide by zero. I should never be started
1149        * with count == 0, so let's assert that
1150        */
1151       g_assert(cf->count > 0);
1152       prog_val = (gfloat) count / cf->count;
1153
1154       if (progbar == NULL)
1155         /* Create the progress bar if necessary */
1156         progbar = delayed_create_progress_dlg(action, action_item, &stop_flag,
1157           &start_time, prog_val);
1158
1159       if (progbar != NULL) {
1160         g_snprintf(status_str, sizeof(status_str),
1161                   "%4u of %u frames", count, cf->count);
1162         update_progress_dlg(progbar, prog_val, status_str);
1163       }
1164
1165       progbar_nextstep += progbar_quantum;
1166     }
1167
1168     if (stop_flag) {
1169       /* Well, the user decided to abort the filtering.  Just stop.
1170
1171          XXX - go back to the previous filter?  Users probably just
1172          want not to wait for a filtering operation to finish;
1173          unless we cancel by having no filter, reverting to the
1174          previous filter will probably be even more expensive than
1175          continuing the filtering, as it involves going back to the
1176          beginning and filtering, and even with no filter we currently
1177          have to re-generate the entire clist, which is also expensive.
1178
1179          I'm not sure what Network Monitor does, but it doesn't appear
1180          to give you an unfiltered display if you cancel. */
1181       break;
1182     }
1183
1184     count++;
1185
1186     if (redissect) {
1187       /* Since all state for the frame was destroyed, mark the frame
1188        * as not visited, free the GSList referring to the state
1189        * data (the per-frame data itself was freed by
1190        * "init_dissection()"), and null out the GSList pointer. */
1191       fdata->flags.visited = 0;
1192       if (fdata->pfd) {
1193         g_slist_free(fdata->pfd);
1194         fdata->pfd = NULL;
1195       }
1196     }
1197
1198     if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1199         cf->pd, fdata->cap_len, &err, &err_info)) {
1200         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
1201                       cf_read_error_message(err, err_info), cf->filename);
1202         break;
1203     }
1204
1205     /* If the previous frame is displayed, and we haven't yet seen the
1206        selected frame, remember that frame - it's the closest one we've
1207        yet seen before the selected frame. */
1208     if (prev_row != -1 && !selected_frame_seen) {
1209       preceding_row = prev_row;
1210       preceding_frame = prev_frame;
1211     }
1212     row = add_packet_to_packet_list(fdata, cf, &cf->pseudo_header, cf->pd,
1213                                         refilter);
1214
1215     /* If this frame is displayed, and this is the first frame we've
1216        seen displayed after the selected frame, remember this frame -
1217        it's the closest one we've yet seen at or after the selected
1218        frame. */
1219     if (row != -1 && selected_frame_seen && following_row == -1) {
1220       following_row = row;
1221       following_frame = fdata;
1222     }
1223     if (fdata == selected_frame) {
1224       selected_row = row;
1225       selected_frame_seen = TRUE;
1226     }
1227
1228     /* Remember this row/frame - it'll be the previous row/frame
1229        on the next pass through the loop. */
1230     prev_row = row;
1231     prev_frame = fdata;
1232   }
1233
1234   if (redissect) {
1235     /* Clear out what remains of the visited flags and per-frame data
1236        pointers.
1237
1238        XXX - that may cause various forms of bogosity when dissecting
1239        these frames, as they won't have been seen by this sequential
1240        pass, but the only alternative I see is to keep scanning them
1241        even though the user requested that the scan stop, and that
1242        would leave the user stuck with an Ethereal grinding on
1243        until it finishes.  Should we just stick them with that? */
1244     for (; fdata != NULL; fdata = fdata->next) {
1245       fdata->flags.visited = 0;
1246       if (fdata->pfd) {
1247         g_slist_free(fdata->pfd);
1248         fdata->pfd = NULL;
1249       }
1250     }
1251   }
1252
1253   /* We're done filtering the packets; destroy the progress bar if it
1254      was created. */
1255   if (progbar != NULL)
1256     destroy_progress_dlg(progbar);
1257
1258   /* Unfreeze the packet list. */
1259   packet_list_thaw();
1260
1261   if (selected_row == -1) {
1262     /* The selected frame didn't pass the filter. */
1263     if (selected_frame == NULL) {
1264       /* That's because there *was* no selected frame.  Make the first
1265          displayed frame the current frame. */
1266       selected_row = 0;
1267     } else {
1268       /* Find the nearest displayed frame to the selected frame (whether
1269          it's before or after that frame) and make that the current frame.
1270          If the next and previous displayed frames are equidistant from the
1271          selected frame, choose the next one. */
1272       g_assert(following_frame == NULL ||
1273                following_frame->num >= selected_frame->num);
1274       g_assert(preceding_frame == NULL ||
1275                preceding_frame->num <= selected_frame->num);
1276       if (following_frame == NULL) {
1277         /* No frame after the selected frame passed the filter, so we
1278            have to select the last displayed frame before the selected
1279            frame. */
1280         selected_row = preceding_row;
1281       } else if (preceding_frame == NULL) {
1282         /* No frame before the selected frame passed the filter, so we
1283            have to select the first displayed frame after the selected
1284            frame. */
1285         selected_row = following_row;
1286       } else {
1287         /* Choose the closer of the last displayed frame before the
1288            selected frame and the first displayed frame after the
1289            selected frame; in case of a tie, choose the first displayed
1290            frame after the selected frame. */
1291         if (following_frame->num - selected_frame->num <=
1292             selected_frame->num - preceding_frame->num) {
1293           selected_row = following_row;
1294         } else {
1295           /* The previous frame is closer to the selected frame than the
1296              next frame. */
1297           selected_row = preceding_row;
1298         }
1299       }
1300     }
1301   }
1302
1303   if (selected_row == -1) {
1304     /* There are no frames displayed at all. */
1305     unselect_packet(cf);
1306   } else {
1307     /* Either the frame that was selected passed the filter, or we've
1308        found the nearest displayed frame to that frame.  Select it, make
1309        it the focus row, and make it visible. */
1310     packet_list_set_selected_row(selected_row);
1311   }
1312 }
1313
1314 typedef enum {
1315   PSP_FINISHED,
1316   PSP_STOPPED,
1317   PSP_FAILED
1318 } psp_return_t;
1319
1320 psp_return_t
1321 process_specified_packets(capture_file *cf, packet_range_t *range,
1322     const char *string1, const char *string2,
1323     gboolean (*callback)(capture_file *, frame_data *,
1324                          union wtap_pseudo_header *, const guint8 *, void *),
1325     void *callback_args)
1326 {
1327   frame_data *fdata;
1328   int         err;
1329   gchar      *err_info;
1330   union wtap_pseudo_header pseudo_header;
1331   guint8      pd[WTAP_MAX_PACKET_SIZE+1];
1332   psp_return_t ret = PSP_FINISHED;
1333
1334   progdlg_t  *progbar = NULL;
1335   int         progbar_count;
1336   float       progbar_val;
1337   gboolean    progbar_stop_flag;
1338   GTimeVal    progbar_start_time;
1339   gchar       progbar_status_str[100];
1340   int         progbar_nextstep;
1341   int         progbar_quantum;
1342   range_process_e process_this;
1343
1344   /* Update the progress bar when it gets to this value. */
1345   progbar_nextstep = 0;
1346   /* When we reach the value that triggers a progress bar update,
1347      bump that value by this amount. */
1348   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1349   /* Count of packets at which we've looked. */
1350   progbar_count = 0;
1351
1352   progbar_stop_flag = FALSE;
1353   g_get_current_time(&progbar_start_time);
1354
1355   packet_range_process_init(range);
1356
1357   /* Iterate through the list of packets, printing the packets that
1358      were selected by the current display filter.  */
1359   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1360     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1361        when we update it, we have to run the GTK+ main loop to get it
1362        to repaint what's pending, and doing so may involve an "ioctl()"
1363        to see if there's any pending input from an X server, and doing
1364        that for every packet can be costly, especially on a big file. */
1365     if (progbar_count >= progbar_nextstep) {
1366       /* let's not divide by zero. I should never be started
1367        * with count == 0, so let's assert that
1368        */
1369       g_assert(cf->count > 0);
1370       progbar_val = (gfloat) progbar_count / cf->count;
1371
1372       if (progbar == NULL)
1373         /* Create the progress bar if necessary */
1374         progbar = delayed_create_progress_dlg(string1, string2,
1375                                               &progbar_stop_flag,
1376                                               &progbar_start_time,
1377                                               progbar_val);
1378
1379       if (progbar != NULL) {
1380         g_snprintf(progbar_status_str, sizeof(progbar_status_str),
1381                    "%4u of %u packets", progbar_count, cf->count);
1382         update_progress_dlg(progbar, progbar_val, progbar_status_str);
1383       }
1384
1385       progbar_nextstep += progbar_quantum;
1386     }
1387
1388     if (progbar_stop_flag) {
1389       /* Well, the user decided to abort the operation.  Just stop,
1390          and arrange to return TRUE to our caller, so they know it
1391          was stopped explicitly. */
1392       ret = PSP_STOPPED;
1393       break;
1394     }
1395
1396     progbar_count++;
1397
1398     /* do we have to process this packet? */
1399     process_this = packet_range_process_packet(range, fdata);
1400     if (process_this == range_process_next) {
1401         /* this packet uninteresting, continue with next one */
1402         continue;
1403     } else if (process_this == range_processing_finished) {
1404         /* all interesting packets processed, stop the loop */
1405         break;
1406     }
1407
1408     /* Get the packet */
1409     if (!wtap_seek_read(cf->wth, fdata->file_off, &pseudo_header,
1410                         pd, fdata->cap_len, &err, &err_info)) {
1411       /* Attempt to get the packet failed. */
1412       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
1413                     cf_read_error_message(err, err_info), cf->filename);
1414       ret = PSP_FAILED;
1415       break;
1416     }
1417     if (!callback(cf, fdata, &pseudo_header, pd, callback_args)) {
1418       /* Callback failed.  We assume it reported the error appropriately. */
1419       ret = PSP_FAILED;
1420       break;
1421     }
1422   }
1423
1424   /* We're done printing the packets; destroy the progress bar if
1425      it was created. */
1426   if (progbar != NULL)
1427     destroy_progress_dlg(progbar);
1428
1429   return ret;
1430 }
1431
1432 static gboolean
1433 retap_packet(capture_file *cf _U_, frame_data *fdata,
1434              union wtap_pseudo_header *pseudo_header, const guint8 *pd,
1435              void *argsp _U_)
1436 {
1437   epan_dissect_t *edt;
1438
1439   /* If we have tap listeners, allocate a protocol tree root node, so that
1440      we'll construct a protocol tree against which a filter expression can
1441      be evaluated. */
1442   edt = epan_dissect_new(num_tap_filters != 0, FALSE);
1443   tap_queue_init(edt);
1444   epan_dissect_run(edt, pseudo_header, pd, fdata, NULL);
1445   tap_push_tapped_queue(edt);
1446   epan_dissect_free(edt);
1447
1448   return TRUE;
1449 }
1450
1451 int
1452 retap_packets(capture_file *cf)
1453 {
1454   packet_range_t range;
1455
1456   /* Reset the tap listeners. */
1457   reset_tap_listeners();
1458
1459   /* Iterate through the list of packets, dissecting all packets and
1460      re-running the taps. */
1461   packet_range_init(&range);
1462   packet_range_process_init(&range);
1463   switch (process_specified_packets(cf, &range, "Refiltering statistics on",
1464                                     "all packets", retap_packet,
1465                                     NULL)) {
1466   case PSP_FINISHED:
1467     /* Completed successfully. */
1468     break;
1469
1470   case PSP_STOPPED:
1471     /* Well, the user decided to abort the refiltering.
1472        Return FALSE so our caller knows they did that. */
1473     return FALSE;
1474
1475   case PSP_FAILED:
1476     /* Error while retapping. */
1477     return FALSE;
1478   }
1479
1480   return TRUE;
1481 }
1482
1483 typedef struct {
1484   print_args_t *print_args;
1485   FILE         *print_fh;
1486   gboolean      print_separator;
1487   char         *line_buf;
1488   int           line_buf_len;
1489   gint         *col_widths;
1490 } print_callback_args_t;
1491
1492 static gboolean
1493 print_packet(capture_file *cf, frame_data *fdata,
1494              union wtap_pseudo_header *pseudo_header, const guint8 *pd,
1495              void *argsp)
1496 {
1497   print_callback_args_t *args = argsp;
1498   epan_dissect_t *edt;
1499   int             i;
1500   char           *cp;
1501   int             line_len;
1502   int             column_len;
1503   int             cp_off;
1504
1505   if (args->print_args->print_summary) {
1506     /* Fill in the column information, but don't bother creating
1507        the logical protocol tree. */
1508     edt = epan_dissect_new(FALSE, FALSE);
1509     epan_dissect_run(edt, pseudo_header, pd, fdata, &cf->cinfo);
1510     epan_dissect_fill_in_columns(edt);
1511     cp = &args->line_buf[0];
1512     line_len = 0;
1513     for (i = 0; i < cf->cinfo.num_cols; i++) {
1514       /* Find the length of the string for this column. */
1515       column_len = strlen(cf->cinfo.col_data[i]);
1516       if (args->col_widths[i] > column_len)
1517          column_len = args->col_widths[i];
1518
1519       /* Make sure there's room in the line buffer for the column; if not,
1520          double its length. */
1521       line_len += column_len + 1;       /* "+1" for space */
1522       if (line_len > args->line_buf_len) {
1523         cp_off = cp - args->line_buf;
1524         args->line_buf_len = 2 * line_len;
1525         args->line_buf = g_realloc(args->line_buf, args->line_buf_len + 1);
1526         cp = args->line_buf + cp_off;
1527       }
1528
1529       /* Right-justify the packet number column. */
1530       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1531         sprintf(cp, "%*s", args->col_widths[i], cf->cinfo.col_data[i]);
1532       else
1533         sprintf(cp, "%-*s", args->col_widths[i], cf->cinfo.col_data[i]);
1534       cp += column_len;
1535       if (i != cf->cinfo.num_cols - 1)
1536         *cp++ = ' ';
1537     }
1538     *cp = '\0';
1539     print_line(args->print_fh, 0, args->print_args->format, args->line_buf);
1540   } else {
1541     if (args->print_separator)
1542       print_line(args->print_fh, 0, args->print_args->format, "");
1543
1544     /* Create the logical protocol tree, complete with the display
1545        representation of the items; we don't need the columns here,
1546        however. */
1547     edt = epan_dissect_new(TRUE, TRUE);
1548     epan_dissect_run(edt, pseudo_header, pd, fdata, NULL);
1549
1550     /* Print the information in that tree. */
1551     proto_tree_print(args->print_args, edt, args->print_fh);
1552
1553     if (args->print_args->print_hex) {
1554       /* Print the full packet data as hex. */
1555       print_hex_data(args->print_fh, args->print_args->format, edt);
1556     }
1557
1558     /* Print a blank line if we print anything after this. */
1559     args->print_separator = TRUE;
1560   } /* if (print_summary) */
1561   epan_dissect_free(edt);
1562
1563   return !ferror(args->print_fh);
1564 }
1565
1566 pp_return_t
1567 print_packets(capture_file *cf, print_args_t *print_args)
1568 {
1569   int         i;
1570   print_callback_args_t callback_args;
1571   gint        data_width;
1572   char        *cp;
1573   int         cp_off;
1574   int         column_len;
1575   int         line_len;
1576   psp_return_t ret;
1577
1578   callback_args.print_fh = open_print_dest(print_args->to_file,
1579                                            print_args->dest);
1580   if (callback_args.print_fh == NULL)
1581     return PP_OPEN_ERROR;       /* attempt to open destination failed */
1582
1583   print_preamble(callback_args.print_fh, print_args->format);
1584   if (ferror(callback_args.print_fh)) {
1585     close_print_dest(print_args->to_file, callback_args.print_fh);
1586     return PP_WRITE_ERROR;
1587   }
1588
1589   callback_args.print_args = print_args;
1590   callback_args.print_separator = FALSE;
1591   callback_args.line_buf = NULL;
1592   callback_args.line_buf_len = 256;
1593   callback_args.col_widths = NULL;
1594   if (print_args->print_summary) {
1595     /* We're printing packet summaries.  Allocate the line buffer at
1596        its initial length. */
1597     callback_args.line_buf = g_malloc(callback_args.line_buf_len + 1);
1598
1599     /* Find the widths for each of the columns - maximum of the
1600        width of the title and the width of the data - and print
1601        the column titles. */
1602     callback_args.col_widths = (gint *) g_malloc(sizeof(gint) * cf->cinfo.num_cols);
1603     cp = &callback_args.line_buf[0];
1604     line_len = 0;
1605     for (i = 0; i < cf->cinfo.num_cols; i++) {
1606       /* Don't pad the last column. */
1607       if (i == cf->cinfo.num_cols - 1)
1608         callback_args.col_widths[i] = 0;
1609       else {
1610         callback_args.col_widths[i] = strlen(cf->cinfo.col_title[i]);
1611         data_width = get_column_char_width(get_column_format(i));
1612         if (data_width > callback_args.col_widths[i])
1613           callback_args.col_widths[i] = data_width;
1614       }
1615
1616       /* Find the length of the string for this column. */
1617       column_len = strlen(cf->cinfo.col_title[i]);
1618       if (callback_args.col_widths[i] > column_len)
1619         column_len = callback_args.col_widths[i];
1620
1621       /* Make sure there's room in the line buffer for the column; if not,
1622          double its length. */
1623       line_len += column_len + 1;       /* "+1" for space */
1624       if (line_len > callback_args.line_buf_len) {
1625         cp_off = cp - callback_args.line_buf;
1626         callback_args.line_buf_len = 2 * line_len;
1627         callback_args.line_buf = g_realloc(callback_args.line_buf,
1628                                            callback_args.line_buf_len + 1);
1629         cp = callback_args.line_buf + cp_off;
1630       }
1631
1632       /* Right-justify the packet number column. */
1633       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1634         sprintf(cp, "%*s", callback_args.col_widths[i], cf->cinfo.col_title[i]);
1635       else
1636         sprintf(cp, "%-*s", callback_args.col_widths[i], cf->cinfo.col_title[i]);
1637       cp += column_len;
1638       if (i != cf->cinfo.num_cols - 1)
1639         *cp++ = ' ';
1640     }
1641     *cp = '\0';
1642     print_line(callback_args.print_fh, 0, print_args->format,
1643                callback_args.line_buf);
1644   } /* if (print_summary) */
1645
1646   /* Iterate through the list of packets, printing the packets we were
1647      told to print. */
1648   ret = process_specified_packets(cf, &print_args->range, "Printing",
1649                                   "selected packets", print_packet,
1650                                   &callback_args);
1651
1652   if (callback_args.col_widths != NULL)
1653     g_free(callback_args.col_widths);
1654   if (callback_args.line_buf != NULL)
1655     g_free(callback_args.line_buf);
1656
1657   switch (ret) {
1658
1659   case PSP_FINISHED:
1660     /* Completed successfully. */
1661     break;
1662
1663   case PSP_STOPPED:
1664     /* Well, the user decided to abort the printing.
1665
1666        XXX - note that what got generated before they did that
1667        will get printed if we're piping to a print program; we'd
1668        have to write to a file and then hand that to the print
1669        program to make it actually not print anything. */
1670     break;
1671
1672   case PSP_FAILED:
1673     /* Error while printing.
1674
1675        XXX - note that what got generated before they did that
1676        will get printed if we're piping to a print program; we'd
1677        have to write to a file and then hand that to the print
1678        program to make it actually not print anything. */
1679     close_print_dest(print_args->to_file, callback_args.print_fh);
1680     return PP_WRITE_ERROR;
1681   }
1682
1683   print_finale(callback_args.print_fh, print_args->format);
1684   if (ferror(callback_args.print_fh)) {
1685     close_print_dest(print_args->to_file, callback_args.print_fh);
1686     return PP_WRITE_ERROR;
1687   }
1688
1689   close_print_dest(print_args->to_file, callback_args.print_fh);
1690
1691   return PP_OK;
1692 }
1693
1694 /* Scan through the packet list and change all columns that use the
1695    "command-line-specified" time stamp format to use the current
1696    value of that format. */
1697 void
1698 change_time_formats(capture_file *cf)
1699 {
1700   frame_data *fdata;
1701   progdlg_t  *progbar = NULL;
1702   gboolean    stop_flag;
1703   int         count;
1704   int         row;
1705   int         i;
1706   float       prog_val;
1707   GTimeVal    start_time;
1708   gchar       status_str[100];
1709   int         progbar_nextstep;
1710   int         progbar_quantum;
1711   int         first, last;
1712   gboolean    sorted_by_frame_column;
1713
1714   /* Are there any columns with time stamps in the "command-line-specified"
1715      format?
1716
1717      XXX - we have to force the "column is writable" flag on, as it
1718      might be off from the last frame that was dissected. */
1719   col_set_writable(&cf->cinfo, TRUE);
1720   if (!check_col(&cf->cinfo, COL_CLS_TIME)) {
1721     /* No, there aren't any columns in that format, so we have no work
1722        to do. */
1723     return;
1724   }
1725   first = cf->cinfo.col_first[COL_CLS_TIME];
1726   g_assert(first >= 0);
1727   last = cf->cinfo.col_last[COL_CLS_TIME];
1728
1729   /* Freeze the packet list while we redo it, so we don't get any
1730      screen updates while it happens. */
1731   packet_list_freeze();
1732
1733   /* Update the progress bar when it gets to this value. */
1734   progbar_nextstep = 0;
1735   /* When we reach the value that triggers a progress bar update,
1736      bump that value by this amount. */
1737   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1738   /* Count of packets at which we've looked. */
1739   count = 0;
1740
1741   /*  If the rows are currently sorted by the frame column then we know
1742    *  the row number of each packet: it's the row number of the previously
1743    *  displayed packet + 1.
1744    *
1745    *  Otherwise, if the display is sorted by a different column then we have
1746    *  to use the O(N) packet_list_find_row_from_data() (thus making the job
1747    *  of changing the time display format O(N**2)).
1748    *
1749    *  (XXX - In fact it's still O(N**2) because gtk_clist_set_text() takes
1750    *  the row number and walks that many elements down the clist to find
1751    *  the appropriate element.)
1752    */
1753   sorted_by_frame_column = FALSE;
1754   for (i = 0; i < cf->cinfo.num_cols; i++) {
1755     if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1756     {
1757       sorted_by_frame_column = (i == packet_list_get_sort_column());
1758       break;
1759     }
1760   }
1761
1762   stop_flag = FALSE;
1763   g_get_current_time(&start_time);
1764
1765   /* Iterate through the list of packets, checking whether the packet
1766      is in a row of the summary list and, if so, whether there are
1767      any columns that show the time in the "command-line-specified"
1768      format and, if so, update that row. */
1769   for (fdata = cf->plist, row = -1; fdata != NULL; fdata = fdata->next) {
1770     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1771        when we update it, we have to run the GTK+ main loop to get it
1772        to repaint what's pending, and doing so may involve an "ioctl()"
1773        to see if there's any pending input from an X server, and doing
1774        that for every packet can be costly, especially on a big file. */
1775     if (count >= progbar_nextstep) {
1776       /* let's not divide by zero. I should never be started
1777        * with count == 0, so let's assert that
1778        */
1779       g_assert(cf->count > 0);
1780
1781       prog_val = (gfloat) count / cf->count;
1782
1783       if (progbar == NULL)
1784         /* Create the progress bar if necessary */
1785         progbar = delayed_create_progress_dlg("Changing", "time display", 
1786           &stop_flag, &start_time, prog_val);
1787
1788       if (progbar != NULL) {
1789         g_snprintf(status_str, sizeof(status_str),
1790                    "%4u of %u packets", count, cf->count);
1791         update_progress_dlg(progbar, prog_val, status_str);
1792       }
1793
1794       progbar_nextstep += progbar_quantum;
1795     }
1796
1797     if (stop_flag) {
1798       /* Well, the user decided to abort the redisplay.  Just stop.
1799
1800          XXX - this leaves the time field in the old format in
1801          frames we haven't yet processed.  So it goes; should we
1802          simply not offer them the option of stopping? */
1803       break;
1804     }
1805
1806     count++;
1807
1808     /* Find what row this packet is in. */
1809     if (!sorted_by_frame_column) {
1810       /* This function is O(N), so we try to avoid using it... */
1811       row = packet_list_find_row_from_data(fdata);
1812     } else {
1813       /* ...which we do by maintaining a count of packets that are
1814          being displayed (i.e., that have passed the display filter),
1815          and using the current value of that count as the row number
1816          (which is why we can only do it when the display is sorted
1817          by the frame number). */
1818       if (fdata->flags.passed_dfilter)
1819         row++;
1820       else
1821         continue;
1822     }
1823
1824     if (row != -1) {
1825       /* This packet is in the summary list, on row "row". */
1826
1827       for (i = first; i <= last; i++) {
1828         if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1829           /* This is one of the columns that shows the time in
1830              "command-line-specified" format; update it. */
1831           cf->cinfo.col_buf[i][0] = '\0';
1832           col_set_cls_time(fdata, &cf->cinfo, i);
1833           packet_list_set_text(row, i, cf->cinfo.col_data[i]);
1834         }
1835       }
1836     }
1837   }
1838
1839   /* We're done redisplaying the packets; destroy the progress bar if it
1840      was created. */
1841   if (progbar != NULL)
1842     destroy_progress_dlg(progbar);
1843
1844   /* Set the column widths of those columns that show the time in
1845      "command-line-specified" format. */
1846   for (i = first; i <= last; i++) {
1847     if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1848       packet_list_set_cls_time_width(i);
1849     }
1850   }
1851
1852   /* Unfreeze the packet list. */
1853   packet_list_thaw();
1854 }
1855
1856 typedef struct {
1857         const char      *string;
1858         size_t          string_len;
1859         capture_file    *cf;
1860         gboolean        frame_matched;
1861 } match_data;
1862
1863 gboolean
1864 find_packet_protocol_tree(capture_file *cf, const char *string)
1865 {
1866   match_data            mdata;
1867
1868   mdata.string = string;
1869   mdata.string_len = strlen(string);
1870   return find_packet(cf, match_protocol_tree, &mdata);
1871 }
1872
1873 static gboolean
1874 match_protocol_tree(capture_file *cf, frame_data *fdata, void *criterion)
1875 {
1876   match_data            *mdata = criterion;
1877   epan_dissect_t        *edt;
1878
1879   /* Construct the protocol tree, including the displayed text */
1880   edt = epan_dissect_new(TRUE, TRUE);
1881   /* We don't need the column information */
1882   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1883
1884   /* Iterate through all the nodes, seeing if they have text that matches. */
1885   mdata->cf = cf;
1886   mdata->frame_matched = FALSE;
1887   proto_tree_children_foreach(edt->tree, match_subtree_text, mdata);
1888   epan_dissect_free(edt);
1889   return mdata->frame_matched;
1890 }
1891
1892 static void
1893 match_subtree_text(proto_node *node, gpointer data)
1894 {
1895   match_data    *mdata = (match_data*) data;
1896   const gchar   *string = mdata->string;
1897   size_t        string_len = mdata->string_len;
1898   capture_file  *cf = mdata->cf;
1899   field_info    *fi = PITEM_FINFO(node);
1900   gchar         label_str[ITEM_LABEL_LENGTH];
1901   gchar         *label_ptr;
1902   size_t        label_len;
1903   guint32       i;
1904   guint8        c_char;
1905   size_t        c_match = 0;
1906
1907   if (mdata->frame_matched) {
1908     /* We already had a match; don't bother doing any more work. */
1909     return;
1910   }
1911
1912   /* Don't match invisible entries. */
1913   if (!fi->visible)
1914     return;
1915
1916   /* was a free format label produced? */
1917   if (fi->rep) {
1918     label_ptr = fi->rep->representation;
1919   } else {
1920     /* no, make a generic label */
1921     label_ptr = label_str;
1922     proto_item_fill_label(fi, label_str);
1923   }
1924     
1925   /* Does that label match? */
1926   label_len = strlen(label_ptr);
1927   for (i = 0; i < label_len; i++) {
1928     c_char = label_ptr[i];
1929     if (cf->case_type)
1930       c_char = toupper(c_char);
1931     if (c_char == string[c_match]) {
1932       c_match++;
1933       if (c_match == string_len) {
1934         /* No need to look further; we have a match */
1935         mdata->frame_matched = TRUE;
1936         return;
1937       }
1938     } else
1939       c_match = 0;
1940   }
1941   
1942   /* Recurse into the subtree, if it exists */
1943   if (node->first_child != NULL)
1944     proto_tree_children_foreach(node, match_subtree_text, mdata);
1945 }
1946
1947 gboolean
1948 find_packet_summary_line(capture_file *cf, const char *string)
1949 {
1950   match_data            mdata;
1951
1952   mdata.string = string;
1953   mdata.string_len = strlen(string);
1954   return find_packet(cf, match_summary_line, &mdata);
1955 }
1956
1957 static gboolean
1958 match_summary_line(capture_file *cf, frame_data *fdata, void *criterion)
1959 {
1960   match_data            *mdata = criterion;
1961   const gchar           *string = mdata->string;
1962   size_t                string_len = mdata->string_len;
1963   epan_dissect_t        *edt;
1964   const char            *info_column;
1965   size_t                info_column_len;
1966   gboolean              frame_matched = FALSE;
1967   gint                  colx;
1968   guint32               i;
1969   guint8                c_char;
1970   size_t                c_match = 0;
1971
1972   /* Don't bother constructing the protocol tree */
1973   edt = epan_dissect_new(FALSE, FALSE);
1974   /* Get the column information */
1975   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
1976
1977   /* Find the Info column */
1978   for (colx = 0; colx < cf->cinfo.num_cols; colx++) {
1979     if (cf->cinfo.fmt_matx[colx][COL_INFO]) {
1980       /* Found it.  See if we match. */
1981       info_column = edt->pi.cinfo->col_data[colx];
1982       info_column_len = strlen(info_column);
1983       for (i = 0; i < info_column_len; i++) {
1984         c_char = info_column[i];
1985         if (cf->case_type)
1986           c_char = toupper(c_char);
1987         if (c_char == string[c_match]) {
1988           c_match++;
1989           if (c_match == string_len) {
1990             frame_matched = TRUE;
1991             break;
1992           }
1993         } else
1994           c_match = 0;
1995       }
1996       break;
1997     }
1998   }
1999   epan_dissect_free(edt);
2000   return frame_matched;
2001 }
2002
2003 typedef struct {
2004         const guint8 *data;
2005         size_t data_len;
2006 } cbs_t;        /* "Counted byte string" */
2007
2008 gboolean
2009 find_packet_data(capture_file *cf, const guint8 *string, size_t string_size)
2010 {
2011   cbs_t info;
2012
2013   info.data = string;
2014   info.data_len = string_size;
2015
2016   /* String or hex search? */
2017   if (cf->ascii) {
2018     /* String search - what type of string? */
2019     switch (cf->scs_type) {
2020
2021     case SCS_ASCII_AND_UNICODE:
2022       return find_packet(cf, match_ascii_and_unicode, &info);
2023
2024     case SCS_ASCII:
2025       return find_packet(cf, match_ascii, &info);
2026
2027     case SCS_UNICODE:
2028       return find_packet(cf, match_unicode, &info);
2029
2030     default:
2031       g_assert_not_reached();
2032       return FALSE;
2033     }
2034   } else
2035     return find_packet(cf, match_binary, &info);
2036 }
2037
2038 static gboolean
2039 match_ascii_and_unicode(capture_file *cf, frame_data *fdata, void *criterion)
2040 {
2041   cbs_t         *info = criterion;
2042   const char    *ascii_text = info->data;
2043   size_t        textlen = info->data_len;
2044   gboolean      frame_matched;
2045   guint32       buf_len;
2046   guint32       i;
2047   guint8        c_char;
2048   size_t        c_match = 0;
2049
2050   frame_matched = FALSE;
2051   buf_len = fdata->pkt_len;
2052   for (i = 0; i < buf_len; i++) {
2053     c_char = cf->pd[i];
2054     if (cf->case_type)
2055       c_char = toupper(c_char);
2056     if (c_char != 0) {
2057       if (c_char == ascii_text[c_match]) {
2058         c_match++;
2059         if (c_match == textlen) {
2060           frame_matched = TRUE;
2061           break;
2062         }
2063       } else
2064         c_match = 0;
2065     }
2066   }
2067   return frame_matched;
2068 }
2069
2070 static gboolean
2071 match_ascii(capture_file *cf, frame_data *fdata, void *criterion)
2072 {
2073   cbs_t         *info = criterion;
2074   const char    *ascii_text = info->data;
2075   size_t        textlen = info->data_len;
2076   gboolean      frame_matched;
2077   guint32       buf_len;
2078   guint32       i;
2079   guint8        c_char;
2080   size_t        c_match = 0;
2081
2082   frame_matched = FALSE;
2083   buf_len = fdata->pkt_len;
2084   for (i = 0; i < buf_len; i++) {
2085     c_char = cf->pd[i];
2086     if (cf->case_type)
2087       c_char = toupper(c_char);
2088     if (c_char == ascii_text[c_match]) {
2089       c_match++;
2090       if (c_match == textlen) {
2091         frame_matched = TRUE;
2092         break;
2093       }
2094     } else
2095       c_match = 0;
2096   }
2097   return frame_matched;
2098 }
2099
2100 static gboolean
2101 match_unicode(capture_file *cf, frame_data *fdata, void *criterion)
2102 {
2103   cbs_t         *info = criterion;
2104   const char    *ascii_text = info->data;
2105   size_t        textlen = info->data_len;
2106   gboolean      frame_matched;
2107   guint32       buf_len;
2108   guint32       i;
2109   guint8        c_char;
2110   size_t        c_match = 0;
2111
2112   frame_matched = FALSE;
2113   buf_len = fdata->pkt_len;
2114   for (i = 0; i < buf_len; i++) {
2115     c_char = cf->pd[i];
2116     if (cf->case_type)
2117       c_char = toupper(c_char);
2118     if (c_char == ascii_text[c_match]) {
2119       c_match++;
2120       i++;
2121       if (c_match == textlen) {
2122         frame_matched = TRUE;
2123         break;
2124       }
2125     } else
2126       c_match = 0;
2127   }
2128   return frame_matched;
2129 }
2130
2131 static gboolean
2132 match_binary(capture_file *cf, frame_data *fdata, void *criterion)
2133 {
2134   cbs_t         *info = criterion;
2135   const guint8  *binary_data = info->data;
2136   size_t        datalen = info->data_len;
2137   gboolean      frame_matched;
2138   guint32       buf_len;
2139   guint32       i;
2140   size_t        c_match = 0;
2141
2142   frame_matched = FALSE;
2143   buf_len = fdata->pkt_len;
2144   for (i = 0; i < buf_len; i++) {
2145     if (cf->pd[i] == binary_data[c_match]) {
2146       c_match++;
2147       if (c_match == datalen) {
2148         frame_matched = TRUE;
2149         break;
2150       }
2151     } else
2152       c_match = 0;
2153   }
2154   return frame_matched;
2155 }
2156
2157 gboolean
2158 find_packet_dfilter(capture_file *cf, dfilter_t *sfcode)
2159 {
2160   return find_packet(cf, match_dfilter, sfcode);
2161 }
2162
2163 static gboolean
2164 match_dfilter(capture_file *cf, frame_data *fdata, void *criterion)
2165 {
2166   dfilter_t             *sfcode = criterion;
2167   epan_dissect_t        *edt;
2168   gboolean              frame_matched;
2169
2170   edt = epan_dissect_new(TRUE, FALSE);
2171   epan_dissect_prime_dfilter(edt, sfcode);
2172   epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
2173   frame_matched = dfilter_apply_edt(sfcode, edt);
2174   epan_dissect_free(edt);
2175   return frame_matched;
2176 }
2177
2178 static gboolean
2179 find_packet(capture_file *cf,
2180             gboolean (*match_function)(capture_file *, frame_data *, void *),
2181             void *criterion)
2182 {
2183   frame_data *start_fd;
2184   frame_data *fdata;
2185   frame_data *new_fd = NULL;
2186   progdlg_t  *progbar = NULL;
2187   gboolean    stop_flag;
2188   int         count;
2189   int         err;
2190   gchar      *err_info;
2191   int         row;
2192   float       prog_val;
2193   GTimeVal    start_time;
2194   gchar       status_str[100];
2195   int         progbar_nextstep;
2196   int         progbar_quantum;
2197
2198   start_fd = cf->current_frame;
2199   if (start_fd != NULL)  {
2200     /* Iterate through the list of packets, starting at the packet we've
2201        picked, calling a routine to run the filter on the packet, see if
2202        it matches, and stop if so.  */
2203     count = 0;
2204     fdata = start_fd;
2205
2206     progbar_nextstep = 0;
2207     /* When we reach the value that triggers a progress bar update,
2208        bump that value by this amount. */
2209     progbar_quantum = cf->count/N_PROGBAR_UPDATES;
2210
2211     stop_flag = FALSE;
2212     g_get_current_time(&start_time);
2213
2214     fdata = start_fd;
2215     for (;;) {
2216       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
2217          when we update it, we have to run the GTK+ main loop to get it
2218          to repaint what's pending, and doing so may involve an "ioctl()"
2219          to see if there's any pending input from an X server, and doing
2220          that for every packet can be costly, especially on a big file. */
2221       if (count >= progbar_nextstep) {
2222         /* let's not divide by zero. I should never be started
2223          * with count == 0, so let's assert that
2224          */
2225         g_assert(cf->count > 0);
2226
2227         prog_val = (gfloat) count / cf->count;
2228
2229         /* Create the progress bar if necessary */
2230         if (progbar == NULL)
2231            progbar = delayed_create_progress_dlg("Searching", cf->sfilter, 
2232              &stop_flag, &start_time, prog_val);
2233
2234         if (progbar != NULL) {
2235           g_snprintf(status_str, sizeof(status_str),
2236                      "%4u of %u packets", count, cf->count);
2237           update_progress_dlg(progbar, prog_val, status_str);
2238         }
2239
2240         progbar_nextstep += progbar_quantum;
2241       }
2242
2243       if (stop_flag) {
2244         /* Well, the user decided to abort the search.  Go back to the
2245            frame where we started. */
2246         new_fd = start_fd;
2247         break;
2248       }
2249
2250       /* Go past the current frame. */
2251       if (cf->sbackward) {
2252         /* Go on to the previous frame. */
2253         fdata = fdata->prev;
2254         if (fdata == NULL) {
2255           /*
2256            * XXX - other apps have a bit more of a detailed message
2257            * for this, and instead of offering "OK" and "Cancel",
2258            * they offer things such as "Continue" and "Cancel";
2259            * we need an API for popping up alert boxes with
2260            * {Verb} and "Cancel".
2261            */
2262           simple_dialog(ESD_TYPE_CONFIRMATION, ESD_BTN_OK,
2263                         "You have searched up to the beginning of the capture.\n"
2264                         "Do you want to continue the search from the end of the capture?");
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                         "You have searched up to the end of the capture.\n"
2273                         "Do you want to continue the search from the beginning of the capture?");
2274           fdata = cf->plist;    /* wrap around */
2275         }
2276       }
2277
2278       count++;
2279
2280       /* Is this packet in the display? */
2281       if (fdata->flags.passed_dfilter) {
2282         /* Yes.  Load its data. */
2283         if (!wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
2284                         cf->pd, fdata->cap_len, &err, &err_info)) {
2285           /* Read error.  Report the error, and go back to the frame
2286              where we started. */
2287           simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2288                         cf_read_error_message(err, err_info), cf->filename);
2289           new_fd = start_fd;
2290           break;
2291         }
2292
2293         /* Does it match the search criterion? */
2294         if ((*match_function)(cf, fdata, criterion)) {
2295           new_fd = fdata;
2296           break;        /* found it! */
2297         }
2298       }
2299
2300       if (fdata == start_fd) {
2301         /* We're back to the frame we were on originally, and that frame
2302            doesn't match the search filter.  The search failed. */
2303         break;
2304       }
2305     }
2306
2307     /* We're done scanning the packets; destroy the progress bar if it
2308        was created. */
2309     if (progbar != NULL)
2310       destroy_progress_dlg(progbar);
2311   }
2312
2313   if (new_fd != NULL) {
2314     /* We found a frame.  Find what row it's in. */
2315     row = packet_list_find_row_from_data(new_fd);
2316     g_assert(row != -1);
2317
2318     /* Select that row, make it the focus row, and make it visible. */
2319     packet_list_set_selected_row(row);
2320     return TRUE;        /* success */
2321   } else
2322     return FALSE;       /* failure */
2323 }
2324
2325 gboolean
2326 goto_frame(capture_file *cf, guint fnumber)
2327 {
2328   frame_data *fdata;
2329   int row;
2330
2331   for (fdata = cf->plist; fdata != NULL && fdata->num < fnumber; fdata = fdata->next)
2332     ;
2333
2334   if (fdata == NULL) {
2335     /* we didn't find a packet with that packet number */
2336     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2337                   "There is no packet with that packet number.");
2338     return FALSE;       /* we failed to go to that packet */
2339   }
2340   if (!fdata->flags.passed_dfilter) {
2341     /* that packet currently isn't displayed */
2342     /* XXX - add it to the set of displayed packets? */
2343     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2344                   "That packet is not currently being displayed.");
2345     return FALSE;       /* we failed to go to that packet */
2346   }
2347
2348   /* We found that packet, and it's currently being displayed.
2349      Find what row it's in. */
2350   row = packet_list_find_row_from_data(fdata);
2351   g_assert(row != -1);
2352
2353   /* Select that row, make it the focus row, and make it visible. */
2354   packet_list_set_selected_row(row);
2355   return TRUE;  /* we got to that packet */
2356 }
2357
2358 gboolean
2359 goto_top_frame(capture_file *cf)
2360 {
2361   frame_data *fdata;
2362   int row;
2363   frame_data *lowest_fdata = NULL;
2364
2365   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
2366     if (fdata->flags.passed_dfilter) {
2367         lowest_fdata = fdata;
2368         break;
2369     }
2370   }
2371
2372   if (lowest_fdata == NULL) {
2373       return FALSE;
2374   }
2375
2376   /* We found that packet, and it's currently being displayed.
2377      Find what row it's in. */
2378   row = packet_list_find_row_from_data(lowest_fdata);
2379   g_assert(row != -1);
2380
2381   /* Select that row, make it the focus row, and make it visible. */
2382   packet_list_set_selected_row(row);
2383   return TRUE;  /* we got to that packet */
2384 }
2385
2386 gboolean
2387 goto_bottom_frame(capture_file *cf)
2388 {
2389   frame_data *fdata;
2390   int row;
2391   frame_data *highest_fdata = NULL;
2392
2393   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
2394     if (fdata->flags.passed_dfilter) {
2395         highest_fdata = fdata;
2396     }
2397   }
2398
2399   if (highest_fdata == NULL) {
2400       return FALSE;
2401   }
2402
2403   /* We found that packet, and it's currently being displayed.
2404      Find what row it's in. */
2405   row = packet_list_find_row_from_data(highest_fdata);
2406   g_assert(row != -1);
2407
2408   /* Select that row, make it the focus row, and make it visible. */
2409   packet_list_set_selected_row(row);
2410   return TRUE;  /* we got to that packet */
2411 }
2412
2413 /* Select the packet on a given row. */
2414 void
2415 select_packet(capture_file *cf, int row)
2416 {
2417   frame_data *fdata;
2418   int err;
2419   gchar *err_info;
2420
2421   /* Get the frame data struct pointer for this frame */
2422   fdata = (frame_data *)packet_list_get_row_data(row);
2423
2424   if (fdata == NULL) {
2425     /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
2426        the first entry is added to it by "real_insert_row()", that row
2427        is selected (see "real_insert_row()", in "gtk/gtkclist.c", in both
2428        our version and the vanilla GTK+ version).
2429
2430        This means that a "select-row" signal is emitted; this causes
2431        "packet_list_select_cb()" to be called, which causes "select_packet()"
2432        to be called.
2433
2434        "select_packet()" fetches, above, the data associated with the
2435        row that was selected; however, as "gtk_clist_append()", which
2436        called "real_insert_row()", hasn't yet returned, we haven't yet
2437        associated any data with that row, so we get back a null pointer.
2438
2439        We can't assume that there's only one frame in the frame list,
2440        either, as we may be filtering the display.
2441
2442        We therefore assume that, if "row" is 0, i.e. the first row
2443        is being selected, and "cf->first_displayed" equals
2444        "cf->last_displayed", i.e. there's only one frame being
2445        displayed, that frame is the frame we want.
2446
2447        This means we have to set "cf->first_displayed" and
2448        "cf->last_displayed" before adding the row to the
2449        GtkCList; see the comment in "add_packet_to_packet_list()". */
2450
2451        if (row == 0 && cf->first_displayed == cf->last_displayed)
2452          fdata = cf->first_displayed;
2453   }
2454
2455   /* Get the data in that frame. */
2456   if (!wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
2457                        cf->pd, fdata->cap_len, &err, &err_info)) {
2458     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2459                   cf_read_error_message(err, err_info), cf->filename);
2460     return;
2461   }
2462
2463   /* Record that this frame is the current frame. */
2464   cf->current_frame = fdata;
2465
2466   /* Create the logical protocol tree. */
2467   if (cf->edt != NULL) {
2468     epan_dissect_free(cf->edt);
2469     cf->edt = NULL;
2470   }
2471   /* We don't need the columns here. */
2472   cf->edt = epan_dissect_new(TRUE, TRUE);
2473   epan_dissect_run(cf->edt, &cf->pseudo_header, cf->pd, cf->current_frame,
2474           NULL);
2475
2476   /* Display the GUI protocol tree and hex dump.
2477      XXX - why do we dump core if we call "proto_tree_draw()"
2478      before calling "add_byte_views()"? */
2479   add_main_byte_views(cf->edt);
2480   main_proto_tree_draw(cf->edt->tree);
2481
2482   /* A packet is selected. */
2483   set_menus_for_selected_packet(cf);
2484 }
2485
2486 /* Unselect the selected packet, if any. */
2487 void
2488 unselect_packet(capture_file *cf)
2489 {
2490   /* Destroy the epan_dissect_t for the unselected packet. */
2491   if (cf->edt != NULL) {
2492     epan_dissect_free(cf->edt);
2493     cf->edt = NULL;
2494   }
2495
2496   /* Clear out the display of that packet. */
2497   clear_tree_and_hex_views();
2498
2499   /* No packet is selected. */
2500   cf->current_frame = NULL;
2501   set_menus_for_selected_packet(cf);
2502
2503   /* No protocol tree means no selected field. */
2504   unselect_field(cf);
2505 }
2506
2507 /* Unset the selected protocol tree field, if any. */
2508 void
2509 unselect_field(capture_file *cf)
2510 {
2511   statusbar_pop_field_msg();
2512   cf->finfo_selected = NULL;
2513   set_menus_for_selected_tree_row(cf);
2514 }
2515
2516 /*
2517  * Mark a particular frame.
2518  */
2519 void
2520 mark_frame(capture_file *cf, frame_data *frame)
2521 {
2522   frame->flags.marked = TRUE;
2523   cf->marked_count++;
2524 }
2525
2526 /*
2527  * Unmark a particular frame.
2528  */
2529 void
2530 unmark_frame(capture_file *cf, frame_data *frame)
2531 {
2532   frame->flags.marked = FALSE;
2533   cf->marked_count--;
2534 }
2535
2536 typedef struct {
2537   wtap_dumper *pdh;
2538   const char  *fname;
2539 } save_callback_args_t;
2540
2541 /*
2542  * Save a capture to a file, in a particular format, saving either
2543  * all packets, all currently-displayed packets, or all marked packets.
2544  *
2545  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
2546  * up a message box for the failure.
2547  */
2548 static gboolean
2549 save_packet(capture_file *cf _U_, frame_data *fdata,
2550             union wtap_pseudo_header *pseudo_header, const guint8 *pd,
2551             void *argsp)
2552 {
2553   save_callback_args_t *args = argsp;
2554   struct wtap_pkthdr hdr;
2555   int           err;
2556
2557   /* init the wtap header for saving */
2558   hdr.ts.tv_sec  = fdata->abs_secs;
2559   hdr.ts.tv_usec = fdata->abs_usecs;
2560   hdr.caplen     = fdata->cap_len;
2561   hdr.len        = fdata->pkt_len;
2562   hdr.pkt_encap  = fdata->lnk_t;
2563
2564   /* and save the packet */
2565   if (!wtap_dump(args->pdh, &hdr, pseudo_header, pd, &err)) {
2566     cf_write_failure_alert_box(args->fname, err);
2567     return FALSE;
2568   }
2569   return TRUE;
2570 }
2571
2572 gboolean
2573 cf_save(char *fname, capture_file *cf, packet_range_t *range, guint save_format)
2574 {
2575   gchar        *from_filename;
2576   gchar        *name_ptr, *save_msg, *save_fmt = " Saving: %s...";
2577   size_t        msg_len;
2578   int           err;
2579   gboolean      do_copy;
2580   wtap_dumper  *pdh;
2581   struct stat   infile, outfile;
2582   save_callback_args_t callback_args;
2583
2584   name_ptr = get_basename(fname);
2585   msg_len = strlen(name_ptr) + strlen(save_fmt) + 2;
2586   save_msg = g_malloc(msg_len);
2587   snprintf(save_msg, msg_len, save_fmt, name_ptr);
2588   statusbar_push_file_msg(save_msg);
2589   g_free(save_msg);
2590
2591   /*
2592    * Check that the from file is not the same as to file
2593    * We do it here so we catch all cases ...
2594    * Unfortunately, the file requester gives us an absolute file
2595    * name and the read file name may be relative (if supplied on
2596    * the command line). From Joerg Mayer.
2597    *
2598    * This is a bit tricky on win32. The st_ino field is documented as:
2599    * "The inode, and therefore st_ino, has no meaning in the FAT, ..."
2600    * but it *is* set to zero if stat() returns without an error,
2601    * so this is working, but maybe not quite the way expected. ULFL
2602    */
2603    infile.st_ino = 1;   /* These prevent us from getting equality         */
2604    outfile.st_ino = 2;  /* If one or other of the files is not accessible */
2605    stat(cf->filename, &infile);
2606    stat(fname, &outfile);
2607    if (infile.st_ino == outfile.st_ino) {
2608     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2609       "%sCapture file: \"%s\" already exists!%s\n\n"
2610       "Please choose a different filename.",
2611       simple_dialog_primary_start(), fname, simple_dialog_primary_end());
2612     goto fail;
2613   }
2614
2615   packet_range_process_init(range);
2616
2617   /* Used to be :
2618    * if (!save_filtered && !save_marked && !save_manual_range && 
2619    *     !save_marked_range && !save_curr && save_format == cf->cd_t) {
2620    */ 
2621         
2622   if (packet_range_process_all(range) && save_format == cf->cd_t) {
2623     /* We're not filtering packets, and we're saving it in the format
2624        it's already in, so we can just move or copy the raw data. */
2625
2626     if (cf->is_tempfile) {
2627       /* The file being saved is a temporary file from a live
2628          capture, so it doesn't need to stay around under that name;
2629          first, try renaming the capture buffer file to the new name. */
2630 #ifndef WIN32
2631       if (rename(cf->filename, fname) == 0) {
2632         /* That succeeded - there's no need to copy the source file. */
2633         from_filename = NULL;
2634         do_copy = FALSE;
2635       } else {
2636         if (errno == EXDEV) {
2637           /* They're on different file systems, so we have to copy the
2638              file. */
2639           do_copy = TRUE;
2640           from_filename = cf->filename;
2641         } else {
2642           /* The rename failed, but not because they're on different
2643              file systems - put up an error message.  (Or should we
2644              just punt and try to copy?  The only reason why I'd
2645              expect the rename to fail and the copy to succeed would
2646              be if we didn't have permission to remove the file from
2647              the temporary directory, and that might be fixable - but
2648              is it worth requiring the user to go off and fix it?) */
2649           simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2650                                 file_rename_error_message(errno), fname);
2651           goto fail;
2652         }
2653       }
2654 #else
2655       do_copy = TRUE;
2656       from_filename = cf->filename;
2657 #endif
2658     } else {
2659       /* It's a permanent file, so we should copy it, and not remove the
2660          original. */
2661       do_copy = TRUE;
2662       from_filename = cf->filename;
2663     }
2664
2665     if (do_copy) {
2666       /* Copy the file, if we haven't moved it. */
2667       if (!copy_binary_file(from_filename, fname))
2668         goto fail;
2669     }
2670   } else {
2671     /* Either we're filtering packets, or we're saving in a different
2672        format; we can't do that by copying or moving the capture file,
2673        we have to do it by writing the packets out in Wiretap. */
2674     pdh = wtap_dump_open(fname, save_format, cf->lnk_t, cf->snap, &err);
2675     if (pdh == NULL) {
2676       cf_open_failure_alert_box(fname, err, NULL, TRUE, save_format);
2677       goto fail;
2678     }
2679
2680     /* XXX - we let the user save a subset of the packets.
2681
2682        If we do that, should we make that file the current file?  If so,
2683        it means we can no longer get at the other packets.  What does
2684        NetMon do? */
2685
2686     /* Iterate through the list of packets, processing the packets we were
2687        told to process.
2688
2689        XXX - we've already called "packet_range_process_init(range)", but
2690        "process_specified_packets()" will do it again.  Fortunately,
2691        that's harmless in this case, as we haven't done anything to
2692        "range" since we initialized it. */
2693     callback_args.pdh = pdh;
2694     callback_args.fname = fname;
2695     switch (process_specified_packets(cf, range, "Saving",
2696                                       "selected packets", save_packet,
2697                                       &callback_args)) {
2698
2699     case PSP_FINISHED:
2700       /* Completed successfully. */
2701       break;
2702
2703     case PSP_STOPPED:
2704       /* The user decided to abort the saving.
2705          XXX - remove the output file? */
2706       break;
2707
2708     case PSP_FAILED:
2709       /* Error while saving. */
2710       wtap_dump_close(pdh, &err);
2711       goto fail;
2712     }
2713
2714     if (!wtap_dump_close(pdh, &err)) {
2715       cf_close_failure_alert_box(fname, err);
2716       goto fail;
2717     }
2718   }
2719
2720   /* Pop the "Saving:" message off the status bar. */
2721   statusbar_pop_file_msg();
2722
2723   if (packet_range_process_all(range)) {
2724     /* We saved the entire capture, not just some packets from it.
2725        Open and read the file we saved it to.
2726
2727        XXX - this is somewhat of a waste; we already have the
2728        packets, all this gets us is updated file type information
2729        (which we could just stuff into "cf"), and having the new
2730        file be the one we have opened and from which we're reading
2731        the data, and it means we have to spend time opening and
2732        reading the file, which could be a significant amount of
2733        time if the file is large. */
2734     cf->user_saved = TRUE;
2735
2736     if ((err = cf_open(fname, FALSE, cf)) == 0) {
2737       /* XXX - report errors if this fails?
2738          What should we return if it fails or is aborted? */
2739       switch (cf_read(cf)) {
2740
2741       case READ_SUCCESS:
2742       case READ_ERROR:
2743         /* Just because we got an error, that doesn't mean we were unable
2744            to read any of the file; we handle what we could get from the
2745            file. */
2746         break;
2747
2748       case READ_ABORTED:
2749         /* The user bailed out of re-reading the capture file; the
2750            capture file has been closed - just return (without
2751            changing any menu settings; "cf_close()" set them
2752            correctly for the "no capture file open" state). */
2753         break;
2754       }
2755       set_menus_for_unsaved_capture_file(FALSE);
2756     }
2757   }
2758   return TRUE;
2759
2760 fail:
2761   /* Pop the "Saving:" message off the status bar. */
2762   statusbar_pop_file_msg();
2763   return FALSE;
2764 }
2765
2766 static void
2767 cf_open_failure_alert_box(const char *filename, int err, gchar *err_info,
2768                           gboolean for_writing, int file_type)
2769 {
2770   if (err < 0) {
2771     /* Wiretap error. */
2772     switch (err) {
2773
2774     case WTAP_ERR_NOT_REGULAR_FILE:
2775       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2776                     "The file \"%s\" is a \"special file\" or socket or other non-regular file.",
2777                     filename);
2778       break;
2779
2780     case WTAP_ERR_RANDOM_OPEN_PIPE:
2781       /* Seen only when opening a capture file for reading. */
2782       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2783                     "The file \"%s\" is a pipe or FIFO; Ethereal cannot read pipe or FIFO files.",
2784                     filename);
2785       break;
2786
2787     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
2788       /* Seen only when opening a capture file for reading. */
2789       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2790                     "The file \"%s\" is not a capture file in a format Ethereal understands.",
2791                     filename);
2792       break;
2793
2794     case WTAP_ERR_UNSUPPORTED:
2795       /* Seen only when opening a capture file for reading. */
2796       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2797                     "The file \"%s\" is not a capture file in a format Ethereal understands.\n"
2798                     "(%s)",
2799                     filename, err_info);
2800       g_free(err_info);
2801       break;
2802
2803     case WTAP_ERR_CANT_WRITE_TO_PIPE:
2804       /* Seen only when opening a capture file for writing. */
2805       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2806                     "The file \"%s\" is a pipe, and %s capture files cannot be "
2807                     "written to a pipe.",
2808                     filename, wtap_file_type_string(file_type));
2809       break;
2810
2811     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2812       /* Seen only when opening a capture file for writing. */
2813       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2814                     "Ethereal does not support writing capture files in that format.");
2815       break;
2816
2817     case WTAP_ERR_UNSUPPORTED_ENCAP:
2818       if (for_writing) {
2819         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2820                       "Ethereal cannot save this capture in that format.");
2821       } else {
2822         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2823                       "The file \"%s\" is a capture for a network type that Ethereal doesn't support.\n"
2824                       "(%s)",
2825                       filename, err_info);
2826         g_free(err_info);
2827       }
2828       break;
2829
2830     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2831       if (for_writing) {
2832         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2833                       "Ethereal cannot save this capture in that format.");
2834       } else {
2835         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2836                       "The file \"%s\" is a capture for a network type that Ethereal doesn't support.",
2837                       filename);
2838       }
2839       break;
2840
2841     case WTAP_ERR_BAD_RECORD:
2842       /* Seen only when opening a capture file for reading. */
2843       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2844                     "The file \"%s\" appears to be damaged or corrupt.\n"
2845                     "(%s)",
2846                     filename, err_info);
2847       g_free(err_info);
2848       break;
2849
2850     case WTAP_ERR_CANT_OPEN:
2851       if (for_writing) {
2852         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2853                       "The file \"%s\" could not be created for some unknown reason.",
2854                       filename);
2855       } else {
2856         simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2857                       "The file \"%s\" could not be opened for some unknown reason.",
2858                       filename);
2859       }
2860       break;
2861
2862     case WTAP_ERR_SHORT_READ:
2863       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2864                     "The file \"%s\" appears to have been cut short"
2865                     " in the middle of a packet or other data.",
2866                     filename);
2867       break;
2868
2869     case WTAP_ERR_SHORT_WRITE:
2870       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2871                     "A full header couldn't be written to the file \"%s\".",
2872                     filename);
2873       break;
2874
2875     default:
2876       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2877                     "The file \"%s\" could not be %s: %s.",
2878                     filename,
2879                     for_writing ? "created" : "opened",
2880                     wtap_strerror(err));
2881       break;
2882     }
2883   } else {
2884     /* OS error. */
2885     open_failure_alert_box(filename, err, for_writing);
2886   }
2887 }
2888
2889 static char *
2890 file_rename_error_message(int err)
2891 {
2892   char *errmsg;
2893   static char errmsg_errno[1024+1];
2894
2895   switch (err) {
2896
2897   case ENOENT:
2898     errmsg = "The path to the file \"%s\" does not exist.";
2899     break;
2900
2901   case EACCES:
2902     errmsg = "You do not have permission to move the capture file to \"%s\".";
2903     break;
2904
2905   default:
2906     snprintf(errmsg_errno, sizeof(errmsg_errno),
2907                     "The file \"%%s\" could not be moved: %s.",
2908                                 wtap_strerror(err));
2909     errmsg = errmsg_errno;
2910     break;
2911   }
2912   return errmsg;
2913 }
2914
2915 char *
2916 cf_read_error_message(int err, gchar *err_info)
2917 {
2918   static char errmsg_errno[1024+1];
2919
2920   switch (err) {
2921
2922   case WTAP_ERR_UNSUPPORTED:
2923   case WTAP_ERR_UNSUPPORTED_ENCAP:
2924   case WTAP_ERR_BAD_RECORD:
2925     snprintf(errmsg_errno, sizeof(errmsg_errno),
2926              "An error occurred while reading from the file \"%%s\": %s.\n(%s)",
2927              wtap_strerror(err), err_info);
2928     break;
2929
2930   default:
2931     snprintf(errmsg_errno, sizeof(errmsg_errno),
2932              "An error occurred while reading from the file \"%%s\": %s.",
2933              wtap_strerror(err));
2934     break;
2935   }
2936   return errmsg_errno;
2937 }
2938
2939 static void
2940 cf_write_failure_alert_box(const char *filename, int err)
2941 {
2942   if (err < 0) {
2943     /* Wiretap error. */
2944     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2945                   "An error occurred while writing to the file \"%s\": %s.",
2946                   filename, wtap_strerror(err));
2947   } else {
2948     /* OS error. */
2949     write_failure_alert_box(filename, err);
2950   }
2951 }
2952
2953 /* Check for write errors - if the file is being written to an NFS server,
2954    a write error may not show up until the file is closed, as NFS clients
2955    might not send writes to the server until the "write()" call finishes,
2956    so that the write may fail on the server but the "write()" may succeed. */
2957 static void
2958 cf_close_failure_alert_box(const char *filename, int err)
2959 {
2960   if (err < 0) {
2961     /* Wiretap error. */
2962     switch (err) {
2963
2964     case WTAP_ERR_CANT_CLOSE:
2965       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2966                     "The file \"%s\" couldn't be closed for some unknown reason.",
2967                     filename);
2968       break;
2969
2970     case WTAP_ERR_SHORT_WRITE:
2971       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2972                     "Not all the packets could be written to the file \"%s\".",
2973                     filename);
2974       break;
2975
2976     default:
2977       simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
2978                     "An error occurred while closing the file \"%s\": %s.",
2979                     filename, wtap_strerror(err));
2980       break;
2981     }
2982   } else {
2983     /* OS error.
2984        We assume that a close error from the OS is really a write error. */
2985     write_failure_alert_box(filename, err);
2986   }
2987 }
2988
2989
2990 /* Copies a file in binary mode, for those operating systems that care about
2991  * such things.
2992  * Returns TRUE on success, FALSE on failure. If a failure, it also
2993  * displays a simple dialog window with the error message.
2994  */
2995 static gboolean
2996 copy_binary_file(char *from_filename, char *to_filename)
2997 {
2998   int           from_fd, to_fd, nread, nwritten, err;
2999   guint8        pd[65536];
3000
3001   /* Copy the raw bytes of the file. */
3002   from_fd = open(from_filename, O_RDONLY | O_BINARY);
3003   if (from_fd < 0) {
3004     open_failure_alert_box(from_filename, errno, FALSE);
3005     goto done;
3006   }
3007
3008   /* Use open() instead of creat() so that we can pass the O_BINARY
3009      flag, which is relevant on Win32; it appears that "creat()"
3010      may open the file in text mode, not binary mode, but we want
3011      to copy the raw bytes of the file, so we need the output file
3012      to be open in binary mode. */
3013   to_fd = open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
3014   if (to_fd < 0) {
3015     open_failure_alert_box(to_filename, errno, TRUE);
3016     close(from_fd);
3017     goto done;
3018   }
3019
3020   while ((nread = read(from_fd, pd, sizeof pd)) > 0) {
3021     nwritten = write(to_fd, pd, nread);
3022     if (nwritten < nread) {
3023       if (nwritten < 0)
3024         err = errno;
3025       else
3026         err = WTAP_ERR_SHORT_WRITE;
3027       write_failure_alert_box(to_filename, err);
3028       close(from_fd);
3029       close(to_fd);
3030       goto done;
3031     }
3032   }
3033   if (nread < 0) {
3034     err = errno;
3035     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
3036                   "An error occurred while reading from the file \"%s\": %s.",
3037                   from_filename, strerror(err));
3038     close(from_fd);
3039     close(to_fd);
3040     goto done;
3041   }
3042   close(from_fd);
3043   if (close(to_fd) < 0) {
3044     write_failure_alert_box(to_filename, errno);
3045     goto done;
3046   }
3047
3048   return TRUE;
3049
3050 done:
3051   return FALSE;
3052 }