Change a comment to be slightly easier to read
[metze/wireshark/wip.git] / reordercap.c
index c08349165475cdaf9c1efb9e4b6160eaf2d46532..92469746821ffa5c787fef3338c6d51d6db5a790 100644 (file)
@@ -1,7 +1,5 @@
 /* Reorder the frames from an input dump file, and write to output dump file.
- * Martin Mathieson
- *
- * $Id$
+ * Martin Mathieson and Jakub Jawadzki
  *
  * Wireshark - Network traffic analyzer
  * By Gerald Combs <gerald@wireshark.org>
  *
  */
 
+#include "config.h"
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <glib.h>
+
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef HAVE_GETOPT_H
+#include <getopt.h>
+#endif
+
+#ifdef HAVE_LIBZ
+#include <zlib.h>      /* to get the libz version number */
+#endif
 
 #include "wtap.h"
 
+#ifndef HAVE_GETOPT
+#include "wsutil/wsgetopt.h"
+#endif
+
+#include <wsutil/strnatcmp.h>
+#include <wsutil/file_util.h>
+#include <wsutil/crash_info.h>
+#include <wsutil/copyright_info.h>
+#include <wsutil/os_version_info.h>
+#include <wsutil/ws_version_info.h>
+
+#include "version_info.h"
+
+static void
+show_version(GString *comp_info_str, GString *runtime_info_str)
+{
+    printf("Reordercap (Wireshark) %s\n"
+           "\n"
+           "%s"
+           "\n"
+           "%s"
+           "\n"
+           "%s",
+           get_ws_vcs_version_info(), get_copyright_info(),
+           comp_info_str->str, runtime_info_str->str);
+}
 
 /* Show command-line usage */
-/* TODO: add reoder list length as an optional param? */
-static void usage(void)
+static void
+print_usage(FILE *output)
 {
-    printf("usage:  reordercap <infile> <outfile>\n");
+    fprintf(output, "\n");
+    fprintf(output, "Usage: reordercap [options] <infile> <outfile>\n");
+    fprintf(output, "\n");
+    fprintf(output, "Options:\n");
+    fprintf(output, "  -n        don't write to output file if the input file is ordered.\n");
+    fprintf(output, "  -h        display this help and exit.\n");
 }
 
 /* Remember where this frame was in the file */
 typedef struct FrameRecord_t {
-    gint64               offset;
-    guint32              length;
-
-    struct wtap_nstime   time;
+    gint64       offset;
+    guint        num;
 
-    /* List item pointers */
-    struct FrameRecord_t *prev;
-    struct FrameRecord_t *next;
+    nstime_t     time;
 } FrameRecord_t;
 
-/* This is pretty big, but I don't mind waiting a few seconds */
-#define MAX_REORDER_LIST_LENGTH 3000
-static int g_FrameRecordCount;
-
-/* This is the list of frames, sorted by time.  Later frames at the front, earlier
-   ones at the end */
-static FrameRecord_t *g_FrameListHead;
-static FrameRecord_t *g_FrameListTail;
-
 
 /**************************************************/
 /* Debugging only                                 */
@@ -65,290 +96,298 @@ static FrameRecord_t *g_FrameListTail;
 /* Enable this symbol to see debug output */
 /* #define REORDER_DEBUG */
 
-#ifdef REORDER_DEBUG
-static void ReorderListDebugPrint(void)
-{
-    int count=0;
-    FrameRecord_t *tmp = g_FrameListHead;
-    printf("\n");
-    while (tmp != NULL) {
-        printf("%6d: offset=%6" G_GINT64_MODIFIER "u, length=%6u, time=%lu:%u",
-               ++count, tmp->offset, tmp->length, tmp->time.secs, tmp->time.nsecs);
-
-        if (tmp == g_FrameListHead) {
-            printf(" (head)");
-        }
-        if (tmp == g_FrameListTail) {
-            printf(" (tail)\n");
-        }
-        printf("\n");
-
-        tmp = tmp->next;
-    }
-    printf("\n");
-}
-#else
-#define ReorderListDebugPrint()
-#endif
-
 #ifdef REORDER_DEBUG
 #define DEBUG_PRINT printf
 #else
 #define DEBUG_PRINT(...)
 #endif
-
 /**************************************************/
 
-/* Counting frames that weren't in order */
-static int g_OutOfOrder = 0;
-
-
-/* Is time1 later than time2? */
-static gboolean isLaterTime(struct wtap_nstime time1,
-                            struct wtap_nstime time2)
-{
-    if (time1.secs > time2.secs) {
-        return TRUE;
-    }
-    if (time1.secs == time2.secs) {
-        return (time1.nsecs > time2.nsecs);
-    }
-    else {
-        return FALSE;
-    }
-}
 
-/* Is the reorder list empty? */
-static gboolean ReorderListEmpty(void)
+static void
+frame_write(FrameRecord_t *frame, wtap *wth, wtap_dumper *pdh, Buffer *buf,
+            const char *infile)
 {
-    return (g_FrameRecordCount == 0);
-}
+    int    err;
+    gchar  *err_info;
+    struct wtap_pkthdr phdr;
 
-/* Is the reorder list full? */
-static gboolean ReorderListFull(void)
-{
-    return (g_FrameRecordCount >= MAX_REORDER_LIST_LENGTH);
-}
+    memset(&phdr, 0, sizeof(struct wtap_pkthdr));
 
-/* Add a new frame to the reorder list */
-/* Adding later ones to the front */
-static void ReorderListAdd(gint64 offset, guint32 length,
-                           struct wtap_nstime time)
-{
-    FrameRecord_t *tmp;
-    FrameRecord_t *newFrameRecord = g_malloc(sizeof(FrameRecord_t));
-
-    /* Populate fields */
-    DEBUG_PRINT("\nAdded with offset=%06" G_GINT64_MODIFIER "u, length=%05u, secs=%lu, nsecs=%d\n",
-                offset, length, time.secs, time.nsecs);
-    newFrameRecord->offset = offset;
-    newFrameRecord->length = length;
-    newFrameRecord->time = time;
-
-    /* We will definitely add it below, so inc counter */
-    g_FrameRecordCount++;
-
-    /* First time, this will be the head */
-    if (g_FrameListHead == NULL) {
-        DEBUG_PRINT("this item will be head - only item\n");
-        g_FrameListHead = newFrameRecord;
-        newFrameRecord->prev = NULL;
-        newFrameRecord->next = NULL;
-        g_FrameListTail = newFrameRecord;
-        return;
-    }
+    DEBUG_PRINT("\nDumping frame (offset=%" G_GINT64_MODIFIER "u)\n",
+                frame->offset);
 
-    /* Look for the place in the list where this item fits */
-    tmp = g_FrameListHead;
-    while (tmp != NULL) {
-        if (isLaterTime(time, tmp->time)) {
-            DEBUG_PRINT("Time was Later, writing before element\n");
 
-            /* Insert newFrameRecord *before* tmp */
-
-            /* Fix up prev item */
-            if (tmp == g_FrameListHead) {
-                /* Inserting before existing head */
-                g_FrameListHead = newFrameRecord;
-            }
-            else {
-                /* Our prev is tmps old prev */
-                newFrameRecord->prev = tmp->prev;
-                /* Its next points to us */
-                newFrameRecord->prev->next = newFrameRecord;
-
-                /* Inserted after another item */
-                DEBUG_PRINT("*** Inc out out of order count\n");
-                g_OutOfOrder++;
+    /* Re-read the first frame from the stored location */
+    if (!wtap_seek_read(wth, frame->offset, &phdr, buf, &err, &err_info)) {
+        if (err != 0) {
+            /* Print a message noting that the read failed somewhere along the line. */
+            fprintf(stderr,
+                    "reordercap: An error occurred while re-reading \"%s\": %s.\n",
+                    infile, wtap_strerror(err));
+            switch (err) {
+
+            case WTAP_ERR_UNSUPPORTED:
+            case WTAP_ERR_UNSUPPORTED_ENCAP:
+            case WTAP_ERR_BAD_FILE:
+                fprintf(stderr, "(%s)\n", err_info);
+                g_free(err_info);
+                break;
             }
-
-            /* Fix up next item */
-            newFrameRecord->next = tmp;
-            tmp->prev = newFrameRecord;
-
-            return;
-        }
-
-        /* Didn't find an item to insert in front of */
-        if (tmp->next == NULL) {
-            DEBUG_PRINT("Reached the end of the list, so insert here\n");
-
-            /* We are the new last item */
-            tmp->next = newFrameRecord;
-            newFrameRecord->prev = tmp;
-            newFrameRecord->next = NULL;
-            g_FrameListTail = newFrameRecord;
-
-            /* There were other items but we were earlier than them */
-            DEBUG_PRINT("*** Inc out out of order count\n");
-            g_OutOfOrder++;
-
-            return;
-        }
-        else {
-            /* Move onto the next item */
-            DEBUG_PRINT("Time was earlier, move to next position\n");
-            tmp = tmp->next;
+            exit(1);
         }
     }
-}
-
-/* Dump the earliest item in the reorder list to the output file, and pop it */
-static void ReorderListDumpEarliest(wtap *wth, wtap_dumper *pdh)
-{
-    union wtap_pseudo_header pseudo_header;
-    int    err;
-    gchar  *errinfo;
-    const struct wtap_pkthdr *phdr;
-    guint8 buf[16000];
-    struct wtap_pkthdr new_phdr;
-
-    FrameRecord_t *prev_tail = g_FrameListTail;
-
-    DEBUG_PRINT("\nDumping frame (offset=%" G_GINT64_MODIFIER "u, length=%u) (%u items in list)\n", 
-                g_FrameListHead->offset, g_FrameListHead->length,
-                g_FrameRecordCount);
-
-    /* Re-read the first frame from the stored location */
-    wtap_seek_read(wth,
-                   g_FrameListTail->offset,
-                   &pseudo_header,
-                   buf,
-                   g_FrameListTail->length,
-                   &err,
-                   &errinfo);
-    DEBUG_PRINT("re-read: err is %u, buf is (%s)\n", err, buf);
-
-    /* Get packet header */
-    phdr = wtap_phdr(wth);
 
     /* Copy, and set length and timestamp from item. */
-    memcpy((void*)&new_phdr, phdr, sizeof(struct wtap_pkthdr));
-    new_phdr.len = g_FrameListTail->length;
-    new_phdr.ts.secs = g_FrameListTail->time.secs;
-    new_phdr.ts.nsecs = g_FrameListTail->time.nsecs;
+    /* TODO: remove when wtap_seek_read() will read phdr */
+    phdr.ts = frame->time;
 
     /* Dump frame to outfile */
-    if (!wtap_dump(pdh, &new_phdr, &pseudo_header, buf, &err)) {
-        printf("Error (%s) writing frame to outfile\n", wtap_strerror(err));
+    if (!wtap_dump(pdh, &phdr, buffer_start_ptr(buf), &err)) {
+        fprintf(stderr, "reordercap: Error (%s) writing frame to outfile\n",
+                wtap_strerror(err));
         exit(1);
     }
+}
 
-    /* Now remove this (the last/earliest) item from the list */
-    if (g_FrameListTail->prev == NULL) {
-        g_FrameListTail = NULL;
-        g_FrameListHead = NULL;
-    }
-    else {
-        /* 2nd last item is now last */
-        g_FrameListTail->prev->next = NULL;
-        g_FrameListTail = g_FrameListTail->prev;
-    }
+/* Comparing timestamps between 2 frames.
+   negative if (t1 < t2)
+   zero     if (t1 == t2)
+   positive if (t1 > t2)
+*/
+static int
+frames_compare(gconstpointer a, gconstpointer b)
+{
+    const FrameRecord_t *frame1 = *(const FrameRecord_t *const *) a;
+    const FrameRecord_t *frame2 = *(const FrameRecord_t *const *) b;
 
-    /* And free the struct */
-    g_free(prev_tail);
-    g_FrameRecordCount--;
+    const nstime_t *time1 = &frame1->time;
+    const nstime_t *time2 = &frame2->time;
 
-    DEBUG_PRINT("Frame written, %u remaining\n", g_FrameRecordCount);
+    return nstime_cmp(time1, time2);
 }
 
+static void
+get_reordercap_compiled_info(GString *str)
+{
+    /* LIBZ */
+    g_string_append(str, ", ");
+#ifdef HAVE_LIBZ
+    g_string_append(str, "with libz ");
+#ifdef ZLIB_VERSION
+    g_string_append(str, ZLIB_VERSION);
+#else /* ZLIB_VERSION */
+    g_string_append(str, "(version unknown)");
+#endif /* ZLIB_VERSION */
+#else /* HAVE_LIBZ */
+    g_string_append(str, "without libz");
+#endif /* HAVE_LIBZ */
+}
 
+static void
+get_reordercap_runtime_info(GString *str)
+{
+    /* zlib */
+#if defined(HAVE_LIBZ) && !defined(_WIN32)
+    g_string_append_printf(str, ", with libz %s", zlibVersion());
+#endif
+}
 
 /********************************************************************/
 /* Main function.                                                   */
 /********************************************************************/
-int main(int argc, char *argv[])
+int
+main(int argc, char *argv[])
 {
+    GString *comp_info_str;
+    GString *runtime_info_str;
     wtap *wth = NULL;
     wtap_dumper *pdh = NULL;
+    Buffer buf;
     int err;
     gchar *err_info;
     gint64 data_offset;
     const struct wtap_pkthdr *phdr;
-    guint32 read_count = 0;
-
-    /* 1st arg is infile, 2nd arg is outfile */
+    guint wrong_order_count = 0;
+    gboolean write_output_regardless = TRUE;
+    guint i;
+    wtapng_section_t            *shb_hdr;
+    wtapng_iface_descriptions_t *idb_inf;
+
+    GPtrArray *frames;
+    FrameRecord_t *prevFrame = NULL;
+
+    int opt;
+    static const struct option long_options[] = {
+        {(char *)"help", no_argument, NULL, 'h'},
+        {(char *)"version", no_argument, NULL, 'v'},
+        {0, 0, 0, 0 }
+    };
+    int file_count;
     char *infile;
     char *outfile;
-    if (argc == 3) {
-        infile = argv[1];
-        outfile = argv[2];
+
+    /* Assemble the compile-time version information string */
+    comp_info_str = g_string_new("Compiled ");
+    get_compiled_version_info(comp_info_str, NULL, get_reordercap_compiled_info);
+
+    /* Assemble the run-time version information string */
+    runtime_info_str = g_string_new("Running ");
+    get_runtime_version_info(runtime_info_str, get_reordercap_runtime_info);
+
+    /* Add it to the information to be reported on a crash. */
+    ws_add_crash_info("Reordercap (Wireshark) %s\n"
+         "\n"
+         "%s"
+         "\n"
+         "%s",
+      get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
+
+    /* Process the options first */
+    while ((opt = getopt_long(argc, argv, "hnv", long_options, NULL)) != -1) {
+        switch (opt) {
+            case 'n':
+                write_output_regardless = FALSE;
+                break;
+            case 'h':
+                printf("Reordercap (Wireshark) %s\n"
+                       "Reorder timestamps of input file frames into output file.\n"
+                       "See http://www.wireshark.org for more information.\n",
+                       get_ws_vcs_version_info());
+                print_usage(stdout);
+                exit(0);
+            case 'v':
+                show_version(comp_info_str, runtime_info_str);
+                g_string_free(comp_info_str, TRUE);
+                g_string_free(runtime_info_str, TRUE);
+                exit(0);
+            case '?':
+                print_usage(stderr);
+                exit(1);
+        }
+    }
+
+    /* Remaining args are file names */
+    file_count = argc - optind;
+    if (file_count == 2) {
+        infile  = argv[optind];
+        outfile = argv[optind+1];
     }
     else {
-        usage();
+        print_usage(stderr);
         exit(1);
     }
 
     /* Open infile */
-    wth = wtap_open_offline(infile, &err, &err_info, TRUE);
+    /* TODO: if reordercap is ever changed to give the user a choice of which
+       open_routine reader to use, then the following needs to change. */
+    wth = wtap_open_offline(infile, WTAP_TYPE_AUTO, &err, &err_info, TRUE);
     if (wth == NULL) {
-        printf("reorder: Can't open %s: %s\n", infile, wtap_strerror(err));
+        fprintf(stderr, "reordercap: Can't open %s: %s\n", infile,
+                wtap_strerror(err));
+        switch (err) {
+
+        case WTAP_ERR_UNSUPPORTED:
+        case WTAP_ERR_UNSUPPORTED_ENCAP:
+        case WTAP_ERR_BAD_FILE:
+            fprintf(stderr, "(%s)\n", err_info);
+            g_free(err_info);
+            break;
+        }
         exit(1);
     }
+    DEBUG_PRINT("file_type_subtype is %u\n", wtap_file_type_subtype(wth));
 
-    DEBUG_PRINT("file_type is %u\n", wtap_file_type(wth));
+    shb_hdr = wtap_file_get_shb_info(wth);
+    idb_inf = wtap_file_get_idb_info(wth);
 
     /* Open outfile (same filetype/encap as input file) */
-    pdh = wtap_dump_open(outfile, wtap_file_type(wth), wtap_file_encap(wth), 65535, FALSE, &err);
+    pdh = wtap_dump_open_ng(outfile, wtap_file_type_subtype(wth), wtap_file_encap(wth),
+                            65535, FALSE, shb_hdr, idb_inf, &err);
+    g_free(idb_inf);
     if (pdh == NULL) {
-        printf("Failed to open output file: (%s) - error %s\n", outfile, wtap_strerror(err));
+        fprintf(stderr, "reordercap: Failed to open output file: (%s) - error %s\n",
+                outfile, wtap_strerror(err));
+        g_free(shb_hdr);
         exit(1);
     }
 
+    /* Allocate the array of frame pointers. */
+    frames = g_ptr_array_new();
 
     /* Read each frame from infile */
     while (wtap_read(wth, &err, &err_info, &data_offset)) {
-        read_count++;
+        FrameRecord_t *newFrameRecord;
+
         phdr = wtap_phdr(wth);
 
-        /* Add it to the reordering list */
-        ReorderListAdd(data_offset, phdr->len, phdr->ts);
-        ReorderListDebugPrint();
+        newFrameRecord = g_slice_new(FrameRecord_t);
+        newFrameRecord->num = frames->len + 1;
+        newFrameRecord->offset = data_offset;
+        if (phdr->presence_flags & WTAP_HAS_TS) {
+            newFrameRecord->time = phdr->ts;
+        } else {
+            nstime_set_unset(&newFrameRecord->time);
+        }
 
-        /* If/when the list gets full, dump the earliest item out */
-        if (ReorderListFull()) {
-            DEBUG_PRINT("List is full, dumping earliest!\n");
+        if (prevFrame && frames_compare(&newFrameRecord, &prevFrame) < 0) {
+           wrong_order_count++;
+        }
 
-            /* Write out the earliest one */
-            ReorderListDumpEarliest(wth, pdh);
-            ReorderListDebugPrint();
+        g_ptr_array_add(frames, newFrameRecord);
+        prevFrame = newFrameRecord;
+    }
+    if (err != 0) {
+      /* Print a message noting that the read failed somewhere along the line. */
+      fprintf(stderr,
+              "reordercap: An error occurred while reading \"%s\": %s.\n",
+              infile, wtap_strerror(err));
+      switch (err) {
+
+      case WTAP_ERR_UNSUPPORTED:
+      case WTAP_ERR_UNSUPPORTED_ENCAP:
+      case WTAP_ERR_BAD_FILE:
+          fprintf(stderr, "(%s)\n", err_info);
+          g_free(err_info);
+          break;
+      }
+    }
+
+    printf("%u frames, %u out of order\n", frames->len, wrong_order_count);
+
+    /* Sort the frames */
+    if (wrong_order_count > 0) {
+        g_ptr_array_sort(frames, frames_compare);
+    }
+
+    /* Write out each sorted frame in turn */
+    buffer_init(&buf, 1500);
+    for (i = 0; i < frames->len; i++) {
+        FrameRecord_t *frame = (FrameRecord_t *)frames->pdata[i];
+
+        /* Avoid writing if already sorted and configured to */
+        if (write_output_regardless || (wrong_order_count > 0)) {
+            frame_write(frame, wth, pdh, &buf, infile);
         }
+        g_slice_free(FrameRecord_t, frame);
     }
+    buffer_free(&buf);
 
-    /* Flush out the remaining (ordered) frames */
-    while (!ReorderListEmpty()) {
-        ReorderListDumpEarliest(wth, pdh);
-        ReorderListDebugPrint();
+    if (!write_output_regardless && (wrong_order_count == 0)) {
+        printf("Not writing output file because input file is already in order!\n");
     }
 
+    /* Free the whole array */
+    g_ptr_array_free(frames, TRUE);
+
     /* Close outfile */
     if (!wtap_dump_close(pdh, &err)) {
-        printf("Error closing %s: %s\n", outfile, wtap_strerror(err));
+        fprintf(stderr, "reordercap: Error closing %s: %s\n", outfile,
+                wtap_strerror(err));
+        g_free(shb_hdr);
         exit(1);
     }
-
-    /* Write how many frames, and how many were out of order */
-    printf("%u frames, %u out of order\n", read_count, g_OutOfOrder);
+    g_free(shb_hdr);
 
     /* Finally, close infile */
     wtap_fdclose(wth);
@@ -356,3 +395,15 @@ int main(int argc, char *argv[])
     return 0;
 }
 
+/*
+ * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
+ *
+ * Local variables:
+ * c-basic-offset: 4
+ * tab-width: 8
+ * indent-tabs-mode: nil
+ * End:
+ *
+ * vi: set shiftwidth=4 tabstop=8 expandtab:
+ * :indentSize=4:tabSize=8:noTabs=true:
+ */