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