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