5248662d2ed18d4f083e54a5686916e25c57327d
[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_UNISTD_H
32 #include <unistd.h>
33 #endif
34
35 #ifdef HAVE_GETOPT_H
36 #include <getopt.h>
37 #endif
38
39 #ifdef HAVE_LIBZ
40 #include <zlib.h>      /* to get the libz version number */
41 #endif
42
43 #include "wtap.h"
44
45 #ifndef HAVE_GETOPT_LONG
46 #include "wsutil/wsgetopt.h"
47 #endif
48
49 #include <wsutil/file_util.h>
50 #include <wsutil/crash_info.h>
51 #include <wsutil/ws_version_info.h>
52
53 #include "version_info.h"
54
55 /* Show command-line usage */
56 static void
57 print_usage(FILE *output)
58 {
59     fprintf(output, "\n");
60     fprintf(output, "Usage: reordercap [options] <infile> <outfile>\n");
61     fprintf(output, "\n");
62     fprintf(output, "Options:\n");
63     fprintf(output, "  -n        don't write to output file if the input file is ordered.\n");
64     fprintf(output, "  -h        display this help and exit.\n");
65 }
66
67 /* Remember where this frame was in the file */
68 typedef struct FrameRecord_t {
69     gint64       offset;
70     guint        num;
71
72     nstime_t     time;
73 } FrameRecord_t;
74
75
76 /**************************************************/
77 /* Debugging only                                 */
78
79 /* Enable this symbol to see debug output */
80 /* #define REORDER_DEBUG */
81
82 #ifdef REORDER_DEBUG
83 #define DEBUG_PRINT printf
84 #else
85 #define DEBUG_PRINT(...)
86 #endif
87 /**************************************************/
88
89
90 static void
91 frame_write(FrameRecord_t *frame, wtap *wth, wtap_dumper *pdh,
92             struct wtap_pkthdr *phdr, Buffer *buf, const char *infile)
93 {
94     int    err;
95     gchar  *err_info;
96
97     DEBUG_PRINT("\nDumping frame (offset=%" G_GINT64_MODIFIER "u)\n",
98                 frame->offset);
99
100
101     /* Re-read the frame from the stored location */
102     if (!wtap_seek_read(wth, frame->offset, phdr, buf, &err, &err_info)) {
103         if (err != 0) {
104             /* Print a message noting that the read failed somewhere along the line. */
105             fprintf(stderr,
106                     "reordercap: An error occurred while re-reading \"%s\": %s.\n",
107                     infile, wtap_strerror(err));
108             if (err_info != NULL) {
109                 fprintf(stderr, "(%s)\n", err_info);
110                 g_free(err_info);
111             }
112             exit(1);
113         }
114     }
115
116     /* Copy, and set length and timestamp from item. */
117     /* TODO: remove when wtap_seek_read() fills in phdr,
118        including time stamps, for all file types  */
119     phdr->ts = frame->time;
120
121     /* Dump frame to outfile */
122     if (!wtap_dump(pdh, phdr, ws_buffer_start_ptr(buf), &err, &err_info)) {
123         fprintf(stderr, "reordercap: Error (%s) writing frame to outfile\n",
124                 wtap_strerror(err));
125         if (err_info != NULL) {
126             fprintf(stderr, "(%s)\n", err_info);
127             g_free(err_info);
128         }
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->time;
145     const nstime_t *time2 = &frame2->time;
146
147     return nstime_cmp(time1, time2);
148 }
149
150 static void
151 get_reordercap_compiled_info(GString *str)
152 {
153     /* LIBZ */
154     g_string_append(str, ", ");
155 #ifdef HAVE_LIBZ
156     g_string_append(str, "with libz ");
157 #ifdef ZLIB_VERSION
158     g_string_append(str, ZLIB_VERSION);
159 #else /* ZLIB_VERSION */
160     g_string_append(str, "(version unknown)");
161 #endif /* ZLIB_VERSION */
162 #else /* HAVE_LIBZ */
163     g_string_append(str, "without libz");
164 #endif /* HAVE_LIBZ */
165 }
166
167 static void
168 get_reordercap_runtime_info(GString *str)
169 {
170     /* zlib */
171 #if defined(HAVE_LIBZ) && !defined(_WIN32)
172     g_string_append_printf(str, ", with libz %s", zlibVersion());
173 #endif
174 }
175
176 /********************************************************************/
177 /* Main function.                                                   */
178 /********************************************************************/
179 int
180 main(int argc, char *argv[])
181 {
182     GString *comp_info_str;
183     GString *runtime_info_str;
184     wtap *wth = NULL;
185     wtap_dumper *pdh = NULL;
186     struct wtap_pkthdr dump_phdr;
187     Buffer buf;
188     int err;
189     gchar *err_info;
190     gint64 data_offset;
191     const struct wtap_pkthdr *phdr;
192     guint wrong_order_count = 0;
193     gboolean write_output_regardless = TRUE;
194     guint i;
195     wtapng_section_t            *shb_hdr;
196     wtapng_iface_descriptions_t *idb_inf;
197
198     GPtrArray *frames;
199     FrameRecord_t *prevFrame = NULL;
200
201     int opt;
202     static const struct option long_options[] = {
203         {(char *)"help", no_argument, NULL, 'h'},
204         {(char *)"version", no_argument, NULL, 'v'},
205         {0, 0, 0, 0 }
206     };
207     int file_count;
208     char *infile;
209     char *outfile;
210
211     /* Assemble the compile-time version information string */
212     comp_info_str = g_string_new("Compiled ");
213     get_compiled_version_info(comp_info_str, NULL, get_reordercap_compiled_info);
214
215     /* Assemble the run-time version information string */
216     runtime_info_str = g_string_new("Running ");
217     get_runtime_version_info(runtime_info_str, get_reordercap_runtime_info);
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
227     /* Process the options first */
228     while ((opt = getopt_long(argc, argv, "hnv", long_options, NULL)) != -1) {
229         switch (opt) {
230             case 'n':
231                 write_output_regardless = FALSE;
232                 break;
233             case 'h':
234                 printf("Reordercap (Wireshark) %s\n"
235                        "Reorder timestamps of input file frames into output file.\n"
236                        "See http://www.wireshark.org for more information.\n",
237                        get_ws_vcs_version_info());
238                 print_usage(stdout);
239                 exit(0);
240             case 'v':
241                 show_version("Reordercap (Wireshark)", comp_info_str, runtime_info_str);
242                 g_string_free(comp_info_str, TRUE);
243                 g_string_free(runtime_info_str, TRUE);
244                 exit(0);
245             case '?':
246                 print_usage(stderr);
247                 exit(1);
248         }
249     }
250
251     /* Remaining args are file names */
252     file_count = argc - optind;
253     if (file_count == 2) {
254         infile  = argv[optind];
255         outfile = argv[optind+1];
256     }
257     else {
258         print_usage(stderr);
259         exit(1);
260     }
261
262     /* Open infile */
263     /* TODO: if reordercap is ever changed to give the user a choice of which
264        open_routine reader to use, then the following needs to change. */
265     wth = wtap_open_offline(infile, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
266     if (wth == NULL) {
267         fprintf(stderr, "reordercap: Can't open %s: %s\n", infile,
268                 wtap_strerror(err));
269         if (err_info != NULL) {
270             fprintf(stderr, "(%s)\n", err_info);
271             g_free(err_info);
272         }
273         exit(1);
274     }
275     DEBUG_PRINT("file_type_subtype is %u\n", wtap_file_type_subtype(wth));
276
277     shb_hdr = wtap_file_get_shb_info(wth);
278     idb_inf = wtap_file_get_idb_info(wth);
279
280     /* Open outfile (same filetype/encap as input file) */
281     pdh = wtap_dump_open_ng(outfile, wtap_file_type_subtype(wth), wtap_file_encap(wth),
282                             65535, FALSE, shb_hdr, idb_inf, &err);
283     g_free(idb_inf);
284     if (pdh == NULL) {
285         fprintf(stderr, "reordercap: Failed to open output file: (%s) - error %s\n",
286                 outfile, wtap_strerror(err));
287         g_free(shb_hdr);
288         exit(1);
289     }
290
291     /* Allocate the array of frame pointers. */
292     frames = g_ptr_array_new();
293
294     /* Read each frame from infile */
295     while (wtap_read(wth, &err, &err_info, &data_offset)) {
296         FrameRecord_t *newFrameRecord;
297
298         phdr = wtap_phdr(wth);
299
300         newFrameRecord = g_slice_new(FrameRecord_t);
301         newFrameRecord->num = frames->len + 1;
302         newFrameRecord->offset = data_offset;
303         if (phdr->presence_flags & WTAP_HAS_TS) {
304             newFrameRecord->time = phdr->ts;
305         } else {
306             nstime_set_unset(&newFrameRecord->time);
307         }
308
309         if (prevFrame && frames_compare(&newFrameRecord, &prevFrame) < 0) {
310            wrong_order_count++;
311         }
312
313         g_ptr_array_add(frames, newFrameRecord);
314         prevFrame = newFrameRecord;
315     }
316     if (err != 0) {
317       /* Print a message noting that the read failed somewhere along the line. */
318       fprintf(stderr,
319               "reordercap: An error occurred while reading \"%s\": %s.\n",
320               infile, wtap_strerror(err));
321       if (err_info != NULL) {
322           fprintf(stderr, "(%s)\n", err_info);
323           g_free(err_info);
324       }
325     }
326
327     printf("%u frames, %u out of order\n", frames->len, wrong_order_count);
328
329     /* Sort the frames */
330     if (wrong_order_count > 0) {
331         g_ptr_array_sort(frames, frames_compare);
332     }
333
334     /* Write out each sorted frame in turn */
335     wtap_phdr_init(&dump_phdr);
336     ws_buffer_init(&buf, 1500);
337     for (i = 0; i < frames->len; i++) {
338         FrameRecord_t *frame = (FrameRecord_t *)frames->pdata[i];
339
340         /* Avoid writing if already sorted and configured to */
341         if (write_output_regardless || (wrong_order_count > 0)) {
342             frame_write(frame, wth, pdh, &dump_phdr, &buf, infile);
343         }
344         g_slice_free(FrameRecord_t, frame);
345     }
346     wtap_phdr_cleanup(&dump_phdr);
347     ws_buffer_free(&buf);
348
349     if (!write_output_regardless && (wrong_order_count == 0)) {
350         printf("Not writing output file because input file is already in order!\n");
351     }
352
353     /* Free the whole array */
354     g_ptr_array_free(frames, TRUE);
355
356     /* Close outfile */
357     if (!wtap_dump_close(pdh, &err)) {
358         fprintf(stderr, "reordercap: Error closing %s: %s\n", outfile,
359                 wtap_strerror(err));
360         g_free(shb_hdr);
361         exit(1);
362     }
363     g_free(shb_hdr);
364
365     /* Finally, close infile */
366     wtap_fdclose(wth);
367
368     return 0;
369 }
370
371 /*
372  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
373  *
374  * Local variables:
375  * c-basic-offset: 4
376  * tab-width: 8
377  * indent-tabs-mode: nil
378  * End:
379  *
380  * vi: set shiftwidth=4 tabstop=8 expandtab:
381  * :indentSize=4:tabSize=8:noTabs=true:
382  */