Fix the problems WRT overwriting a capture file. From Joerg Mayer.
[metze/wireshark/wip.git] / file.c
1 /* file.c
2  * File I/O routines
3  *
4  * $Id: file.c,v 1.283 2002/07/21 16:54:22 sharpe 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 #include <gtk/gtk.h>
30
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34
35 #include <time.h>
36
37 #ifdef HAVE_IO_H
38 #include <io.h>
39 #endif
40
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <errno.h>
45 #include <signal.h>
46
47 #ifdef HAVE_SYS_STAT_H
48 #include <sys/stat.h>
49 #endif
50
51 #ifdef HAVE_FCNTL_H
52 #include <fcntl.h>
53 #endif
54
55 #ifdef NEED_SNPRINTF_H
56 # include "snprintf.h"
57 #endif
58
59 #ifdef NEED_STRERROR_H
60 #include "strerror.h"
61 #endif
62
63 #ifdef HAVE_SYS_TYPES_H
64 # include <sys/types.h>
65 #endif
66
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
69 #endif
70
71 #include <epan/epan.h>
72 #include <epan/filesystem.h>
73
74 #include "gtk/main.h"
75 #include "color.h"
76 #include "gtk/color_utils.h"
77 #include "column.h"
78 #include <epan/packet.h>
79 #include "print.h"
80 #include "file.h"
81 #include "menu.h"
82 #include "util.h"
83 #include "simple_dialog.h"
84 #include "progress_dlg.h"
85 #include "ui_util.h"
86 #include "statusbar.h"
87 #include "prefs.h"
88 #include "gtk/proto_draw.h"
89 #include "gtk/packet_win.h"
90 #include <epan/dfilter/dfilter.h>
91 #include <epan/conversation.h>
92 #include "globals.h"
93 #include "gtk/colors.h"
94 #include <epan/epan_dissect.h>
95
96 extern GtkWidget *packet_list, *byte_nb_ptr, *tree_view;
97
98 #ifdef HAVE_LIBPCAP
99 gboolean auto_scroll_live;
100 #endif
101
102 static guint32 firstsec, firstusec;
103 static guint32 prevsec, prevusec;
104
105 static void read_packet(capture_file *cf, long offset);
106
107 static void rescan_packets(capture_file *cf, const char *action,
108         gboolean refilter, gboolean redissect);
109
110 static void set_selected_row(int row);
111
112 static void freeze_clist(capture_file *cf);
113 static void thaw_clist(capture_file *cf);
114
115 static char *file_rename_error_message(int err);
116 static char *file_close_error_message(int err);
117 static gboolean copy_binary_file(char *from_filename, char *to_filename);
118
119 /* Update the progress bar this many times when reading a file. */
120 #define N_PROGBAR_UPDATES       100
121
122 /* Number of "frame_data" structures per memory chunk.
123    XXX - is this the right number? */
124 #define FRAME_DATA_CHUNK_SIZE   1024
125
126 int
127 open_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
128 {
129   wtap       *wth;
130   int         err;
131   int         fd;
132   struct stat cf_stat;
133
134   wth = wtap_open_offline(fname, &err, TRUE);
135   if (wth == NULL)
136     goto fail;
137
138   /* Find the size of the file. */
139   fd = wtap_fd(wth);
140   if (fstat(fd, &cf_stat) < 0) {
141     err = errno;
142     wtap_close(wth);
143     goto fail;
144   }
145
146   /* The open succeeded.  Close whatever capture file we had open,
147      and fill in the information for this file. */
148   close_cap_file(cf);
149
150   /* Initialize all data structures used for dissection. */
151   init_dissection();
152
153   /* We're about to start reading the file. */
154   cf->state = FILE_READ_IN_PROGRESS;
155
156   cf->wth = wth;
157   cf->filed = fd;
158   cf->f_len = cf_stat.st_size;
159
160   /* Set the file name because we need it to set the follow stream filter.
161      XXX - is that still true?  We need it for other reasons, though,
162      in any case. */
163   cf->filename = g_strdup(fname);
164
165   /* Indicate whether it's a permanent or temporary file. */
166   cf->is_tempfile = is_tempfile;
167
168   /* If it's a temporary capture buffer file, mark it as not saved. */
169   cf->user_saved = !is_tempfile;
170
171   cf->cd_t      = wtap_file_type(cf->wth);
172   cf->count     = 0;
173   cf->marked_count = 0;
174   cf->drops_known = FALSE;
175   cf->drops     = 0;
176   cf->esec      = 0;
177   cf->eusec     = 0;
178   cf->snap      = wtap_snapshot_length(cf->wth);
179   if (cf->snap == 0) {
180     /* Snapshot length not known. */
181     cf->has_snap = FALSE;
182     cf->snap = WTAP_MAX_PACKET_SIZE;
183   } else
184     cf->has_snap = TRUE;
185   cf->progbar_quantum = 0;
186   cf->progbar_nextstep = 0;
187   firstsec = 0, firstusec = 0;
188   prevsec = 0, prevusec = 0;
189  
190   cf->plist_chunk = g_mem_chunk_new("frame_data_chunk",
191         sizeof(frame_data),
192         FRAME_DATA_CHUNK_SIZE * sizeof(frame_data),
193         G_ALLOC_AND_FREE);
194   g_assert(cf->plist_chunk);
195
196   return (0);
197
198 fail:
199   simple_dialog(ESD_TYPE_CRIT, NULL,
200                         file_open_error_message(err, FALSE, 0), fname);
201   return (err);
202 }
203
204 /* Reset everything to a pristine state */
205 void
206 close_cap_file(capture_file *cf)
207 {
208   /* Die if we're in the middle of reading a file. */
209   g_assert(cf->state != FILE_READ_IN_PROGRESS);
210
211   /* Destroy all popup packet windows, as they refer to packets in the
212      capture file we're closing. */
213   destroy_packet_wins();
214
215   if (cf->wth) {
216     wtap_close(cf->wth);
217     cf->wth = NULL;
218   }
219   /* We have no file open... */
220   if (cf->filename != NULL) {
221     /* If it's a temporary file, remove it. */
222     if (cf->is_tempfile)
223       unlink(cf->filename);
224     g_free(cf->filename);
225     cf->filename = NULL;
226   }
227   /* ...which means we have nothing to save. */
228   cf->user_saved = FALSE;
229
230   if (cf->plist_chunk != NULL) {
231     g_mem_chunk_destroy(cf->plist_chunk);
232     cf->plist_chunk = NULL;
233   }
234   if (cf->rfcode != NULL) {
235     dfilter_free(cf->rfcode);
236     cf->rfcode = NULL;
237   }
238   cf->plist = NULL;
239   cf->plist_end = NULL;
240   unselect_packet(cf);  /* nothing to select */
241   cf->first_displayed = NULL;
242   cf->last_displayed = NULL;
243
244   /* Clear the packet list. */
245   gtk_clist_freeze(GTK_CLIST(packet_list));
246   gtk_clist_clear(GTK_CLIST(packet_list));
247   gtk_clist_thaw(GTK_CLIST(packet_list));
248
249   /* Clear any file-related status bar messages.
250      XXX - should be "clear *ALL* file-related status bar messages;
251      will there ever be more than one on the stack? */
252   statusbar_pop_file_msg();
253
254   /* Restore the standard title bar message. */
255   set_main_window_name("The Ethereal Network Analyzer");
256
257   /* Disable all menu items that make sense only if you have a capture. */
258   set_menus_for_capture_file(FALSE);
259   set_menus_for_unsaved_capture_file(FALSE);
260   set_menus_for_captured_packets(FALSE);
261   set_menus_for_selected_packet(FALSE);
262   set_menus_for_capture_in_progress(FALSE);
263   set_menus_for_selected_tree_row(FALSE);
264
265   /* We have no file open. */
266   cf->state = FILE_CLOSED;
267 }
268
269 /* Set the file name in the status line, in the name for the main window,
270    and in the name for the main window's icon. */
271 static void
272 set_display_filename(capture_file *cf)
273 {
274   gchar  *name_ptr;
275   size_t  msg_len;
276   static const gchar done_fmt_nodrops[] = " File: %s";
277   static const gchar done_fmt_drops[] = " File: %s  Drops: %u";
278   gchar  *done_msg;
279   gchar  *win_name_fmt = "%s - Ethereal";
280   gchar  *win_name;
281
282   if (!cf->is_tempfile) {
283     /* Get the last component of the file name, and put that in the
284        status bar. */
285     name_ptr = get_basename(cf->filename);
286   } else {
287     /* The file we read is a temporary file from a live capture;
288        we don't mention its name in the status bar. */
289     name_ptr = "<capture>";
290   }
291
292   if (cf->drops_known) {
293     msg_len = strlen(name_ptr) + strlen(done_fmt_drops) + 64;
294     done_msg = g_malloc(msg_len);
295     snprintf(done_msg, msg_len, done_fmt_drops, name_ptr, cf->drops);
296   } else {
297     msg_len = strlen(name_ptr) + strlen(done_fmt_nodrops);
298     done_msg = g_malloc(msg_len);
299     snprintf(done_msg, msg_len, done_fmt_nodrops, name_ptr);
300   }
301   statusbar_push_file_msg(done_msg);
302   g_free(done_msg);
303
304   msg_len = strlen(name_ptr) + strlen(win_name_fmt) + 1;
305   win_name = g_malloc(msg_len);
306   snprintf(win_name, msg_len, win_name_fmt, name_ptr);
307   set_main_window_name(win_name);
308   g_free(win_name);
309 }
310
311 read_status_t
312 read_cap_file(capture_file *cf, int *err)
313 {
314   gchar      *name_ptr, *load_msg, *load_fmt = " Loading: %s...";
315   size_t      msg_len;
316   char       *errmsg;
317   char        errmsg_errno[1024+1];
318   gchar       err_str[2048+1];
319   long        data_offset;
320   progdlg_t  *progbar;
321   gboolean    stop_flag;
322   int         file_pos;
323   float       prog_val;
324   int         fd;
325   struct stat cf_stat;
326
327   name_ptr = get_basename(cf->filename);
328
329   msg_len = strlen(name_ptr) + strlen(load_fmt) + 2;
330   load_msg = g_malloc(msg_len);
331   snprintf(load_msg, msg_len, load_fmt, name_ptr);
332   statusbar_push_file_msg(load_msg);
333
334   /* Update the progress bar when it gets to this value. */
335   cf->progbar_nextstep = 0;
336   /* When we reach the value that triggers a progress bar update,
337      bump that value by this amount. */
338   cf->progbar_quantum = cf->f_len/N_PROGBAR_UPDATES;
339
340 #ifndef O_BINARY
341 #define O_BINARY        0
342 #endif
343
344   freeze_clist(cf);
345
346   stop_flag = FALSE;
347   progbar = create_progress_dlg(load_msg, "Stop", &stop_flag);
348   g_free(load_msg);
349
350   while ((wtap_read(cf->wth, err, &data_offset))) {
351     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
352        when we update it, we have to run the GTK+ main loop to get it
353        to repaint what's pending, and doing so may involve an "ioctl()"
354        to see if there's any pending input from an X server, and doing
355        that for every packet can be costly, especially on a big file. */
356     if (data_offset >= cf->progbar_nextstep) {
357         file_pos = lseek(cf->filed, 0, SEEK_CUR);
358         prog_val = (gfloat) file_pos / (gfloat) cf->f_len;
359         if (prog_val > 1.0) {
360           /* The file probably grew while we were reading it.
361              Update "cf->f_len", and try again. */
362           fd = wtap_fd(cf->wth);
363           if (fstat(fd, &cf_stat) >= 0) {
364             cf->f_len = cf_stat.st_size;
365             prog_val = (gfloat) file_pos / (gfloat) cf->f_len;
366           }
367           /* If it's still > 1, either the "fstat()" failed (in which
368              case there's not much we can do about it), or the file
369              *shrank* (in which case there's not much we can do about
370              it); just clip the progress value at 1.0. */
371           if (prog_val > 1.0)
372             prog_val = 1.0;
373         }
374         update_progress_dlg(progbar, prog_val);
375         cf->progbar_nextstep += cf->progbar_quantum;
376     }
377
378     if (stop_flag) {
379       /* Well, the user decided to abort the read.  Destroy the progress
380          bar, close the capture file, and return READ_ABORTED so our caller
381          can do whatever is appropriate when that happens. */
382       destroy_progress_dlg(progbar);
383       cf->state = FILE_READ_ABORTED;    /* so that we're allowed to close it */
384       gtk_clist_thaw(GTK_CLIST(packet_list));   /* undo our freeze */
385       close_cap_file(cf);
386       return (READ_ABORTED);
387     }
388     read_packet(cf, data_offset);
389   }
390
391   /* We're done reading the file; destroy the progress bar. */
392   destroy_progress_dlg(progbar);
393
394   /* We're done reading sequentially through the file. */
395   cf->state = FILE_READ_DONE;
396
397   /* Close the sequential I/O side, to free up memory it requires. */
398   wtap_sequential_close(cf->wth);
399
400   /* Allow the protocol dissectors to free up memory that they
401    * don't need after the sequential run-through of the packets. */
402   postseq_cleanup_all_protocols();
403
404   /* Set the file encapsulation type now; we don't know what it is until
405      we've looked at all the packets, as we don't know until then whether
406      there's more than one type (and thus whether it's
407      WTAP_ENCAP_PER_PACKET). */
408   cf->lnk_t = wtap_file_encap(cf->wth);
409
410   cf->current_frame = cf->first_displayed;
411   thaw_clist(cf);
412
413   statusbar_pop_file_msg();
414   set_display_filename(cf);
415
416   /* Enable menu items that make sense if you have a capture file you've
417      finished reading. */
418   set_menus_for_capture_file(TRUE);
419   set_menus_for_unsaved_capture_file(!cf->user_saved);
420
421   /* Enable menu items that make sense if you have some captured packets. */
422   set_menus_for_captured_packets(TRUE);
423
424   /* If we have any displayed packets to select, select the first of those
425      packets by making the first row the selected row. */
426   if (cf->first_displayed != NULL)
427     gtk_signal_emit_by_name(GTK_OBJECT(packet_list), "select_row", 0);
428
429   if (*err != 0) {
430     /* Put up a message box noting that the read failed somewhere along
431        the line.  Don't throw out the stuff we managed to read, though,
432        if any. */
433     switch (*err) {
434
435     case WTAP_ERR_UNSUPPORTED_ENCAP:
436       errmsg = "The capture file is for a network type that Ethereal doesn't support.";
437       break;
438
439     case WTAP_ERR_CANT_READ:
440       errmsg = "An attempt to read from the file failed for"
441                " some unknown reason.";
442       break;
443
444     case WTAP_ERR_SHORT_READ:
445       errmsg = "The capture file appears to have been cut short"
446                " in the middle of a packet.";
447       break;
448
449     case WTAP_ERR_BAD_RECORD:
450       errmsg = "The capture file appears to be damaged or corrupt.";
451       break;
452
453     default:
454       snprintf(errmsg_errno, sizeof(errmsg_errno),
455                "An error occurred while reading the"
456                " capture file: %s.", wtap_strerror(*err));
457       errmsg = errmsg_errno;
458       break;
459     }
460     snprintf(err_str, sizeof err_str, errmsg);
461     simple_dialog(ESD_TYPE_CRIT, NULL, err_str);
462     return (READ_ERROR);
463   } else
464     return (READ_SUCCESS);
465 }
466
467 #ifdef HAVE_LIBPCAP
468 int
469 start_tail_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
470 {
471   int     err;
472   int     i;
473
474   err = open_cap_file(fname, is_tempfile, cf);
475   if (err == 0) {
476     /* Disable menu items that make no sense if you're currently running
477        a capture. */
478     set_menus_for_capture_in_progress(TRUE);
479
480     /* Enable menu items that make sense if you have some captured
481        packets (yes, I know, we don't have any *yet*). */
482     set_menus_for_captured_packets(TRUE);
483
484     for (i = 0; i < cf->cinfo.num_cols; i++) {
485       if (get_column_resize_type(cf->cinfo.col_fmt[i]) == RESIZE_LIVE)
486         gtk_clist_set_column_auto_resize(GTK_CLIST(packet_list), i, TRUE);
487       else {
488         gtk_clist_set_column_auto_resize(GTK_CLIST(packet_list), i, FALSE);
489         gtk_clist_set_column_width(GTK_CLIST(packet_list), i,
490                                 cf->cinfo.col_width[i]);
491         gtk_clist_set_column_resizeable(GTK_CLIST(packet_list), i, TRUE);
492       }
493     }
494
495     statusbar_push_file_msg(" <live capture in progress>");
496   }
497   return err;
498 }
499
500 read_status_t
501 continue_tail_cap_file(capture_file *cf, int to_read, int *err)
502 {
503   long data_offset = 0;
504
505   gtk_clist_freeze(GTK_CLIST(packet_list));
506
507   while (to_read != 0 && (wtap_read(cf->wth, err, &data_offset))) {
508     if (cf->state == FILE_READ_ABORTED) {
509       /* Well, the user decided to exit Ethereal.  Break out of the
510          loop, and let the code below (which is called even if there
511          aren't any packets left to read) exit. */
512       break;
513     }
514     read_packet(cf, data_offset);
515     to_read--;
516   }
517
518   gtk_clist_thaw(GTK_CLIST(packet_list));
519
520   /* XXX - this cheats and looks inside the packet list to find the final
521      row number. */
522   if (auto_scroll_live && cf->plist_end != NULL)
523     gtk_clist_moveto(GTK_CLIST(packet_list), 
524                        GTK_CLIST(packet_list)->rows - 1, -1, 1.0, 1.0);
525
526   if (cf->state == FILE_READ_ABORTED) {
527     /* Well, the user decided to exit Ethereal.  Return READ_ABORTED
528        so that our caller can kill off the capture child process;
529        this will cause an EOF on the pipe from the child, so
530        "finish_tail_cap_file()" will be called, and it will clean up
531        and exit. */
532     return READ_ABORTED;
533   } else if (*err != 0) {
534     /* We got an error reading the capture file.
535        XXX - pop up a dialog box? */
536     return (READ_ERROR);
537   } else
538     return (READ_SUCCESS);
539 }
540
541 read_status_t
542 finish_tail_cap_file(capture_file *cf, int *err)
543 {
544   long data_offset;
545
546   gtk_clist_freeze(GTK_CLIST(packet_list));
547
548   while ((wtap_read(cf->wth, err, &data_offset))) {
549     if (cf->state == FILE_READ_ABORTED) {
550       /* Well, the user decided to abort the read.  Break out of the
551          loop, and let the code below (which is called even if there
552          aren't any packets left to read) exit. */
553       break;
554     }
555     read_packet(cf, data_offset);
556   }
557
558   if (cf->state == FILE_READ_ABORTED) {
559     /* Well, the user decided to abort the read.  We're only called
560        when the child capture process closes the pipe to us (meaning
561        it's probably exited), so we can just close the capture
562        file; we return READ_ABORTED so our caller can do whatever
563        is appropriate when that happens. */
564     close_cap_file(cf);
565     return READ_ABORTED;
566   }
567
568   thaw_clist(cf);
569   if (auto_scroll_live && cf->plist_end != NULL)
570     /* XXX - this cheats and looks inside the packet list to find the final
571        row number. */
572     gtk_clist_moveto(GTK_CLIST(packet_list), 
573                        GTK_CLIST(packet_list)->rows - 1, -1, 1.0, 1.0);
574
575   /* We're done reading sequentially through the file. */
576   cf->state = FILE_READ_DONE;
577
578   /* We're done reading sequentially through the file; close the
579      sequential I/O side, to free up memory it requires. */
580   wtap_sequential_close(cf->wth);
581
582   /* Allow the protocol dissectors to free up memory that they
583    * don't need after the sequential run-through of the packets. */
584   postseq_cleanup_all_protocols();
585
586   /* Set the file encapsulation type now; we don't know what it is until
587      we've looked at all the packets, as we don't know until then whether
588      there's more than one type (and thus whether it's
589      WTAP_ENCAP_PER_PACKET). */
590   cf->lnk_t = wtap_file_encap(cf->wth);
591
592   /* Pop the "<live capture in progress>" message off the status bar. */
593   statusbar_pop_file_msg();
594
595   set_display_filename(cf);
596
597   /* Enable menu items that make sense if you're not currently running
598      a capture. */
599   set_menus_for_capture_in_progress(FALSE);
600
601   /* Enable menu items that make sense if you have a capture file
602      you've finished reading. */
603   set_menus_for_capture_file(TRUE);
604   set_menus_for_unsaved_capture_file(!cf->user_saved);
605
606   if (*err != 0) {
607     /* We got an error reading the capture file.
608        XXX - pop up a dialog box? */
609     return (READ_ERROR);
610   } else
611     return (READ_SUCCESS);
612 }
613 #endif /* HAVE_LIBPCAP */
614
615 typedef struct {
616   color_filter_t *colorf;
617   epan_dissect_t *edt;
618 } apply_color_filter_args;
619
620 /*
621  * If no color filter has been applied, apply this one.
622  * (The "if no color filter has been applied" is to handle the case where
623  * more than one color filter matches the packet.)
624  */
625 static void
626 apply_color_filter(gpointer filter_arg, gpointer argp)
627 {
628   color_filter_t *colorf = filter_arg;
629   apply_color_filter_args *args = argp;
630
631   if (colorf->c_colorfilter != NULL && args->colorf == NULL) {
632     if (dfilter_apply_edt(colorf->c_colorfilter, args->edt))
633       args->colorf = colorf;
634   }
635 }
636
637 static int
638 add_packet_to_packet_list(frame_data *fdata, capture_file *cf,
639         union wtap_pseudo_header *pseudo_header, const u_char *buf,
640         gboolean refilter)
641 {
642   apply_color_filter_args args;
643   gint          row;
644   gboolean      create_proto_tree = FALSE;
645   epan_dissect_t *edt;
646   GdkColor      fg, bg;
647
648   /* We don't yet have a color filter to apply. */
649   args.colorf = NULL;
650
651   /* If we don't have the time stamp of the first packet in the
652      capture, it's because this is the first packet.  Save the time
653      stamp of this packet as the time stamp of the first packet. */
654   if (!firstsec && !firstusec) {
655     firstsec  = fdata->abs_secs;
656     firstusec = fdata->abs_usecs;
657   }
658
659   /* If either
660
661         we have a display filter and are re-applying it;
662
663         we have a list of color filters;
664
665      allocate a protocol tree root node, so that we'll construct
666      a protocol tree against which a filter expression can be
667      evaluated. */
668   if ((cf->dfcode != NULL && refilter) || filter_list != NULL)
669           create_proto_tree = TRUE;
670
671   /* Dissect the frame. */
672   edt = epan_dissect_new(create_proto_tree, FALSE);
673
674   if (cf->dfcode != NULL && refilter) {
675       epan_dissect_prime_dfilter(edt, cf->dfcode);
676   }
677   if (filter_list) {
678       filter_list_prime_edt(edt);
679   }
680   epan_dissect_run(edt, pseudo_header, buf, fdata, &cf->cinfo);
681
682
683   /* If we have a display filter, apply it if we're refiltering, otherwise
684      leave the "passed_dfilter" flag alone.
685
686      If we don't have a display filter, set "passed_dfilter" to 1. */
687   if (cf->dfcode != NULL) {
688     if (refilter) {
689       if (cf->dfcode != NULL)
690         fdata->flags.passed_dfilter = dfilter_apply_edt(cf->dfcode, edt) ? 1 : 0;
691       else
692         fdata->flags.passed_dfilter = 1;
693     }
694   } else
695     fdata->flags.passed_dfilter = 1;
696
697   /* If we have color filters, and the frame is to be displayed, apply
698      the color filters. */
699   if (fdata->flags.passed_dfilter) {
700     if (filter_list != NULL) {
701       args.edt = edt;
702       g_slist_foreach(filter_list, apply_color_filter, &args);
703     }
704   }
705
706
707   if (fdata->flags.passed_dfilter) {
708     /* This frame passed the display filter, so add it to the clist. */
709
710     /* If we don't have the time stamp of the previous displayed packet,
711        it's because this is the first displayed packet.  Save the time
712        stamp of this packet as the time stamp of the previous displayed
713        packet. */
714     if (!prevsec && !prevusec) {
715       prevsec  = fdata->abs_secs;
716       prevusec = fdata->abs_usecs;
717     }
718
719     /* Get the time elapsed between the first packet and this packet. */
720     compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
721                 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
722
723     /* If it's greater than the current elapsed time, set the elapsed time
724        to it (we check for "greater than" so as not to be confused by
725        time moving backwards). */
726     if ((gint32)cf->esec < fdata->rel_secs
727         || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
728       cf->esec = fdata->rel_secs;
729       cf->eusec = fdata->rel_usecs;
730     }
731   
732     /* Get the time elapsed between the previous displayed packet and
733        this packet. */
734     compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
735                 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
736     prevsec = fdata->abs_secs;
737     prevusec = fdata->abs_usecs;
738
739     epan_dissect_fill_in_columns(edt);
740
741     /* If we haven't yet seen the first frame, this is it.
742
743        XXX - we must do this before we add the row to the display,
744        as, if the display's GtkCList's selection mode is
745        GTK_SELECTION_BROWSE, when the first entry is added to it,
746        "select_packet()" will be called, and it will fetch the row
747        data for the 0th row, and will get a null pointer rather than
748        "fdata", as "gtk_clist_append()" won't yet have returned and
749        thus "gtk_clist_set_row_data()" won't yet have been called.
750
751        We thus need to leave behind bread crumbs so that
752        "select_packet()" can find this frame.  See the comment
753        in "select_packet()". */
754     if (cf->first_displayed == NULL)
755       cf->first_displayed = fdata;
756
757     /* This is the last frame we've seen so far. */
758     cf->last_displayed = fdata;
759
760     row = gtk_clist_append(GTK_CLIST(packet_list), cf->cinfo.col_data);
761     gtk_clist_set_row_data(GTK_CLIST(packet_list), row, fdata);
762
763     if (fdata->flags.marked) {
764         color_t_to_gdkcolor(&bg, &prefs.gui_marked_bg);
765         color_t_to_gdkcolor(&fg, &prefs.gui_marked_fg);
766     } else if (filter_list != NULL && (args.colorf != NULL)) {
767         bg = args.colorf->bg_color;
768         fg = args.colorf->fg_color;
769     } else {
770         bg = WHITE;
771         fg = BLACK;
772     }
773     gtk_clist_set_background(GTK_CLIST(packet_list), row, &bg);
774     gtk_clist_set_foreground(GTK_CLIST(packet_list), row, &fg);
775   } else {
776     /* This frame didn't pass the display filter, so it's not being added
777        to the clist, and thus has no row. */
778     row = -1;
779   }
780   epan_dissect_free(edt);
781   return row;
782 }
783
784 static void
785 read_packet(capture_file *cf, long offset)
786 {
787   const struct wtap_pkthdr *phdr = wtap_phdr(cf->wth);
788   union wtap_pseudo_header *pseudo_header = wtap_pseudoheader(cf->wth);
789   const u_char *buf = wtap_buf_ptr(cf->wth);
790   frame_data   *fdata;
791   int           passed;
792   frame_data   *plist_end;
793   epan_dissect_t *edt;
794
795   /* Allocate the next list entry, and add it to the list. */
796   fdata = g_mem_chunk_alloc(cf->plist_chunk);
797
798   fdata->next = NULL;
799   fdata->prev = NULL;
800   fdata->pfd  = NULL;
801   fdata->pkt_len  = phdr->len;
802   fdata->cap_len  = phdr->caplen;
803   fdata->file_off = offset;
804   fdata->lnk_t = phdr->pkt_encap;
805   fdata->abs_secs  = phdr->ts.tv_sec;
806   fdata->abs_usecs = phdr->ts.tv_usec;
807   fdata->flags.encoding = CHAR_ASCII;
808   fdata->flags.visited = 0;
809   fdata->flags.marked = 0;
810
811   passed = TRUE;
812   if (cf->rfcode) {
813     edt = epan_dissect_new(TRUE, FALSE);
814     epan_dissect_prime_dfilter(edt, cf->rfcode);
815     epan_dissect_run(edt, pseudo_header, buf, fdata, NULL);
816     passed = dfilter_apply_edt(cf->rfcode, edt);
817     epan_dissect_free(edt);
818   }   
819   if (passed) {
820     plist_end = cf->plist_end;
821     fdata->prev = plist_end;
822     if (plist_end != NULL)
823       plist_end->next = fdata;
824     else
825       cf->plist = fdata;
826     cf->plist_end = fdata;
827
828     cf->count++;
829     fdata->num = cf->count;
830     add_packet_to_packet_list(fdata, cf, pseudo_header, buf, TRUE);
831   } else {
832     /* XXX - if we didn't have read filters, or if we could avoid
833        allocating the "frame_data" structure until we knew whether
834        the frame passed the read filter, we could use a G_ALLOC_ONLY
835        memory chunk...
836
837        ...but, at least in one test I did, where I just made the chunk
838        a G_ALLOC_ONLY chunk and read in a huge capture file, it didn't
839        seem to save a noticeable amount of time or space. */
840     g_mem_chunk_free(cf->plist_chunk, fdata);
841   }
842 }
843
844 int
845 filter_packets(capture_file *cf, gchar *dftext)
846 {
847   dfilter_t *dfcode;
848
849   if (dftext == NULL) {
850     /* The new filter is an empty filter (i.e., display all packets). */
851     dfcode = NULL;
852   } else {
853     /*
854      * We have a filter; make a copy of it (as we'll be saving it),
855      * and try to compile it.
856      */
857     dftext = g_strdup(dftext);
858     if (!dfilter_compile(dftext, &dfcode)) {
859       /* The attempt failed; report an error. */
860       simple_dialog(ESD_TYPE_CRIT, NULL, dfilter_error_msg);
861       return 0;
862     }
863
864     /* Was it empty? */
865     if (dfcode == NULL) {
866       /* Yes - free the filter text, and set it to null. */
867       g_free(dftext);
868       dftext = NULL;
869     }
870   }
871
872   /* We have a valid filter.  Replace the current filter. */
873   if (cf->dfilter != NULL)
874     g_free(cf->dfilter);
875   cf->dfilter = dftext;
876   if (cf->dfcode != NULL)
877     dfilter_free(cf->dfcode);
878   cf->dfcode = dfcode;
879
880   /* Now rescan the packet list, applying the new filter, but not
881      throwing away information constructed on a previous pass. */
882   rescan_packets(cf, "Filtering", TRUE, FALSE);
883   return 1;
884 }
885
886 void
887 colorize_packets(capture_file *cf)
888 {
889   rescan_packets(cf, "Colorizing", FALSE, FALSE);
890 }
891
892 void
893 redissect_packets(capture_file *cf)
894 {
895   rescan_packets(cf, "Reprocessing", TRUE, TRUE);
896 }
897
898 /* Rescan the list of packets, reconstructing the CList.
899
900    "action" describes why we're doing this; it's used in the progress
901    dialog box.
902
903    "refilter" is TRUE if we need to re-evaluate the filter expression.
904
905    "redissect" is TRUE if we need to make the dissectors reconstruct
906    any state information they have (because a preference that affects
907    some dissector has changed, meaning some dissector might construct
908    its state differently from the way it was constructed the last time). */
909 static void
910 rescan_packets(capture_file *cf, const char *action, gboolean refilter,
911                 gboolean redissect)
912 {
913   frame_data *fdata;
914   progdlg_t *progbar;
915   gboolean stop_flag;
916   guint32 progbar_quantum;
917   guint32 progbar_nextstep;
918   unsigned int count;
919   int err;
920   frame_data *selected_frame;
921   int selected_row;
922   int row;
923
924   /* Which frame, if any, is the currently selected frame?
925      XXX - should the selected frame or the focus frame be the "current"
926      frame, that frame being the one from which "Find Frame" searches
927      start? */
928   selected_frame = cf->current_frame;
929
930   /* We don't yet know what row that frame will be on, if any, after we
931      rebuild the clist, however. */
932   selected_row = -1;
933
934   if (redissect) {
935     /* We need to re-initialize all the state information that protocols
936        keep, because some preference that controls a dissector has changed,
937        which might cause the state information to be constructed differently
938        by that dissector. */
939
940     /* Initialize all data structures used for dissection. */
941     init_dissection();
942   }
943
944   /* Freeze the packet list while we redo it, so we don't get any
945      screen updates while it happens. */
946   gtk_clist_freeze(GTK_CLIST(packet_list));
947
948   /* Clear it out. */
949   gtk_clist_clear(GTK_CLIST(packet_list));
950
951   /* We don't yet know which will be the first and last frames displayed. */
952   cf->first_displayed = NULL;
953   cf->last_displayed = NULL;
954
955   /* Iterate through the list of frames.  Call a routine for each frame
956      to check whether it should be displayed and, if so, add it to
957      the display list. */
958   firstsec = 0;
959   firstusec = 0;
960   prevsec = 0;
961   prevusec = 0;
962
963   /* Update the progress bar when it gets to this value. */
964   progbar_nextstep = 0;
965   /* When we reach the value that triggers a progress bar update,
966      bump that value by this amount. */
967   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
968   /* Count of packets at which we've looked. */
969   count = 0;
970
971   stop_flag = FALSE;
972   progbar = create_progress_dlg(action, "Stop", &stop_flag);
973
974   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
975     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
976        when we update it, we have to run the GTK+ main loop to get it
977        to repaint what's pending, and doing so may involve an "ioctl()"
978        to see if there's any pending input from an X server, and doing
979        that for every packet can be costly, especially on a big file. */
980     if (count >= progbar_nextstep) {
981       /* let's not divide by zero. I should never be started
982        * with count == 0, so let's assert that
983        */
984       g_assert(cf->count > 0);
985
986       update_progress_dlg(progbar, (gfloat) count / cf->count);
987
988       progbar_nextstep += progbar_quantum;
989     }
990
991     if (stop_flag) {
992       /* Well, the user decided to abort the filtering.  Just stop.
993
994          XXX - go back to the previous filter?  Users probably just
995          want not to wait for a filtering operation to finish;
996          unless we cancel by having no filter, reverting to the
997          previous filter will probably be even more expensive than
998          continuing the filtering, as it involves going back to the
999          beginning and filtering, and even with no filter we currently
1000          have to re-generate the entire clist, which is also expensive.
1001
1002          I'm not sure what Network Monitor does, but it doesn't appear
1003          to give you an unfiltered display if you cancel. */
1004       break;
1005     }
1006
1007     count++;
1008
1009     if (redissect) {
1010       /* Since all state for the frame was destroyed, mark the frame
1011        * as not visited, free the GSList referring to the state
1012        * data (the per-frame data itself was freed by
1013        * "init_dissection()"), and null out the GSList pointer. */
1014       fdata->flags.visited = 0;
1015       if (fdata->pfd) {
1016         g_slist_free(fdata->pfd);
1017         fdata->pfd = NULL;
1018       }
1019     }
1020
1021     /* XXX - do something with "err" */
1022     wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1023         cf->pd, fdata->cap_len, &err);
1024
1025     row = add_packet_to_packet_list(fdata, cf, &cf->pseudo_header, cf->pd,
1026                                         refilter);
1027     if (fdata == selected_frame)
1028       selected_row = row;
1029   }
1030  
1031   if (redissect) {
1032     /* Clear out what remains of the visited flags and per-frame data
1033        pointers.
1034
1035        XXX - that may cause various forms of bogosity when dissecting
1036        these frames, as they won't have been seen by this sequential
1037        pass, but the only alternative I see is to keep scanning them
1038        even though the user requested that the scan stop, and that
1039        would leave the user stuck with an Ethereal grinding on
1040        until it finishes.  Should we just stick them with that? */
1041     for (; fdata != NULL; fdata = fdata->next) {
1042       fdata->flags.visited = 0;
1043       if (fdata->pfd) {
1044         g_slist_free(fdata->pfd);
1045         fdata->pfd = NULL;
1046       }
1047     }
1048   }
1049
1050   /* We're done filtering the packets; destroy the progress bar. */
1051   destroy_progress_dlg(progbar);
1052
1053   /* Unfreeze the packet list. */
1054   gtk_clist_thaw(GTK_CLIST(packet_list));
1055
1056   if (selected_row != -1) {
1057     /* The frame that was selected passed the filter; select it, make it
1058        the focus row, and make it visible. */
1059     set_selected_row(selected_row);
1060     finfo_selected = NULL;
1061   } else {
1062     /* The selected frame didn't pass the filter; make the first frame
1063        the current frame, and leave it unselected. */
1064     unselect_packet(cf);
1065     cf->current_frame = cf->first_displayed;
1066   }
1067 }
1068
1069 int
1070 print_packets(capture_file *cf, print_args_t *print_args)
1071 {
1072   int         i;
1073   frame_data *fdata;
1074   progdlg_t  *progbar;
1075   gboolean    stop_flag;
1076   guint32     progbar_quantum;
1077   guint32     progbar_nextstep;
1078   guint32     count;
1079   int         err;
1080   gint       *col_widths = NULL;
1081   gint        data_width;
1082   gboolean    print_separator;
1083   char       *line_buf = NULL;
1084   int         line_buf_len = 256;
1085   char        *cp;
1086   int         column_len;
1087   int         line_len;
1088   epan_dissect_t *edt = NULL;
1089
1090   cf->print_fh = open_print_dest(print_args->to_file, print_args->dest);
1091   if (cf->print_fh == NULL)
1092     return FALSE;       /* attempt to open destination failed */
1093
1094   print_preamble(cf->print_fh, print_args->format);
1095
1096   if (print_args->print_summary) {
1097     /* We're printing packet summaries.  Allocate the line buffer at
1098        its initial length. */
1099     line_buf = g_malloc(line_buf_len + 1);
1100
1101     /* Find the widths for each of the columns - maximum of the
1102        width of the title and the width of the data - and print
1103        the column titles. */
1104     col_widths = (gint *) g_malloc(sizeof(gint) * cf->cinfo.num_cols);
1105     cp = &line_buf[0];
1106     line_len = 0;
1107     for (i = 0; i < cf->cinfo.num_cols; i++) {
1108       /* Don't pad the last column. */
1109       if (i == cf->cinfo.num_cols - 1)
1110         col_widths[i] = 0;
1111       else {
1112         col_widths[i] = strlen(cf->cinfo.col_title[i]);
1113         data_width = get_column_char_width(get_column_format(i));
1114         if (data_width > col_widths[i])
1115           col_widths[i] = data_width;
1116       }
1117
1118       /* Find the length of the string for this column. */
1119       column_len = strlen(cf->cinfo.col_title[i]);
1120       if (col_widths[i] > column_len)
1121         column_len = col_widths[i];
1122
1123       /* Make sure there's room in the line buffer for the column; if not,
1124          double its length. */
1125       line_len += column_len + 1;       /* "+1" for space */
1126       if (line_len > line_buf_len) {
1127         line_buf_len *= 2;
1128         line_buf = g_realloc(line_buf, line_buf_len + 1);
1129       }
1130
1131       /* Right-justify the packet number column. */
1132       if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1133         sprintf(cp, "%*s", col_widths[i], cf->cinfo.col_title[i]);
1134       else
1135         sprintf(cp, "%-*s", col_widths[i], cf->cinfo.col_title[i]);
1136       cp += column_len;
1137       if (i != cf->cinfo.num_cols - 1)
1138         *cp++ = ' ';
1139     }
1140     *cp = '\0';
1141     print_line(cf->print_fh, 0, print_args->format, line_buf);
1142   }
1143
1144   print_separator = FALSE;
1145
1146   /* Update the progress bar when it gets to this value. */
1147   progbar_nextstep = 0;
1148   /* When we reach the value that triggers a progress bar update,
1149      bump that value by this amount. */
1150   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1151   /* Count of packets at which we've looked. */
1152   count = 0;
1153
1154   stop_flag = FALSE;
1155   progbar = create_progress_dlg("Printing", "Stop", &stop_flag);
1156
1157   /* Iterate through the list of packets, printing the packets that
1158      were selected by the current display filter.  */
1159   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1160     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1161        when we update it, we have to run the GTK+ main loop to get it
1162        to repaint what's pending, and doing so may involve an "ioctl()"
1163        to see if there's any pending input from an X server, and doing
1164        that for every packet can be costly, especially on a big file. */
1165     if (count >= progbar_nextstep) {
1166       /* let's not divide by zero. I should never be started
1167        * with count == 0, so let's assert that
1168        */
1169       g_assert(cf->count > 0);
1170
1171       update_progress_dlg(progbar, (gfloat) count / cf->count);
1172
1173       progbar_nextstep += progbar_quantum;
1174     }
1175
1176     if (stop_flag) {
1177       /* Well, the user decided to abort the printing.  Just stop.
1178
1179          XXX - note that what got generated before they did that
1180          will get printed, as we're piping to a print program; we'd
1181          have to write to a file and then hand that to the print
1182          program to make it actually not print anything. */
1183       break;
1184     }
1185
1186     count++;
1187     /* Check to see if we are suppressing unmarked packets, if so, 
1188      * suppress them and then proceed to check for visibility.
1189      */
1190     if (((print_args->suppress_unmarked && fdata->flags.marked ) ||
1191         !(print_args->suppress_unmarked)) && fdata->flags.passed_dfilter) {
1192       /* XXX - do something with "err" */
1193       wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1194                         cf->pd, fdata->cap_len, &err);
1195       if (print_args->print_summary) {
1196         /* Fill in the column information, but don't bother creating
1197            the logical protocol tree. */
1198         edt = epan_dissect_new(FALSE, FALSE);
1199         epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, &cf->cinfo);
1200         epan_dissect_fill_in_columns(edt);
1201         cp = &line_buf[0];
1202         line_len = 0;
1203         for (i = 0; i < cf->cinfo.num_cols; i++) {
1204           /* Find the length of the string for this column. */
1205           column_len = strlen(cf->cinfo.col_data[i]);
1206           if (col_widths[i] > column_len)
1207             column_len = col_widths[i];
1208
1209           /* Make sure there's room in the line buffer for the column; if not,
1210              double its length. */
1211           line_len += column_len + 1;   /* "+1" for space */
1212           if (line_len > line_buf_len) {
1213             line_buf_len *= 2;
1214             line_buf = g_realloc(line_buf, line_buf_len + 1);
1215           }
1216
1217           /* Right-justify the packet number column. */
1218           if (cf->cinfo.col_fmt[i] == COL_NUMBER)
1219             sprintf(cp, "%*s", col_widths[i], cf->cinfo.col_data[i]);
1220           else
1221             sprintf(cp, "%-*s", col_widths[i], cf->cinfo.col_data[i]);
1222           cp += column_len;
1223           if (i != cf->cinfo.num_cols - 1)
1224             *cp++ = ' ';
1225         }
1226         *cp = '\0';
1227         print_line(cf->print_fh, 0, print_args->format, line_buf);
1228       } else {
1229         if (print_separator)
1230           print_line(cf->print_fh, 0, print_args->format, "");
1231
1232         /* Create the logical protocol tree, complete with the display
1233            representation of the items; we don't need the columns here,
1234            however. */
1235         edt = epan_dissect_new(TRUE, TRUE);
1236         epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1237
1238         /* Print the information in that tree. */
1239         proto_tree_print(print_args, edt, cf->print_fh);
1240
1241         if (print_args->print_hex) {
1242           /* Print the full packet data as hex. */
1243           print_hex_data(cf->print_fh, print_args->format, edt);
1244         }
1245
1246         /* Print a blank line if we print anything after this. */
1247         print_separator = TRUE;
1248       }
1249       epan_dissect_free(edt);
1250     }
1251   }
1252
1253   /* We're done printing the packets; destroy the progress bar. */
1254   destroy_progress_dlg(progbar);
1255
1256   if (col_widths != NULL)
1257     g_free(col_widths);
1258   if (line_buf != NULL)
1259     g_free(line_buf);
1260
1261   print_finale(cf->print_fh, print_args->format);
1262
1263   close_print_dest(print_args->to_file, cf->print_fh);
1264  
1265   cf->print_fh = NULL;
1266
1267   return TRUE;
1268 }
1269
1270 /* Scan through the packet list and change all columns that use the
1271    "command-line-specified" time stamp format to use the current
1272    value of that format. */
1273 void
1274 change_time_formats(capture_file *cf)
1275 {
1276   frame_data *fdata;
1277   progdlg_t *progbar;
1278   gboolean stop_flag;
1279   guint32 progbar_quantum;
1280   guint32 progbar_nextstep;
1281   unsigned int count;
1282   int row;
1283   int i;
1284   GtkStyle  *pl_style;
1285
1286   /* Are there any columns with time stamps in the "command-line-specified"
1287      format?
1288
1289      XXX - we have to force the "column is writable" flag on, as it
1290      might be off from the last frame that was dissected. */
1291   col_set_writable(&cf->cinfo, TRUE);
1292   if (!check_col(&cf->cinfo, COL_CLS_TIME)) {
1293     /* No, there aren't any columns in that format, so we have no work
1294        to do. */
1295     return;
1296   }
1297
1298   /* Freeze the packet list while we redo it, so we don't get any
1299      screen updates while it happens. */
1300   freeze_clist(cf);
1301
1302   /* Update the progress bar when it gets to this value. */
1303   progbar_nextstep = 0;
1304   /* When we reach the value that triggers a progress bar update,
1305      bump that value by this amount. */
1306   progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1307   /* Count of packets at which we've looked. */
1308   count = 0;
1309
1310   stop_flag = FALSE;
1311   progbar = create_progress_dlg("Changing time display", "Stop", &stop_flag);
1312
1313   /* Iterate through the list of packets, checking whether the packet
1314      is in a row of the summary list and, if so, whether there are
1315      any columns that show the time in the "command-line-specified"
1316      format and, if so, update that row. */
1317   for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1318     /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1319        when we update it, we have to run the GTK+ main loop to get it
1320        to repaint what's pending, and doing so may involve an "ioctl()"
1321        to see if there's any pending input from an X server, and doing
1322        that for every packet can be costly, especially on a big file. */
1323     if (count >= progbar_nextstep) {
1324       /* let's not divide by zero. I should never be started
1325        * with count == 0, so let's assert that
1326        */
1327       g_assert(cf->count > 0);
1328
1329       update_progress_dlg(progbar, (gfloat) count / cf->count);
1330
1331       progbar_nextstep += progbar_quantum;
1332     }
1333
1334     if (stop_flag) {
1335       /* Well, the user decided to abort the redisplay.  Just stop.
1336
1337          XXX - this leaves the time field in the old format in
1338          frames we haven't yet processed.  So it goes; should we
1339          simply not offer them the option of stopping? */
1340       break;
1341     }
1342
1343     count++;
1344
1345     /* Find what row this packet is in. */
1346     row = gtk_clist_find_row_from_data(GTK_CLIST(packet_list), fdata);
1347
1348     if (row != -1) {
1349       /* This packet is in the summary list, on row "row". */
1350
1351       for (i = 0; i < cf->cinfo.num_cols; i++) {
1352         if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1353           /* This is one of the columns that shows the time in
1354              "command-line-specified" format; update it. */
1355           cf->cinfo.col_buf[i][0] = '\0';
1356           col_set_cls_time(fdata, &cf->cinfo, i);
1357           gtk_clist_set_text(GTK_CLIST(packet_list), row, i,
1358                              cf->cinfo.col_data[i]);
1359         }
1360       }
1361     }
1362   }
1363
1364   /* We're done redisplaying the packets; destroy the progress bar. */
1365   destroy_progress_dlg(progbar);
1366
1367   /* Set the column widths of those columns that show the time in
1368      "command-line-specified" format. */
1369   pl_style = gtk_widget_get_style(packet_list);
1370   for (i = 0; i < cf->cinfo.num_cols; i++) {
1371     if (cf->cinfo.fmt_matx[i][COL_CLS_TIME]) {
1372       gtk_clist_set_column_width(GTK_CLIST(packet_list), i,
1373         gdk_string_width(pl_style->font, get_column_longest_string(COL_CLS_TIME)));
1374     }
1375   }
1376
1377   /* Unfreeze the packet list. */
1378   thaw_clist(cf);
1379 }
1380
1381 gboolean
1382 find_packet(capture_file *cf, dfilter_t *sfcode)
1383 {
1384   frame_data *start_fd;
1385   frame_data *fdata;
1386   frame_data *new_fd = NULL;
1387   progdlg_t *progbar = NULL;
1388   gboolean stop_flag;
1389   guint32 progbar_quantum;
1390   guint32 progbar_nextstep;
1391   unsigned int count;
1392   int err;
1393   gboolean frame_matched;
1394   int row;
1395   epan_dissect_t        *edt;
1396
1397   start_fd = cf->current_frame;
1398   if (start_fd != NULL)  {
1399     /* Iterate through the list of packets, starting at the packet we've
1400        picked, calling a routine to run the filter on the packet, see if
1401        it matches, and stop if so.  */
1402     count = 0;
1403     fdata = start_fd;
1404
1405     /* Update the progress bar when it gets to this value.  We start at
1406        20, not 0, so that we don't get a progress bar until we've
1407        checked at least that many frames, so that a very quick search
1408        doesn't pop up and immediately destroy a progress bar.
1409
1410        XXX - should use a timer?  Like 50 ms. */
1411     progbar_nextstep = 20;
1412     /* When we reach the value that triggers a progress bar update,
1413        bump that value by this amount. */
1414     progbar_quantum = cf->count/N_PROGBAR_UPDATES;
1415
1416     stop_flag = FALSE;
1417
1418     fdata = start_fd;
1419     for (;;) {
1420       /* Update the progress bar, but do it only N_PROGBAR_UPDATES times;
1421          when we update it, we have to run the GTK+ main loop to get it
1422          to repaint what's pending, and doing so may involve an "ioctl()"
1423          to see if there's any pending input from an X server, and doing
1424          that for every packet can be costly, especially on a big file. */
1425       if (count >= progbar_nextstep) {
1426         /* let's not divide by zero. I should never be started
1427          * with count == 0, so let's assert that
1428          */
1429         g_assert(cf->count > 0);
1430
1431         /* Create the progress bar if it doesn't exist; we don't create it
1432            immediately, so that we don't have it appear and immediately
1433            disappear if the search is quick. */
1434         if (progbar == NULL)
1435            progbar = create_progress_dlg("Searching", "Cancel", &stop_flag);
1436         
1437         update_progress_dlg(progbar, (gfloat) count / cf->count);
1438
1439         progbar_nextstep += progbar_quantum;
1440       }
1441
1442       if (stop_flag) {
1443         /* Well, the user decided to abort the search.  Go back to the
1444            frame where we started. */
1445         new_fd = start_fd;
1446         break;
1447       }
1448
1449       /* Go past the current frame. */
1450       if (cf->sbackward) {
1451         /* Go on to the previous frame. */
1452         fdata = fdata->prev;
1453         if (fdata == NULL)
1454           fdata = cf->plist_end;        /* wrap around */
1455       } else {
1456         /* Go on to the next frame. */
1457         fdata = fdata->next;
1458         if (fdata == NULL)
1459           fdata = cf->plist;    /* wrap around */
1460       }
1461
1462       count++;
1463
1464       /* Is this packet in the display? */
1465       if (fdata->flags.passed_dfilter) {
1466         /* Yes.  Does it match the search filter? */
1467         /* XXX - do something with "err" */
1468         wtap_seek_read(cf->wth, fdata->file_off, &cf->pseudo_header,
1469                         cf->pd, fdata->cap_len, &err);
1470         edt = epan_dissect_new(TRUE, FALSE);
1471         epan_dissect_prime_dfilter(edt, sfcode);
1472         epan_dissect_run(edt, &cf->pseudo_header, cf->pd, fdata, NULL);
1473         frame_matched = dfilter_apply_edt(sfcode, edt);
1474         epan_dissect_free(edt);
1475         if (frame_matched) {
1476           new_fd = fdata;
1477           break;        /* found it! */
1478         }
1479       }
1480
1481       if (fdata == start_fd) {
1482         /* We're back to the frame we were on originally, and that frame
1483            doesn't match the search filter.  The search failed. */
1484         break;
1485       }
1486     }
1487
1488     /* We're done scanning the packets; destroy the progress bar, if
1489        we created it. */
1490     if (progbar != NULL)
1491       destroy_progress_dlg(progbar);
1492   }
1493
1494   if (new_fd != NULL) {
1495     /* We found a frame.  Find what row it's in. */
1496     row = gtk_clist_find_row_from_data(GTK_CLIST(packet_list), new_fd);
1497     g_assert(row != -1);
1498
1499     /* Select that row, make it the focus row, and make it visible. */
1500     set_selected_row(row);
1501     return TRUE;        /* success */
1502   } else
1503     return FALSE;       /* failure */
1504 }
1505
1506 goto_result_t
1507 goto_frame(capture_file *cf, guint fnumber)
1508 {
1509   frame_data *fdata;
1510   int row;
1511
1512   for (fdata = cf->plist; fdata != NULL && fdata->num < fnumber; fdata = fdata->next)
1513     ;
1514
1515   if (fdata == NULL)
1516     return NO_SUCH_FRAME;       /* we didn't find that frame */
1517   if (!fdata->flags.passed_dfilter)
1518     return FRAME_NOT_DISPLAYED; /* the frame with that number isn't displayed */
1519
1520   /* We found that frame, and it's currently being displayed.
1521      Find what row it's in. */
1522   row = gtk_clist_find_row_from_data(GTK_CLIST(packet_list), fdata);
1523   g_assert(row != -1);
1524
1525   /* Select that row, make it the focus row, and make it visible. */
1526   set_selected_row(row);
1527   return FOUND_FRAME;
1528 }
1529
1530 /* Select the packet on a given row. */
1531 void
1532 select_packet(capture_file *cf, int row)
1533 {
1534   frame_data *fdata;
1535   int err;
1536
1537   /* Get the frame data struct pointer for this frame */
1538   fdata = (frame_data *) gtk_clist_get_row_data(GTK_CLIST(packet_list), row);
1539
1540   if (fdata == NULL) {
1541     /* XXX - if a GtkCList's selection mode is GTK_SELECTION_BROWSE, when
1542        the first entry is added to it by "real_insert_row()", that row
1543        is selected (see "real_insert_row()", in "gtk/gtkclist.c", in both
1544        our version and the vanilla GTK+ version).
1545
1546        This means that a "select-row" signal is emitted; this causes
1547        "packet_list_select_cb()" to be called, which causes "select_packet()"
1548        to be called.
1549
1550        "select_packet()" fetches, above, the data associated with the
1551        row that was selected; however, as "gtk_clist_append()", which
1552        called "real_insert_row()", hasn't yet returned, we haven't yet
1553        associated any data with that row, so we get back a null pointer.
1554
1555        We can't assume that there's only one frame in the frame list,
1556        either, as we may be filtering the display.
1557
1558        We therefore assume that, if "row" is 0, i.e. the first row
1559        is being selected, and "cf->first_displayed" equals
1560        "cf->last_displayed", i.e. there's only one frame being
1561        displayed, that frame is the frame we want.
1562
1563        This means we have to set "cf->first_displayed" and
1564        "cf->last_displayed" before adding the row to the
1565        GtkCList; see the comment in "add_packet_to_packet_list()". */
1566
1567        if (row == 0 && cf->first_displayed == cf->last_displayed)
1568          fdata = cf->first_displayed;
1569   }
1570
1571   /* Record that this frame is the current frame. */
1572   cf->current_frame = fdata;
1573
1574   /* Get the data in that frame. */
1575   /* XXX - do something with "err" */
1576   wtap_seek_read (cf->wth, fdata->file_off, &cf->pseudo_header,
1577                         cf->pd, fdata->cap_len, &err);
1578
1579   /* Create the logical protocol tree. */
1580   if (cf->edt != NULL) {
1581     epan_dissect_free(cf->edt);
1582     cf->edt = NULL;
1583   }
1584   /* We don't need the columns here. */
1585   cf->edt = epan_dissect_new(TRUE, TRUE);
1586   epan_dissect_run(cf->edt, &cf->pseudo_header, cf->pd, cf->current_frame,
1587           NULL);
1588
1589   /* Display the GUI protocol tree and hex dump.
1590      XXX - why do we dump core if we call "proto_tree_draw()"
1591      before calling "add_byte_views()"? */
1592   add_byte_views(cf->edt, tree_view, byte_nb_ptr);
1593   proto_tree_draw(cf->edt->tree, tree_view);
1594
1595   /* A packet is selected. */
1596   set_menus_for_selected_packet(TRUE);
1597 }
1598
1599 /* Unselect the selected packet, if any. */
1600 void
1601 unselect_packet(capture_file *cf)
1602 {
1603   /* Destroy the epan_dissect_t for the unselected packet. */
1604   if (cf->edt != NULL) {
1605     epan_dissect_free(cf->edt);
1606     cf->edt = NULL;
1607   }
1608
1609   /* Clear out the display of that packet. */
1610   clear_tree_and_hex_views();
1611
1612   /* No packet is selected. */
1613   set_menus_for_selected_packet(FALSE);
1614
1615   /* No protocol tree means no selected field. */
1616   unselect_field();
1617 }
1618
1619 /* Set the selected row and the focus row of the packet list to the specified
1620    row, and make it visible if it's not currently visible. */
1621 static void
1622 set_selected_row(int row)
1623 {
1624   if (gtk_clist_row_is_visible(GTK_CLIST(packet_list), row) != GTK_VISIBILITY_FULL)
1625     gtk_clist_moveto(GTK_CLIST(packet_list), row, -1, 0.0, 0.0);
1626
1627   /* XXX - why is there no "gtk_clist_set_focus_row()", so that we
1628      can make the row for the frame we found the focus row?
1629
1630      See
1631
1632  http://www.gnome.org/mailing-lists/archives/gtk-list/2000-January/0038.shtml
1633
1634      */
1635   GTK_CLIST(packet_list)->focus_row = row;
1636
1637   gtk_clist_select_row(GTK_CLIST(packet_list), row, -1);
1638 }
1639
1640 /* Unset the selected protocol tree field, if any. */
1641 void
1642 unselect_field(void)
1643 {
1644   statusbar_pop_field_msg();
1645   finfo_selected = NULL;
1646   set_menus_for_selected_tree_row(FALSE);
1647 }
1648
1649 /*
1650  * Mark a particular frame.
1651  */
1652 void
1653 mark_frame(capture_file *cf, frame_data *frame)
1654 {
1655   frame->flags.marked = TRUE;
1656   cf->marked_count++;
1657 }
1658
1659 /*
1660  * Unmark a particular frame.
1661  */
1662 void
1663 unmark_frame(capture_file *cf, frame_data *frame)
1664 {
1665   frame->flags.marked = FALSE;
1666   cf->marked_count--;
1667 }
1668
1669 static void
1670 freeze_clist(capture_file *cf)
1671 {
1672   int i;
1673
1674   /* Make the column sizes static, so they don't adjust while
1675      we're reading the capture file (freezing the clist doesn't
1676      seem to suffice). */
1677   for (i = 0; i < cf->cinfo.num_cols; i++)
1678     gtk_clist_set_column_auto_resize(GTK_CLIST(packet_list), i, FALSE);
1679   gtk_clist_freeze(GTK_CLIST(packet_list));
1680 }
1681
1682 static void
1683 thaw_clist(capture_file *cf)
1684 {
1685   int i;
1686
1687   for (i = 0; i < cf->cinfo.num_cols; i++) {
1688     if (get_column_resize_type(cf->cinfo.col_fmt[i]) == RESIZE_MANUAL) {
1689       /* Set this column's width to the appropriate value. */
1690       gtk_clist_set_column_width(GTK_CLIST(packet_list), i,
1691                                 cf->cinfo.col_width[i]);
1692     } else {
1693       /* Make this column's size dynamic, so that it adjusts to the
1694          appropriate size. */
1695       gtk_clist_set_column_auto_resize(GTK_CLIST(packet_list), i, TRUE);
1696     }
1697   }
1698   gtk_clist_thaw(GTK_CLIST(packet_list));
1699
1700   /* Hopefully, the columns have now gotten their appropriate sizes;
1701      make them resizeable - a column that auto-resizes cannot be
1702      resized by the user, and *vice versa*. */
1703   for (i = 0; i < cf->cinfo.num_cols; i++)
1704     gtk_clist_set_column_resizeable(GTK_CLIST(packet_list), i, TRUE);
1705 }
1706
1707 /*
1708  * Save a capture to a file, in a particular format, saving either
1709  * all packets, all currently-displayed packets, or all marked packets.
1710  *
1711  * Returns TRUE if it succeeds, FALSE otherwise; if it fails, it pops
1712  * up a message box for the failure.
1713  */
1714 gboolean
1715 save_cap_file(char *fname, capture_file *cf, gboolean save_filtered,
1716                 gboolean save_marked, guint save_format)
1717 {
1718   gchar        *from_filename;
1719   gchar        *name_ptr, *save_msg, *save_fmt = " Saving: %s...";
1720   size_t        msg_len;
1721   int           err;
1722   gboolean      do_copy;
1723   wtap_dumper  *pdh;
1724   frame_data   *fdata;
1725   struct wtap_pkthdr hdr;
1726   union wtap_pseudo_header pseudo_header;
1727   guint8        pd[65536];
1728   struct stat   infile, outfile;
1729
1730   name_ptr = get_basename(fname);
1731   msg_len = strlen(name_ptr) + strlen(save_fmt) + 2;
1732   save_msg = g_malloc(msg_len);
1733   snprintf(save_msg, msg_len, save_fmt, name_ptr);
1734   statusbar_push_file_msg(save_msg);
1735   g_free(save_msg);
1736
1737   /* 
1738    * Check that the from file is not the same as to file 
1739    * We do it here so we catch all cases ...
1740    * Unfortunately, the file requester gives us an absolute file
1741    * name and the read file name may be relative (if supplied on
1742    * the command line). From Joerg Mayer.
1743    */
1744    infile.st_ino = 1;   /* These prevent us from getting equality         */
1745    outfile.st_ino = 2;  /* If one or other of the files is not accessible */
1746    stat(cf->filename, &infile);
1747    stat(fname, &outfile);
1748    if (infile.st_ino == outfile.st_ino) {
1749     simple_dialog(ESD_TYPE_CRIT, NULL, 
1750                       "Can't save over current capture file: %s!",
1751                       cf->filename);
1752     goto fail;
1753   }
1754
1755   if (!save_filtered && !save_marked && save_format == cf->cd_t) {
1756     /* We're not filtering packets, and we're saving it in the format
1757        it's already in, so we can just move or copy the raw data. */
1758
1759     if (cf->is_tempfile) {
1760       /* The file being saved is a temporary file from a live
1761          capture, so it doesn't need to stay around under that name;
1762          first, try renaming the capture buffer file to the new name. */
1763 #ifndef WIN32
1764       if (rename(cf->filename, fname) == 0) {
1765         /* That succeeded - there's no need to copy the source file. */
1766         from_filename = NULL;
1767         do_copy = FALSE;
1768       } else {
1769         if (errno == EXDEV) {
1770           /* They're on different file systems, so we have to copy the
1771              file. */
1772           do_copy = TRUE;
1773           from_filename = cf->filename;
1774         } else {
1775           /* The rename failed, but not because they're on different
1776              file systems - put up an error message.  (Or should we
1777              just punt and try to copy?  The only reason why I'd
1778              expect the rename to fail and the copy to succeed would
1779              be if we didn't have permission to remove the file from
1780              the temporary directory, and that might be fixable - but
1781              is it worth requiring the user to go off and fix it?) */
1782           simple_dialog(ESD_TYPE_CRIT, NULL,
1783                                 file_rename_error_message(errno), fname);
1784           goto fail;
1785         }
1786       }
1787 #else
1788       do_copy = TRUE;
1789       from_filename = cf->filename;
1790 #endif
1791     } else {
1792       /* It's a permanent file, so we should copy it, and not remove the
1793          original. */
1794       do_copy = TRUE;
1795       from_filename = cf->filename;
1796     }
1797
1798     if (do_copy) {
1799       /* Copy the file, if we haven't moved it. */
1800       if (!copy_binary_file(from_filename, fname))
1801         goto fail;
1802     }
1803   } else {
1804     /* Either we're filtering packets, or we're saving in a different
1805        format; we can't do that by copying or moving the capture file,
1806        we have to do it by writing the packets out in Wiretap. */
1807     pdh = wtap_dump_open(fname, save_format, cf->lnk_t, cf->snap, &err);
1808     if (pdh == NULL) {
1809       simple_dialog(ESD_TYPE_CRIT, NULL,
1810                         file_open_error_message(err, TRUE, save_format), fname);
1811       goto fail;
1812     }
1813
1814     /* XXX - have a way to save only the packets currently selected by
1815        the display filter or the marked ones.
1816
1817        If we do that, should we make that file the current file?  If so,
1818        it means we can no longer get at the other packets.  What does
1819        NetMon do? */
1820     for (fdata = cf->plist; fdata != NULL; fdata = fdata->next) {
1821       /* XXX - do a progress bar */
1822       if ((!save_filtered && !save_marked) ||
1823           (save_filtered && fdata->flags.passed_dfilter && !save_marked) ||
1824           (save_marked && fdata->flags.marked && !save_filtered) ||
1825           (save_filtered && save_marked && fdata->flags.passed_dfilter &&
1826            fdata->flags.marked)) {
1827         /* Either :
1828            - we're saving all frames, or
1829            - we're saving filtered frames and this one passed the display filter or
1830            - we're saving marked frames (and it has been marked) or
1831            - we're saving filtered _and_ marked frames,
1832            save it. */
1833         hdr.ts.tv_sec = fdata->abs_secs;
1834         hdr.ts.tv_usec = fdata->abs_usecs;
1835         hdr.caplen = fdata->cap_len;
1836         hdr.len = fdata->pkt_len;
1837         hdr.pkt_encap = fdata->lnk_t;
1838         if (!wtap_seek_read(cf->wth, fdata->file_off, &pseudo_header,
1839                 pd, fdata->cap_len, &err)) {
1840           simple_dialog(ESD_TYPE_CRIT, NULL,
1841                                 file_read_error_message(err), cf->filename);
1842           wtap_dump_close(pdh, &err);
1843           goto fail;
1844         }
1845
1846         if (!wtap_dump(pdh, &hdr, &pseudo_header, pd, &err)) {
1847           simple_dialog(ESD_TYPE_CRIT, NULL,
1848                                 file_write_error_message(err), fname);
1849           wtap_dump_close(pdh, &err);
1850           goto fail;
1851         }
1852       }
1853     }
1854
1855     if (!wtap_dump_close(pdh, &err)) {
1856       simple_dialog(ESD_TYPE_WARN, NULL,
1857                 file_close_error_message(err), fname);
1858       goto fail;
1859     }
1860   }
1861
1862   /* Pop the "Saving:" message off the status bar. */
1863   statusbar_pop_file_msg();
1864   if (!save_filtered && !save_marked) {
1865     /* We saved the entire capture, not just some packets from it.
1866        Open and read the file we saved it to.
1867
1868        XXX - this is somewhat of a waste; we already have the
1869        packets, all this gets us is updated file type information
1870        (which we could just stuff into "cf"), and having the new
1871        file be the one we have opened and from which we're reading
1872        the data, and it means we have to spend time opening and
1873        reading the file, which could be a significant amount of
1874        time if the file is large. */
1875     cf->user_saved = TRUE;
1876
1877     if ((err = open_cap_file(fname, FALSE, cf)) == 0) {
1878       /* XXX - report errors if this fails?
1879          What should we return if it fails or is aborted? */
1880       switch (read_cap_file(cf, &err)) {
1881
1882       case READ_SUCCESS:
1883       case READ_ERROR:
1884         /* Just because we got an error, that doesn't mean we were unable
1885            to read any of the file; we handle what we could get from the
1886            file. */
1887         break;
1888
1889       case READ_ABORTED:
1890         /* The user bailed out of re-reading the capture file; the
1891            capture file has been closed - just return (without
1892            changing any menu settings; "close_cap_file()" set them
1893            correctly for the "no capture file open" state). */
1894         break;
1895       }
1896       set_menus_for_unsaved_capture_file(FALSE);
1897     }
1898   }
1899   return TRUE;
1900
1901 fail:
1902   /* Pop the "Saving:" message off the status bar. */
1903   statusbar_pop_file_msg();
1904   return FALSE;
1905 }
1906
1907 char *
1908 file_open_error_message(int err, gboolean for_writing, int file_type)
1909 {
1910   char *errmsg;
1911   static char errmsg_errno[1024+1];
1912
1913   switch (err) {
1914
1915   case WTAP_ERR_NOT_REGULAR_FILE:
1916     errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
1917     break;
1918
1919   case WTAP_ERR_RANDOM_OPEN_PIPE:
1920     /* Seen only when opening a capture file for reading. */
1921     errmsg = "The file \"%s\" is a pipe or FIFO; Ethereal cannot read pipe or FIFO files.";
1922     break;
1923
1924   case WTAP_ERR_FILE_UNKNOWN_FORMAT:
1925   case WTAP_ERR_UNSUPPORTED:
1926     /* Seen only when opening a capture file for reading. */
1927     errmsg = "The file \"%s\" is not a capture file in a format Ethereal understands.";
1928     break;
1929
1930   case WTAP_ERR_CANT_WRITE_TO_PIPE:
1931     /* Seen only when opening a capture file for writing. */
1932     snprintf(errmsg_errno, sizeof(errmsg_errno),
1933              "The file \"%%s\" is a pipe, and %s capture files cannot be "
1934              "written to a pipe.", wtap_file_type_string(file_type));
1935     errmsg = errmsg_errno;
1936     break;
1937
1938   case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1939     /* Seen only when opening a capture file for writing. */
1940     errmsg = "Ethereal does not support writing capture files in that format.";
1941     break;
1942
1943   case WTAP_ERR_UNSUPPORTED_ENCAP:
1944   case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1945     if (for_writing)
1946       errmsg = "Ethereal cannot save this capture in that format.";
1947     else
1948       errmsg = "The file \"%s\" is a capture for a network type that Ethereal doesn't support.";
1949     break;
1950
1951   case WTAP_ERR_BAD_RECORD:
1952     errmsg = "The file \"%s\" appears to be damaged or corrupt.";
1953     break;
1954
1955   case WTAP_ERR_CANT_OPEN:
1956     if (for_writing)
1957       errmsg = "The file \"%s\" could not be created for some unknown reason.";
1958     else
1959       errmsg = "The file \"%s\" could not be opened for some unknown reason.";
1960     break;
1961
1962   case WTAP_ERR_SHORT_READ:
1963     errmsg = "The file \"%s\" appears to have been cut short"
1964              " in the middle of a packet or other data.";
1965     break;
1966
1967   case WTAP_ERR_SHORT_WRITE:
1968     errmsg = "A full header couldn't be written to the file \"%s\".";
1969     break;
1970
1971   case ENOENT:
1972     if (for_writing)
1973       errmsg = "The path to the file \"%s\" does not exist.";
1974     else
1975       errmsg = "The file \"%s\" does not exist.";
1976     break;
1977
1978   case EACCES:
1979     if (for_writing)
1980       errmsg = "You do not have permission to create or write to the file \"%s\".";
1981     else
1982       errmsg = "You do not have permission to read the file \"%s\".";
1983     break;
1984
1985   case EISDIR:
1986     errmsg = "\"%s\" is a directory (folder), not a file.";
1987     break;
1988
1989   default:
1990     snprintf(errmsg_errno, sizeof(errmsg_errno),
1991                     "The file \"%%s\" could not be %s: %s.",
1992                                 for_writing ? "created" : "opened",
1993                                 wtap_strerror(err));
1994     errmsg = errmsg_errno;
1995     break;
1996   }
1997   return errmsg;
1998 }
1999
2000 static char *
2001 file_rename_error_message(int err)
2002 {
2003   char *errmsg;
2004   static char errmsg_errno[1024+1];
2005
2006   switch (err) {
2007
2008   case ENOENT:
2009     errmsg = "The path to the file \"%s\" does not exist.";
2010     break;
2011
2012   case EACCES:
2013     errmsg = "You do not have permission to move the capture file to \"%s\".";
2014     break;
2015
2016   default:
2017     snprintf(errmsg_errno, sizeof(errmsg_errno),
2018                     "The file \"%%s\" could not be moved: %s.",
2019                                 wtap_strerror(err));
2020     errmsg = errmsg_errno;
2021     break;
2022   }
2023   return errmsg;
2024 }
2025
2026 char *
2027 file_read_error_message(int err)
2028 {
2029   static char errmsg_errno[1024+1];
2030
2031   snprintf(errmsg_errno, sizeof(errmsg_errno),
2032                   "An error occurred while reading from the file \"%%s\": %s.",
2033                                 wtap_strerror(err));
2034   return errmsg_errno;
2035 }
2036
2037 char *
2038 file_write_error_message(int err)
2039 {
2040   char *errmsg;
2041   static char errmsg_errno[1024+1];
2042
2043   switch (err) {
2044
2045   case ENOSPC:
2046     errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
2047     break;
2048
2049 #ifdef EDQUOT
2050   case EDQUOT:
2051     errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
2052     break;
2053 #endif
2054
2055   default:
2056     snprintf(errmsg_errno, sizeof(errmsg_errno),
2057                     "An error occurred while writing to the file \"%%s\": %s.",
2058                                 wtap_strerror(err));
2059     errmsg = errmsg_errno;
2060     break;
2061   }
2062   return errmsg;
2063 }
2064
2065 /* Check for write errors - if the file is being written to an NFS server,
2066    a write error may not show up until the file is closed, as NFS clients
2067    might not send writes to the server until the "write()" call finishes,
2068    so that the write may fail on the server but the "write()" may succeed. */
2069 static char *
2070 file_close_error_message(int err)
2071 {
2072   char *errmsg;
2073   static char errmsg_errno[1024+1];
2074
2075   switch (err) {
2076
2077   case WTAP_ERR_CANT_CLOSE:
2078     errmsg = "The file \"%s\" couldn't be closed for some unknown reason.";
2079     break;
2080
2081   case WTAP_ERR_SHORT_WRITE:
2082     errmsg = "Not all the packets could be written to the file \"%s\".";
2083     break;
2084
2085   case ENOSPC:
2086     errmsg = "The file \"%s\" could not be saved because there is no space left on the file system.";
2087     break;
2088
2089 #ifdef EDQUOT
2090   case EDQUOT:
2091     errmsg = "The file \"%s\" could not be saved because you are too close to, or over, your disk quota.";
2092     break;
2093 #endif
2094
2095   default:
2096     snprintf(errmsg_errno, sizeof(errmsg_errno),
2097                     "An error occurred while closing the file \"%%s\": %s.",
2098                                 wtap_strerror(err));
2099     errmsg = errmsg_errno;
2100     break;
2101   }
2102   return errmsg;
2103 }
2104
2105
2106 /* Copies a file in binary mode, for those operating systems that care about
2107  * such things.
2108  * Returns TRUE on success, FALSE on failure. If a failure, it also
2109  * displays a simple dialog window with the error message.
2110  */
2111 static gboolean
2112 copy_binary_file(char *from_filename, char *to_filename)
2113 {
2114         int           from_fd, to_fd, nread, nwritten, err;
2115         guint8        pd[65536]; /* XXX - Hmm, 64K here, 64K in save_cap_file(),
2116                                     perhaps we should make just one 64K buffer. */
2117
2118       /* Copy the raw bytes of the file. */
2119       from_fd = open(from_filename, O_RDONLY | O_BINARY);
2120       if (from_fd < 0) {
2121         err = errno;
2122         simple_dialog(ESD_TYPE_CRIT, NULL,
2123                         file_open_error_message(err, TRUE, 0), from_filename);
2124         goto done;
2125       }
2126
2127       /* Use open() instead of creat() so that we can pass the O_BINARY
2128          flag, which is relevant on Win32; it appears that "creat()"
2129          may open the file in text mode, not binary mode, but we want
2130          to copy the raw bytes of the file, so we need the output file
2131          to be open in binary mode. */
2132       to_fd = open(to_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
2133       if (to_fd < 0) {
2134         err = errno;
2135         simple_dialog(ESD_TYPE_CRIT, NULL,
2136                         file_open_error_message(err, TRUE, 0), to_filename);
2137         close(from_fd);
2138         goto done;
2139       }
2140
2141       while ((nread = read(from_fd, pd, sizeof pd)) > 0) {
2142         nwritten = write(to_fd, pd, nread);
2143         if (nwritten < nread) {
2144           if (nwritten < 0)
2145             err = errno;
2146           else
2147             err = WTAP_ERR_SHORT_WRITE;
2148           simple_dialog(ESD_TYPE_CRIT, NULL,
2149                                 file_write_error_message(err), to_filename);
2150           close(from_fd);
2151           close(to_fd);
2152           goto done;
2153         }
2154       }
2155       if (nread < 0) {
2156         err = errno;
2157         simple_dialog(ESD_TYPE_CRIT, NULL,
2158                         file_read_error_message(err), from_filename);
2159         close(from_fd);
2160         close(to_fd);
2161         goto done;
2162       }
2163       close(from_fd);
2164       if (close(to_fd) < 0) {
2165         err = errno;
2166         simple_dialog(ESD_TYPE_CRIT, NULL,
2167                 file_close_error_message(err), to_filename);
2168         goto done;
2169       }
2170
2171       return TRUE;
2172
2173    done:
2174       return FALSE;
2175 }