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