Fix Wai dissector
[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/crash_info.h>
50 #include <wsutil/file_util.h>
51 #include <wsutil/ws_diag_control.h>
52 #include <wsutil/ws_version_info.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     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->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->time;
144     const nstime_t *time2 = &frame2->time;
145
146     return nstime_cmp(time1, time2);
147 }
148
149 static void
150 get_reordercap_compiled_info(GString *str)
151 {
152     /* LIBZ */
153     g_string_append(str, ", ");
154 #ifdef HAVE_LIBZ
155     g_string_append(str, "with libz ");
156 #ifdef ZLIB_VERSION
157     g_string_append(str, ZLIB_VERSION);
158 #else /* ZLIB_VERSION */
159     g_string_append(str, "(version unknown)");
160 #endif /* ZLIB_VERSION */
161 #else /* HAVE_LIBZ */
162     g_string_append(str, "without libz");
163 #endif /* HAVE_LIBZ */
164 }
165
166 static void
167 get_reordercap_runtime_info(GString *str)
168 {
169     /* zlib */
170 #if defined(HAVE_LIBZ) && !defined(_WIN32)
171     g_string_append_printf(str, ", with libz %s", zlibVersion());
172 #endif
173 }
174
175 /********************************************************************/
176 /* Main function.                                                   */
177 /********************************************************************/
178 int
179 main(int argc, char *argv[])
180 {
181     GString *comp_info_str;
182     GString *runtime_info_str;
183     wtap *wth = NULL;
184     wtap_dumper *pdh = NULL;
185     struct wtap_pkthdr dump_phdr;
186     Buffer buf;
187     int err;
188     gchar *err_info;
189     gint64 data_offset;
190     const struct wtap_pkthdr *phdr;
191     guint wrong_order_count = 0;
192     gboolean write_output_regardless = TRUE;
193     guint i;
194     wtapng_section_t            *shb_hdr;
195     wtapng_iface_descriptions_t *idb_inf;
196
197     GPtrArray *frames;
198     FrameRecord_t *prevFrame = NULL;
199
200     int opt;
201 DIAG_OFF(cast-qual)
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 DIAG_ON(cast-qual)
208     int file_count;
209     char *infile;
210     char *outfile;
211
212     /* Get the compile-time version information string */
213     comp_info_str = get_compiled_version_info(NULL, get_reordercap_compiled_info);
214
215     /* Get the run-time version information string */
216     runtime_info_str = get_runtime_version_info(get_reordercap_runtime_info);
217
218     /* Add it to the information to be reported on a crash. */
219     ws_add_crash_info("Reordercap (Wireshark) %s\n"
220          "\n"
221          "%s"
222          "\n"
223          "%s",
224       get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
225
226     /* Process the options first */
227     while ((opt = getopt_long(argc, argv, "hnv", long_options, NULL)) != -1) {
228         switch (opt) {
229             case 'n':
230                 write_output_regardless = FALSE;
231                 break;
232             case 'h':
233                 printf("Reordercap (Wireshark) %s\n"
234                        "Reorder timestamps of input file frames into output file.\n"
235                        "See http://www.wireshark.org for more information.\n",
236                        get_ws_vcs_version_info());
237                 print_usage(stdout);
238                 exit(0);
239             case 'v':
240                 show_version("Reordercap (Wireshark)", comp_info_str, runtime_info_str);
241                 g_string_free(comp_info_str, TRUE);
242                 g_string_free(runtime_info_str, TRUE);
243                 exit(0);
244             case '?':
245                 print_usage(stderr);
246                 exit(1);
247         }
248     }
249
250     /* Remaining args are file names */
251     file_count = argc - optind;
252     if (file_count == 2) {
253         infile  = argv[optind];
254         outfile = argv[optind+1];
255     }
256     else {
257         print_usage(stderr);
258         exit(1);
259     }
260
261     /* Open infile */
262     /* TODO: if reordercap is ever changed to give the user a choice of which
263        open_routine reader to use, then the following needs to change. */
264     wth = wtap_open_offline(infile, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
265     if (wth == NULL) {
266         fprintf(stderr, "reordercap: Can't open %s: %s\n", infile,
267                 wtap_strerror(err));
268         if (err_info != NULL) {
269             fprintf(stderr, "(%s)\n", err_info);
270             g_free(err_info);
271         }
272         exit(1);
273     }
274     DEBUG_PRINT("file_type_subtype is %u\n", wtap_file_type_subtype(wth));
275
276     shb_hdr = wtap_file_get_shb_info(wth);
277     idb_inf = wtap_file_get_idb_info(wth);
278
279     /* Open outfile (same filetype/encap as input file) */
280     pdh = wtap_dump_open_ng(outfile, wtap_file_type_subtype(wth), wtap_file_encap(wth),
281                             65535, FALSE, shb_hdr, idb_inf, &err);
282     g_free(idb_inf);
283     if (pdh == NULL) {
284         fprintf(stderr, "reordercap: Failed to open output file: (%s) - error %s\n",
285                 outfile, wtap_strerror(err));
286         g_free(shb_hdr);
287         exit(1);
288     }
289
290     /* Allocate the array of frame pointers. */
291     frames = g_ptr_array_new();
292
293     /* Read each frame from infile */
294     while (wtap_read(wth, &err, &err_info, &data_offset)) {
295         FrameRecord_t *newFrameRecord;
296
297         phdr = wtap_phdr(wth);
298
299         newFrameRecord = g_slice_new(FrameRecord_t);
300         newFrameRecord->num = frames->len + 1;
301         newFrameRecord->offset = data_offset;
302         if (phdr->presence_flags & WTAP_HAS_TS) {
303             newFrameRecord->time = phdr->ts;
304         } else {
305             nstime_set_unset(&newFrameRecord->time);
306         }
307
308         if (prevFrame && frames_compare(&newFrameRecord, &prevFrame) < 0) {
309            wrong_order_count++;
310         }
311
312         g_ptr_array_add(frames, newFrameRecord);
313         prevFrame = newFrameRecord;
314     }
315     if (err != 0) {
316       /* Print a message noting that the read failed somewhere along the line. */
317       fprintf(stderr,
318               "reordercap: An error occurred while reading \"%s\": %s.\n",
319               infile, wtap_strerror(err));
320       if (err_info != NULL) {
321           fprintf(stderr, "(%s)\n", err_info);
322           g_free(err_info);
323       }
324     }
325
326     printf("%u frames, %u out of order\n", frames->len, wrong_order_count);
327
328     /* Sort the frames */
329     if (wrong_order_count > 0) {
330         g_ptr_array_sort(frames, frames_compare);
331     }
332
333     /* Write out each sorted frame in turn */
334     wtap_phdr_init(&dump_phdr);
335     ws_buffer_init(&buf, 1500);
336     for (i = 0; i < frames->len; i++) {
337         FrameRecord_t *frame = (FrameRecord_t *)frames->pdata[i];
338
339         /* Avoid writing if already sorted and configured to */
340         if (write_output_regardless || (wrong_order_count > 0)) {
341             frame_write(frame, wth, pdh, &dump_phdr, &buf, infile);
342         }
343         g_slice_free(FrameRecord_t, frame);
344     }
345     wtap_phdr_cleanup(&dump_phdr);
346     ws_buffer_free(&buf);
347
348     if (!write_output_regardless && (wrong_order_count == 0)) {
349         printf("Not writing output file because input file is already in order!\n");
350     }
351
352     /* Free the whole array */
353     g_ptr_array_free(frames, TRUE);
354
355     /* Close outfile */
356     if (!wtap_dump_close(pdh, &err)) {
357         fprintf(stderr, "reordercap: Error closing %s: %s\n", outfile,
358                 wtap_strerror(err));
359         g_free(shb_hdr);
360         exit(1);
361     }
362     g_free(shb_hdr);
363
364     /* Finally, close infile */
365     wtap_fdclose(wth);
366
367     return 0;
368 }
369
370 /*
371  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
372  *
373  * Local variables:
374  * c-basic-offset: 4
375  * tab-width: 8
376  * indent-tabs-mode: nil
377  * End:
378  *
379  * vi: set shiftwidth=4 tabstop=8 expandtab:
380  * :indentSize=4:tabSize=8:noTabs=true:
381  */