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