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