docbook: put a space after PS prompts.
[gd/wireshark/.git] / ringbuffer.c
1 /* ringbuffer.c
2  * Routines for packet capture windows
3  *
4  * Wireshark - Network traffic analyzer
5  * By Gerald Combs <gerald@wireshark.org>
6  * Copyright 1998 Gerald Combs
7  *
8  * SPDX-License-Identifier: GPL-2.0-or-later
9  */
10
11 /*
12  * <laurent.deniel@free.fr>
13  *
14  * Almost completely rewritten in order to:
15  *
16  * - be able to use a unlimited number of ringbuffer files
17  * - close the current file and open (truncating) the next file at switch
18  * - set the final file name once open (or reopen)
19  * - avoid the deletion of files that could not be truncated (can't arise now)
20  *   and do not erase empty files
21  *
22  * The idea behind that is to remove the limitation of the maximum # of
23  * ringbuffer files being less than the maximum # of open fd per process
24  * and to be able to reduce the amount of virtual memory usage (having only
25  * one file open at most) or the amount of file system usage (by truncating
26  * the files at switch and not the capture stop, and by closing them which
27  * makes possible their move or deletion after a switch).
28  *
29  */
30
31 #include <config.h>
32
33 #ifdef HAVE_LIBPCAP
34
35 #include <stdio.h>
36 #include <string.h>
37 #include <time.h>
38 #include <errno.h>
39
40 #include "wspcap.h"
41
42 #include <glib.h>
43
44 #include "ringbuffer.h"
45 #include <wsutil/file_util.h>
46
47
48 /* Ringbuffer file structure */
49 typedef struct _rb_file {
50   gchar         *name;
51 } rb_file;
52
53 /** Ringbuffer data structure */
54 typedef struct _ringbuf_data {
55   rb_file      *files;
56   guint         num_files;           /**< Number of ringbuffer files (1 to ...) */
57   guint         curr_file_num;       /**< Number of the current file (ever increasing) */
58   gchar        *fprefix;             /**< Filename prefix */
59   gchar        *fsuffix;             /**< Filename suffix */
60   gboolean      unlimited;           /**< TRUE if unlimited number of files */
61
62   int           fd;                  /**< Current ringbuffer file descriptor */
63   FILE         *pdh;
64   char         *io_buffer;              /**< The IO buffer used to write to the file */
65   gboolean      group_read_access;   /**< TRUE if files need to be opened with group read access */
66 } ringbuf_data;
67
68 static ringbuf_data rb_data;
69
70
71 /*
72  * create the next filename and open a new binary file with that name
73  */
74 static int ringbuf_open_file(rb_file *rfile, int *err)
75 {
76   char    filenum[5+1];
77   char    timestr[14+1];
78   time_t  current_time;
79   struct tm *tm;
80
81   if (rfile->name != NULL) {
82     if (rb_data.unlimited == FALSE) {
83       /* remove old file (if any, so ignore error) */
84       ws_unlink(rfile->name);
85     }
86     g_free(rfile->name);
87   }
88
89 #ifdef _WIN32
90   _tzset();
91 #endif
92   current_time = time(NULL);
93
94   g_snprintf(filenum, sizeof(filenum), "%05u", (rb_data.curr_file_num + 1) % RINGBUFFER_MAX_NUM_FILES);
95   tm = localtime(&current_time);
96   if (tm != NULL)
97     strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", tm);
98   else
99     g_strlcpy(timestr, "196912312359", sizeof(timestr)); /* second before the Epoch */
100   rfile->name = g_strconcat(rb_data.fprefix, "_", filenum, "_", timestr,
101                             rb_data.fsuffix, NULL);
102
103   if (rfile->name == NULL) {
104     if (err != NULL)
105       *err = ENOMEM;
106     return -1;
107   }
108
109   rb_data.fd = ws_open(rfile->name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
110                             rb_data.group_read_access ? 0640 : 0600);
111
112   if (rb_data.fd == -1 && err != NULL) {
113     *err = errno;
114   }
115
116   return rb_data.fd;
117 }
118
119 /*
120  * Initialize the ringbuffer data structures
121  */
122 int
123 ringbuf_init(const char *capfile_name, guint num_files, gboolean group_read_access)
124 {
125   unsigned int i;
126   char        *pfx, *last_pathsep;
127   gchar       *save_file;
128
129   rb_data.files = NULL;
130   rb_data.curr_file_num = 0;
131   rb_data.fprefix = NULL;
132   rb_data.fsuffix = NULL;
133   rb_data.unlimited = FALSE;
134   rb_data.fd = -1;
135   rb_data.pdh = NULL;
136   rb_data.io_buffer = NULL;
137   rb_data.group_read_access = group_read_access;
138
139   /* just to be sure ... */
140   if (num_files <= RINGBUFFER_MAX_NUM_FILES) {
141     rb_data.num_files = num_files;
142   } else {
143     rb_data.num_files = RINGBUFFER_MAX_NUM_FILES;
144   }
145
146   /* Check file name */
147   if (capfile_name == NULL) {
148     /* ringbuffer does not work with temporary files! */
149     return -1;
150   }
151
152   /* set file name prefix/suffix */
153
154   save_file = g_strdup(capfile_name);
155   last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
156   pfx = strrchr(save_file,'.');
157   if (pfx != NULL && (last_pathsep == NULL || pfx > last_pathsep)) {
158     /* The pathname has a "." in it, and it's in the last component
159        of the pathname (because there is either only one component,
160        i.e. last_pathsep is null as there are no path separators,
161        or the "." is after the path separator before the last
162        component.
163
164        Treat it as a separator between the rest of the file name and
165        the file name suffix, and arrange that the names given to the
166        ring buffer files have the specified suffix, i.e. put the
167        changing part of the name *before* the suffix. */
168     pfx[0] = '\0';
169     rb_data.fprefix = g_strdup(save_file);
170     pfx[0] = '.'; /* restore capfile_name */
171     rb_data.fsuffix = g_strdup(pfx);
172   } else {
173     /* Either there's no "." in the pathname, or it's in a directory
174        component, so the last component has no suffix. */
175     rb_data.fprefix = g_strdup(save_file);
176     rb_data.fsuffix = NULL;
177   }
178   g_free(save_file);
179   save_file = NULL;
180
181   /* allocate rb_file structures (only one if unlimited since there is no
182      need to save all file names in that case) */
183
184   if (num_files == RINGBUFFER_UNLIMITED_FILES) {
185     rb_data.unlimited = TRUE;
186     rb_data.num_files = 1;
187   }
188
189   rb_data.files = (rb_file *)g_malloc(rb_data.num_files * sizeof(rb_file));
190   if (rb_data.files == NULL) {
191     return -1;
192   }
193
194   for (i=0; i < rb_data.num_files; i++) {
195     rb_data.files[i].name = NULL;
196   }
197
198   /* create the first file */
199   if (ringbuf_open_file(&rb_data.files[0], NULL) == -1) {
200     ringbuf_error_cleanup();
201     return -1;
202   }
203
204   return rb_data.fd;
205 }
206
207
208 /*
209  * Whether the ringbuf filenames are ready.
210  * (Whether ringbuf_init is called and ringbuf_free is not called.)
211  */
212 gboolean ringbuf_is_initialized(void)
213 {
214   return rb_data.files != NULL;
215 }
216
217 const gchar *ringbuf_current_filename(void)
218 {
219   /* g_assert(ringbuf_is_initialized()); */
220   return rb_data.files[rb_data.curr_file_num % rb_data.num_files].name;
221 }
222
223 /*
224  * Calls ws_fdopen() for the current ringbuffer file
225  */
226 FILE *
227 ringbuf_init_libpcap_fdopen(int *err)
228 {
229   rb_data.pdh = ws_fdopen(rb_data.fd, "wb");
230   if (rb_data.pdh == NULL) {
231     if (err != NULL) {
232       *err = errno;
233     }
234   } else {
235     size_t buffsize = IO_BUF_SIZE;
236 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
237     ws_statb64 statb;
238
239     if (ws_fstat64(rb_data.fd, &statb) == 0) {
240       if (statb.st_blksize > IO_BUF_SIZE) {
241         buffsize = statb.st_blksize;
242       }
243     }
244 #endif
245     /* Increase the size of the IO buffer */
246     rb_data.io_buffer = (char *)g_realloc(rb_data.io_buffer, buffsize);
247     setvbuf(rb_data.pdh, rb_data.io_buffer, _IOFBF, buffsize);
248   }
249
250   return rb_data.pdh;
251 }
252
253 /*
254  * Switches to the next ringbuffer file
255  */
256 gboolean
257 ringbuf_switch_file(FILE **pdh, gchar **save_file, int *save_file_fd, int *err)
258 {
259   int     next_file_index;
260   rb_file *next_rfile = NULL;
261
262   /* close current file */
263
264   if (fclose(rb_data.pdh) == EOF) {
265     if (err != NULL) {
266       *err = errno;
267     }
268     ws_close(rb_data.fd);  /* XXX - the above should have closed this already */
269     rb_data.pdh = NULL;    /* it's still closed, we just got an error while closing */
270     rb_data.fd = -1;
271     g_free(rb_data.io_buffer);
272     rb_data.io_buffer = NULL;
273     return FALSE;
274   }
275
276   rb_data.pdh = NULL;
277   rb_data.fd  = -1;
278
279   /* get the next file number and open it */
280
281   rb_data.curr_file_num++ /* = next_file_num*/;
282   next_file_index = (rb_data.curr_file_num) % rb_data.num_files;
283   next_rfile = &rb_data.files[next_file_index];
284
285   if (ringbuf_open_file(next_rfile, err) == -1) {
286     return FALSE;
287   }
288
289   if (ringbuf_init_libpcap_fdopen(err) == NULL) {
290     return FALSE;
291   }
292
293   /* switch to the new file */
294   *save_file = next_rfile->name;
295   *save_file_fd = rb_data.fd;
296   (*pdh) = rb_data.pdh;
297
298   return TRUE;
299 }
300
301 /*
302  * Calls fclose() for the current ringbuffer file
303  */
304 gboolean
305 ringbuf_libpcap_dump_close(gchar **save_file, int *err)
306 {
307   gboolean  ret_val = TRUE;
308
309   /* close current file, if it's open */
310   if (rb_data.pdh != NULL) {
311     if (fclose(rb_data.pdh) == EOF) {
312       if (err != NULL) {
313         *err = errno;
314       }
315       ws_close(rb_data.fd);
316       ret_val = FALSE;
317     }
318     rb_data.pdh = NULL;
319     rb_data.fd  = -1;
320     g_free(rb_data.io_buffer);
321     rb_data.io_buffer = NULL;
322
323   }
324
325   /* set the save file name to the current file */
326   *save_file = rb_data.files[rb_data.curr_file_num % rb_data.num_files].name;
327   return ret_val;
328 }
329
330 /*
331  * Frees all memory allocated by the ringbuffer
332  */
333 void
334 ringbuf_free(void)
335 {
336   unsigned int i;
337
338   if (rb_data.files != NULL) {
339     for (i=0; i < rb_data.num_files; i++) {
340       if (rb_data.files[i].name != NULL) {
341         g_free(rb_data.files[i].name);
342         rb_data.files[i].name = NULL;
343       }
344     }
345     g_free(rb_data.files);
346     rb_data.files = NULL;
347   }
348   if (rb_data.fprefix != NULL) {
349     g_free(rb_data.fprefix);
350     rb_data.fprefix = NULL;
351   }
352   if (rb_data.fsuffix != NULL) {
353     g_free(rb_data.fsuffix);
354     rb_data.fsuffix = NULL;
355   }
356 }
357
358 /*
359  * Frees all memory allocated by the ringbuffer
360  */
361 void
362 ringbuf_error_cleanup(void)
363 {
364   unsigned int i;
365
366   /* try to close via wtap */
367   if (rb_data.pdh != NULL) {
368     if (fclose(rb_data.pdh) == 0) {
369       rb_data.fd = -1;
370     }
371     rb_data.pdh = NULL;
372   }
373
374   /* close directly if still open */
375   if (rb_data.fd != -1) {
376     ws_close(rb_data.fd);
377     rb_data.fd = -1;
378   }
379
380   if (rb_data.files != NULL) {
381     for (i=0; i < rb_data.num_files; i++) {
382       if (rb_data.files[i].name != NULL) {
383         ws_unlink(rb_data.files[i].name);
384       }
385     }
386   }
387   g_free(rb_data.io_buffer);
388   rb_data.io_buffer = NULL;
389
390   /* free the memory */
391   ringbuf_free();
392 }
393
394 #endif /* HAVE_LIBPCAP */
395
396 /*
397  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
398  *
399  * Local Variables:
400  * c-basic-offset: 2
401  * tab-width: 8
402  * indent-tabs-mode: nil
403  * End:
404  *
405  * ex: set shiftwidth=2 tabstop=8 expandtab:
406  * :indentSize=2:tabSize=8:noTabs=true:
407  */