NBAP: Fix style issues in .cnf
[metze/wireshark/wip.git] / reordercap.c
1 /* Reorder the frames from an input dump file, and write to output dump file.
2  * Martin Mathieson and Jakub Jawadzki
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 #include <config.h>
12
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <glib.h>
17
18 #ifdef HAVE_GETOPT_H
19 #include <getopt.h>
20 #endif
21
22 #include <wiretap/wtap.h>
23
24 #ifndef HAVE_GETOPT_LONG
25 #include "wsutil/wsgetopt.h"
26 #endif
27
28 #include <wsutil/cmdarg_err.h>
29 #include <wsutil/crash_info.h>
30 #include <wsutil/filesystem.h>
31 #include <wsutil/file_util.h>
32 #include <wsutil/privileges.h>
33 #include <version_info.h>
34 #include <wiretap/wtap_opttypes.h>
35
36 #ifdef HAVE_PLUGINS
37 #include <wsutil/plugins.h>
38 #endif
39
40 #include <wsutil/report_message.h>
41
42 #include "ui/failure_message.h"
43
44 #define INVALID_OPTION 1
45 #define OPEN_ERROR 2
46 #define OUTPUT_FILE_ERROR 1
47
48 /* Show command-line usage */
49 static void
50 print_usage(FILE *output)
51 {
52     fprintf(output, "\n");
53     fprintf(output, "Usage: reordercap [options] <infile> <outfile>\n");
54     fprintf(output, "\n");
55     fprintf(output, "Options:\n");
56     fprintf(output, "  -n        don't write to output file if the input file is ordered.\n");
57     fprintf(output, "  -h        display this help and exit.\n");
58 }
59
60 /* Remember where this frame was in the file */
61 typedef struct FrameRecord_t {
62     gint64       offset;
63     guint        num;
64
65     nstime_t     frame_time;
66 } FrameRecord_t;
67
68
69 /**************************************************/
70 /* Debugging only                                 */
71
72 /* Enable this symbol to see debug output */
73 /* #define REORDER_DEBUG */
74
75 #ifdef REORDER_DEBUG
76 #define DEBUG_PRINT printf
77 #else
78 #define DEBUG_PRINT(...)
79 #endif
80 /**************************************************/
81
82
83 static void
84 frame_write(FrameRecord_t *frame, wtap *wth, wtap_dumper *pdh,
85             wtap_rec *rec, Buffer *buf, const char *infile,
86             const char *outfile)
87 {
88     int    err;
89     gchar  *err_info;
90
91     DEBUG_PRINT("\nDumping frame (offset=%" G_GINT64_MODIFIER "u)\n",
92                 frame->offset);
93
94
95     /* Re-read the frame from the stored location */
96     if (!wtap_seek_read(wth, frame->offset, rec, buf, &err, &err_info)) {
97         if (err != 0) {
98             /* Print a message noting that the read failed somewhere along the line. */
99             fprintf(stderr,
100                     "reordercap: An error occurred while re-reading \"%s\".\n",
101                     infile);
102             cfile_read_failure_message("reordercap", infile, err, err_info);
103             exit(1);
104         }
105     }
106
107     /* Copy, and set length and timestamp from item. */
108     /* TODO: remove when wtap_seek_read() fills in rec,
109        including time stamps, for all file types  */
110     rec->ts = frame->frame_time;
111
112     /* Dump frame to outfile */
113     if (!wtap_dump(pdh, rec, ws_buffer_start_ptr(buf), &err, &err_info)) {
114         cfile_write_failure_message("reordercap", infile, outfile, err,
115                                     err_info, frame->num,
116                                     wtap_file_type_subtype(wth));
117         exit(1);
118     }
119 }
120
121 /* Comparing timestamps between 2 frames.
122    negative if (t1 < t2)
123    zero     if (t1 == t2)
124    positive if (t1 > t2)
125 */
126 static int
127 frames_compare(gconstpointer a, gconstpointer b)
128 {
129     const FrameRecord_t *frame1 = *(const FrameRecord_t *const *) a;
130     const FrameRecord_t *frame2 = *(const FrameRecord_t *const *) b;
131
132     const nstime_t *time1 = &frame1->frame_time;
133     const nstime_t *time2 = &frame2->frame_time;
134
135     return nstime_cmp(time1, time2);
136 }
137
138 /*
139  * General errors and warnings are reported with an console message
140  * in reordercap.
141  */
142 static void
143 failure_warning_message(const char *msg_format, va_list ap)
144 {
145     fprintf(stderr, "reordercap: ");
146     vfprintf(stderr, msg_format, ap);
147     fprintf(stderr, "\n");
148 }
149
150 /*
151  * Report additional information for an error in command-line arguments.
152  */
153 static void
154 failure_message_cont(const char *msg_format, va_list ap)
155 {
156     vfprintf(stderr, msg_format, ap);
157     fprintf(stderr, "\n");
158 }
159
160 /********************************************************************/
161 /* Main function.                                                   */
162 /********************************************************************/
163 int
164 main(int argc, char *argv[])
165 {
166     GString *comp_info_str;
167     GString *runtime_info_str;
168     char *init_progfile_dir_error;
169     wtap *wth = NULL;
170     wtap_dumper *pdh = NULL;
171     wtap_rec dump_rec;
172     Buffer buf;
173     int err;
174     gchar *err_info;
175     gint64 data_offset;
176     const wtap_rec *rec;
177     guint wrong_order_count = 0;
178     gboolean write_output_regardless = TRUE;
179     guint i;
180     GArray                      *shb_hdrs = NULL;
181     wtapng_iface_descriptions_t *idb_inf = NULL;
182     GArray                      *nrb_hdrs = NULL;
183     int                          ret = EXIT_SUCCESS;
184
185     GPtrArray *frames;
186     FrameRecord_t *prevFrame = NULL;
187
188     int opt;
189     static const struct option long_options[] = {
190         {"help", no_argument, NULL, 'h'},
191         {"version", no_argument, NULL, 'v'},
192         {0, 0, 0, 0 }
193     };
194     int file_count;
195     char *infile;
196     const char *outfile;
197
198     cmdarg_err_init(failure_warning_message, failure_message_cont);
199
200     /* Get the compile-time version information string */
201     comp_info_str = get_compiled_version_info(NULL, NULL);
202
203     /* Get the run-time version information string */
204     runtime_info_str = get_runtime_version_info(NULL);
205
206     /* Add it to the information to be reported on a crash. */
207     ws_add_crash_info("Reordercap (Wireshark) %s\n"
208          "\n"
209          "%s"
210          "\n"
211          "%s",
212       get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
213     g_string_free(comp_info_str, TRUE);
214     g_string_free(runtime_info_str, TRUE);
215
216     /*
217      * Get credential information for later use.
218      */
219     init_process_policies();
220
221     /*
222      * Attempt to get the pathname of the directory containing the
223      * executable file.
224      */
225     init_progfile_dir_error = init_progfile_dir(argv[0]);
226     if (init_progfile_dir_error != NULL) {
227         fprintf(stderr,
228                 "reordercap: Can't get pathname of directory containing the reordercap program: %s.\n",
229                 init_progfile_dir_error);
230         g_free(init_progfile_dir_error);
231     }
232
233     init_report_message(failure_warning_message, failure_warning_message,
234                         NULL, NULL, NULL);
235
236     wtap_init(TRUE);
237
238     /* Process the options first */
239     while ((opt = getopt_long(argc, argv, "hnv", long_options, NULL)) != -1) {
240         switch (opt) {
241             case 'n':
242                 write_output_regardless = FALSE;
243                 break;
244             case 'h':
245                 printf("Reordercap (Wireshark) %s\n"
246                        "Reorder timestamps of input file frames into output file.\n"
247                        "See https://www.wireshark.org for more information.\n",
248                        get_ws_vcs_version_info());
249                 print_usage(stdout);
250                 goto clean_exit;
251             case 'v':
252                 comp_info_str = get_compiled_version_info(NULL, NULL);
253                 runtime_info_str = get_runtime_version_info(NULL);
254                 show_version("Reordercap (Wireshark)", comp_info_str, runtime_info_str);
255                 g_string_free(comp_info_str, TRUE);
256                 g_string_free(runtime_info_str, TRUE);
257                 goto clean_exit;
258             case '?':
259                 print_usage(stderr);
260                 ret = INVALID_OPTION;
261                 goto clean_exit;
262         }
263     }
264
265     /* Remaining args are file names */
266     file_count = argc - optind;
267     if (file_count == 2) {
268         infile  = argv[optind];
269         outfile = argv[optind+1];
270     }
271     else {
272         print_usage(stderr);
273         ret = INVALID_OPTION;
274         goto clean_exit;
275     }
276
277     /* Open infile */
278     /* TODO: if reordercap is ever changed to give the user a choice of which
279        open_routine reader to use, then the following needs to change. */
280     wth = wtap_open_offline(infile, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
281     if (wth == NULL) {
282         cfile_open_failure_message("reordercap", infile, err, err_info);
283         ret = OPEN_ERROR;
284         goto clean_exit;
285     }
286     DEBUG_PRINT("file_type_subtype is %d\n", wtap_file_type_subtype(wth));
287
288     shb_hdrs = wtap_file_get_shb_for_new_file(wth);
289     idb_inf = wtap_file_get_idb_info(wth);
290     nrb_hdrs = wtap_file_get_nrb_for_new_file(wth);
291
292     /* Open outfile (same filetype/encap as input file) */
293     if (strcmp(outfile, "-") == 0) {
294       pdh = wtap_dump_open_stdout_ng(wtap_file_type_subtype(wth), wtap_file_encap(wth),
295                                      wtap_snapshot_length(wth), FALSE, shb_hdrs, idb_inf, nrb_hdrs, &err);
296     } else {
297       pdh = wtap_dump_open_ng(outfile, wtap_file_type_subtype(wth), wtap_file_encap(wth),
298                               wtap_snapshot_length(wth), FALSE, shb_hdrs, idb_inf, nrb_hdrs, &err);
299     }
300     g_free(idb_inf);
301     idb_inf = NULL;
302
303     if (pdh == NULL) {
304         cfile_dump_open_failure_message("reordercap", outfile, err,
305                                         wtap_file_type_subtype(wth));
306         wtap_block_array_free(shb_hdrs);
307         wtap_block_array_free(nrb_hdrs);
308         ret = OUTPUT_FILE_ERROR;
309         goto clean_exit;
310     }
311
312     /* Allocate the array of frame pointers. */
313     frames = g_ptr_array_new();
314
315     /* Read each frame from infile */
316     while (wtap_read(wth, &err, &err_info, &data_offset)) {
317         FrameRecord_t *newFrameRecord;
318
319         rec = wtap_get_rec(wth);
320
321         newFrameRecord = g_slice_new(FrameRecord_t);
322         newFrameRecord->num = frames->len + 1;
323         newFrameRecord->offset = data_offset;
324         if (rec->presence_flags & WTAP_HAS_TS) {
325             newFrameRecord->frame_time = rec->ts;
326         } else {
327             nstime_set_unset(&newFrameRecord->frame_time);
328         }
329
330         if (prevFrame && frames_compare(&newFrameRecord, &prevFrame) < 0) {
331            wrong_order_count++;
332         }
333
334         g_ptr_array_add(frames, newFrameRecord);
335         prevFrame = newFrameRecord;
336     }
337     if (err != 0) {
338       /* Print a message noting that the read failed somewhere along the line. */
339       cfile_read_failure_message("reordercap", infile, err, err_info);
340     }
341
342     printf("%u frames, %u out of order\n", frames->len, wrong_order_count);
343
344     /* Sort the frames */
345     if (wrong_order_count > 0) {
346         g_ptr_array_sort(frames, frames_compare);
347     }
348
349     /* Write out each sorted frame in turn */
350     wtap_rec_init(&dump_rec);
351     ws_buffer_init(&buf, 1500);
352     for (i = 0; i < frames->len; i++) {
353         FrameRecord_t *frame = (FrameRecord_t *)frames->pdata[i];
354
355         /* Avoid writing if already sorted and configured to */
356         if (write_output_regardless || (wrong_order_count > 0)) {
357             frame_write(frame, wth, pdh, &dump_rec, &buf, infile, outfile);
358         }
359         g_slice_free(FrameRecord_t, frame);
360     }
361     wtap_rec_cleanup(&dump_rec);
362     ws_buffer_free(&buf);
363
364     if (!write_output_regardless && (wrong_order_count == 0)) {
365         printf("Not writing output file because input file is already in order.\n");
366     }
367
368     /* Free the whole array */
369     g_ptr_array_free(frames, TRUE);
370
371     /* Close outfile */
372     if (!wtap_dump_close(pdh, &err)) {
373         cfile_close_failure_message(outfile, err);
374         wtap_block_array_free(shb_hdrs);
375         wtap_block_array_free(nrb_hdrs);
376         ret = OUTPUT_FILE_ERROR;
377         goto clean_exit;
378     }
379     wtap_block_array_free(shb_hdrs);
380     wtap_block_array_free(nrb_hdrs);
381
382     /* Finally, close infile and release resources. */
383     wtap_close(wth);
384
385 clean_exit:
386     wtap_cleanup();
387     free_progdirs();
388     return ret;
389 }
390
391 /*
392  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
393  *
394  * Local variables:
395  * c-basic-offset: 4
396  * tab-width: 8
397  * indent-tabs-mode: nil
398  * End:
399  *
400  * vi: set shiftwidth=4 tabstop=8 expandtab:
401  * :indentSize=4:tabSize=8:noTabs=true:
402  */