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