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