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