licensecheck: fix detection of multiple licenses
[metze/wireshark/wip.git] / editcap.c
1 /* editcap.c
2  * Edit capture files.  We can delete packets, adjust timestamps, or
3  * simply convert from one format to another format.
4  *
5  * Originally written by Richard Sharpe.
6  * Improved by Guy Harris.
7  * Further improved by Richard Sharpe.
8  *
9  * Copyright 2013, Richard Sharpe <realrichardsharpe[AT]gmail.com>
10  *
11  * Wireshark - Network traffic analyzer
12  * By Gerald Combs <gerald@wireshark.org>
13  * Copyright 1998 Gerald Combs
14  *
15  * SPDX-License-Identifier: GPL-2.0-or-later
16  */
17
18 #include <config.h>
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <stdarg.h>
24
25 /*
26  * Just make sure we include the prototype for strptime as well
27  * (needed for glibc 2.2) but make sure we do this only if not
28  * yet defined.
29  */
30
31 #ifndef __USE_XOPEN
32 #  define __USE_XOPEN
33 #endif
34
35 #include <time.h>
36 #include <glib.h>
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #ifdef HAVE_GETOPT_H
43 #include <getopt.h>
44 #endif
45
46 #include <wiretap/wtap.h>
47
48 #include "epan/etypes.h"
49 #include "epan/dissectors/packet-ieee80211-radiotap-defs.h"
50
51 #ifndef HAVE_GETOPT_LONG
52 #include "wsutil/wsgetopt.h"
53 #endif
54
55 #ifdef _WIN32
56 #include <wsutil/unicode-utils.h>
57 #include <process.h>    /* getpid */
58 #include <winsock2.h>
59 #endif
60
61 #ifndef HAVE_STRPTIME
62 # include "wsutil/strptime.h"
63 #endif
64
65 #include <wsutil/crash_info.h>
66 #include <wsutil/clopts_common.h>
67 #include <wsutil/cmdarg_err.h>
68 #include <wsutil/filesystem.h>
69 #include <wsutil/file_util.h>
70 #include <wsutil/wsgcrypt.h>
71 #include <wsutil/plugins.h>
72 #include <wsutil/privileges.h>
73 #include <wsutil/report_message.h>
74 #include <wsutil/strnatcmp.h>
75 #include <wsutil/str_util.h>
76 #include <version_info.h>
77 #include <wsutil/pint.h>
78 #include <wsutil/strtoi.h>
79 #include <wiretap/wtap_opttypes.h>
80 #include <wiretap/pcapng.h>
81
82 #include "ui/failure_message.h"
83
84 #include "ringbuffer.h" /* For RINGBUFFER_MAX_NUM_FILES */
85
86 #define INVALID_OPTION 1
87 #define INVALID_FILE 2
88 #define CANT_EXTRACT_PREFIX 2
89 #define WRITE_ERROR 2
90 #define DUMP_ERROR 2
91
92 /*
93  * Some globals so we can pass things to various routines
94  */
95
96 struct select_item {
97     gboolean inclusive;
98     guint first, second;
99 };
100
101 /*
102  * Duplicate frame detection
103  */
104 typedef struct _fd_hash_t {
105     guint8     digest[16];
106     guint32    len;
107     nstime_t   frame_time;
108 } fd_hash_t;
109
110 #define DEFAULT_DUP_DEPTH       5   /* Used with -d */
111 #define MAX_DUP_DEPTH     1000000   /* the maximum window (and actual size of fd_hash[]) for de-duplication */
112
113 static fd_hash_t fd_hash[MAX_DUP_DEPTH];
114 static int       dup_window    = DEFAULT_DUP_DEPTH;
115 static int       cur_dup_entry = 0;
116
117 static guint32   ignored_bytes  = 0;  /* Used with -I */
118
119 #define ONE_BILLION 1000000000
120
121 /* Weights of different errors we can introduce */
122 /* We should probably make these command-line arguments */
123 /* XXX - Should we add a bit-level error? */
124 #define ERR_WT_BIT      5   /* Flip a random bit */
125 #define ERR_WT_BYTE     5   /* Substitute a random byte */
126 #define ERR_WT_ALNUM    5   /* Substitute a random character in [A-Za-z0-9] */
127 #define ERR_WT_FMT      2   /* Substitute "%s" */
128 #define ERR_WT_AA       1   /* Fill the remainder of the buffer with 0xAA */
129 #define ERR_WT_TOTAL    (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
130
131 #define ALNUM_CHARS     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
132 #define ALNUM_LEN       (sizeof(ALNUM_CHARS) - 1)
133
134 struct time_adjustment {
135     nstime_t tv;
136     int is_negative;
137 };
138
139 typedef struct _chop_t {
140     int len_begin;
141     int off_begin_pos;
142     int off_begin_neg;
143     int len_end;
144     int off_end_pos;
145     int off_end_neg;
146 } chop_t;
147
148
149 /* Table of user comments */
150 GTree *frames_user_comments = NULL;
151
152 #define MAX_SELECTIONS 512
153 static struct select_item     selectfrm[MAX_SELECTIONS];
154 static guint                  max_selected              = 0;
155 static int                    keep_em                   = 0;
156 #ifdef PCAP_NG_DEFAULT
157 static int                    out_file_type_subtype     = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcapng   */
158 #else
159 static int                    out_file_type_subtype     = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcap     */
160 #endif
161 static int                    out_frame_type            = -2; /* Leave frame type alone */
162 static int                    verbose                   = 0;  /* Not so verbose         */
163 static struct time_adjustment time_adj                  = {NSTIME_INIT_ZERO, 0}; /* no adjustment */
164 static nstime_t               relative_time_window      = NSTIME_INIT_ZERO; /* de-dup time window */
165 static double                 err_prob                  = -1.0;
166 static time_t                 starttime                 = 0;
167 static time_t                 stoptime                  = 0;
168 static gboolean               check_startstop           = FALSE;
169 static gboolean               rem_vlan                  = FALSE;
170 static gboolean               dup_detect                = FALSE;
171 static gboolean               dup_detect_by_time        = FALSE;
172 static gboolean               skip_radiotap             = FALSE;
173
174 static int                    do_strict_time_adjustment = FALSE;
175 static struct time_adjustment strict_time_adj           = {NSTIME_INIT_ZERO, 0}; /* strict time adjustment */
176 static nstime_t               previous_time             = NSTIME_INIT_ZERO; /* previous time */
177
178 static int find_dct2000_real_data(guint8 *buf);
179 static void handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
180                             const wtap_packet_header *in_phdr, guint8 **buf,
181                             gboolean adjlen);
182
183 static gchar *
184 abs_time_to_str_with_sec_resolution(const nstime_t *abs_time)
185 {
186     struct tm *tmp;
187     gchar     *buf = (gchar *)g_malloc(16);
188
189     tmp = localtime(&abs_time->secs);
190
191     if (tmp) {
192         g_snprintf(buf, 16, "%d%02d%02d%02d%02d%02d",
193             tmp->tm_year + 1900,
194             tmp->tm_mon+1,
195             tmp->tm_mday,
196             tmp->tm_hour,
197             tmp->tm_min,
198             tmp->tm_sec);
199     } else {
200         buf[0] = '\0';
201     }
202
203     return buf;
204 }
205
206 static gchar *
207 fileset_get_filename_by_pattern(guint idx, const wtap_rec *rec,
208                                 gchar *fprefix, gchar *fsuffix)
209 {
210     gchar  filenum[5+1];
211     gchar *timestr;
212     gchar *abs_str;
213
214     g_snprintf(filenum, sizeof(filenum), "%05u", idx % RINGBUFFER_MAX_NUM_FILES);
215     if (rec->presence_flags & WTAP_HAS_TS) {
216         timestr = abs_time_to_str_with_sec_resolution(&rec->ts);
217         abs_str = g_strconcat(fprefix, "_", filenum, "_", timestr, fsuffix, NULL);
218         g_free(timestr);
219     } else
220         abs_str = g_strconcat(fprefix, "_", filenum, fsuffix, NULL);
221
222     return abs_str;
223 }
224
225 static gboolean
226 fileset_extract_prefix_suffix(const char *fname, gchar **fprefix, gchar **fsuffix)
227 {
228     char  *pfx, *last_pathsep;
229     gchar *save_file;
230
231     save_file = g_strdup(fname);
232     if (save_file == NULL) {
233         fprintf(stderr, "editcap: Out of memory\n");
234         return FALSE;
235     }
236
237     last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
238     pfx = strrchr(save_file,'.');
239     if (pfx != NULL && (last_pathsep == NULL || pfx > last_pathsep)) {
240         /* The pathname has a "." in it, and it's in the last component
241          * of the pathname (because there is either only one component,
242          * i.e. last_pathsep is null as there are no path separators,
243          * or the "." is after the path separator before the last
244          * component.
245
246          * Treat it as a separator between the rest of the file name and
247          * the file name suffix, and arrange that the names given to the
248          * ring buffer files have the specified suffix, i.e. put the
249          * changing part of the name *before* the suffix. */
250         pfx[0] = '\0';
251         *fprefix = g_strdup(save_file);
252         pfx[0] = '.'; /* restore capfile_name */
253         *fsuffix = g_strdup(pfx);
254     } else {
255         /* Either there's no "." in the pathname, or it's in a directory
256          * component, so the last component has no suffix. */
257         *fprefix = g_strdup(save_file);
258         *fsuffix = NULL;
259     }
260     g_free(save_file);
261     return TRUE;
262 }
263
264 /* Add a selection item, a simple parser for now */
265 static gboolean
266 add_selection(char *sel, guint* max_selection)
267 {
268     char *locn;
269     char *next;
270
271     if (max_selected >= MAX_SELECTIONS) {
272         /* Let the user know we stopped selecting */
273         fprintf(stderr, "Out of room for packet selections.\n");
274         return(FALSE);
275     }
276
277     if (verbose)
278         fprintf(stderr, "Add_Selected: %s\n", sel);
279
280     if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
281         if (verbose)
282             fprintf(stderr, "Not inclusive ...");
283
284         selectfrm[max_selected].inclusive = FALSE;
285         selectfrm[max_selected].first = get_guint32(sel, "packet number");
286         if (selectfrm[max_selected].first > *max_selection)
287             *max_selection = selectfrm[max_selected].first;
288
289         if (verbose)
290             fprintf(stderr, " %u\n", selectfrm[max_selected].first);
291     } else {
292         if (verbose)
293             fprintf(stderr, "Inclusive ...");
294
295         *locn = '\0';    /* split the range */
296         next = locn + 1;
297         selectfrm[max_selected].inclusive = TRUE;
298         selectfrm[max_selected].first = get_guint32(sel, "beginning of packet range");
299         selectfrm[max_selected].second = get_guint32(next, "end of packet range");
300
301         if (selectfrm[max_selected].second == 0)
302         {
303             /* Not a valid number, presume all */
304             selectfrm[max_selected].second = *max_selection = G_MAXUINT;
305         }
306         else if (selectfrm[max_selected].second > *max_selection)
307             *max_selection = selectfrm[max_selected].second;
308
309         if (verbose)
310             fprintf(stderr, " %u, %u\n", selectfrm[max_selected].first,
311                    selectfrm[max_selected].second);
312     }
313
314     max_selected++;
315     return(TRUE);
316 }
317
318 /* Was the packet selected? */
319
320 static int
321 selected(guint recno)
322 {
323     guint i;
324
325     for (i = 0; i < max_selected; i++) {
326         if (selectfrm[i].inclusive) {
327             if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
328                 return 1;
329         } else {
330             if (recno == selectfrm[i].first)
331                 return 1;
332         }
333     }
334
335   return 0;
336 }
337
338 static gboolean
339 set_time_adjustment(char *optarg_str_p)
340 {
341     char   *frac, *end;
342     long    val;
343     size_t  frac_digits;
344
345     if (!optarg_str_p)
346         return TRUE;
347
348     /* skip leading whitespace */
349     while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
350         optarg_str_p++;
351
352     /* check for a negative adjustment */
353     if (*optarg_str_p == '-') {
354         time_adj.is_negative = 1;
355         optarg_str_p++;
356     }
357
358     /* collect whole number of seconds, if any */
359     if (*optarg_str_p == '.') {         /* only fractional (i.e., .5 is ok) */
360         val  = 0;
361         frac = optarg_str_p;
362     } else {
363         val = strtol(optarg_str_p, &frac, 10);
364         if (frac == NULL || frac == optarg_str_p
365             || val == LONG_MIN || val == LONG_MAX) {
366             fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
367                     optarg_str_p);
368             return FALSE;
369         }
370         if (val < 0) {            /* implies '--' since we caught '-' above  */
371             fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
372                     optarg_str_p);
373             return FALSE;
374         }
375     }
376     time_adj.tv.secs = val;
377
378     /* now collect the partial seconds, if any */
379     if (*frac != '\0') {             /* chars left, so get fractional part */
380         val = strtol(&(frac[1]), &end, 10);
381         /* if more than 9 fractional digits truncate to 9 */
382         if ((end - &(frac[1])) > 9) {
383             frac[10] = 't'; /* 't' for truncate */
384             val = strtol(&(frac[1]), &end, 10);
385         }
386         if (*frac != '.' || end == NULL || end == frac || val < 0
387             || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
388             fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
389                     optarg_str_p);
390             return FALSE;
391         }
392     } else {
393         return TRUE;                     /* no fractional digits */
394     }
395
396     /* adjust fractional portion from fractional to numerator
397      * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
398     frac_digits = end - frac - 1;   /* fractional digit count (remember '.') */
399     while(frac_digits < 9) {    /* this is frac of 10^9 */
400         val *= 10;
401         frac_digits++;
402     }
403
404     time_adj.tv.nsecs = (int)val;
405     return TRUE;
406 }
407
408 static gboolean
409 set_strict_time_adj(char *optarg_str_p)
410 {
411     char   *frac, *end;
412     long    val;
413     size_t  frac_digits;
414
415     if (!optarg_str_p)
416         return TRUE;
417
418     /* skip leading whitespace */
419     while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
420         optarg_str_p++;
421
422     /*
423      * check for a negative adjustment
424      * A negative strict adjustment value is a flag
425      * to adjust all frames by the specifed delta time.
426      */
427     if (*optarg_str_p == '-') {
428         strict_time_adj.is_negative = 1;
429         optarg_str_p++;
430     }
431
432     /* collect whole number of seconds, if any */
433     if (*optarg_str_p == '.') {         /* only fractional (i.e., .5 is ok) */
434         val  = 0;
435         frac = optarg_str_p;
436     } else {
437         val = strtol(optarg_str_p, &frac, 10);
438         if (frac == NULL || frac == optarg_str_p
439             || val == LONG_MIN || val == LONG_MAX) {
440             fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
441                     optarg_str_p);
442             return FALSE;
443         }
444         if (val < 0) {            /* implies '--' since we caught '-' above  */
445             fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
446                     optarg_str_p);
447             return FALSE;
448         }
449     }
450     strict_time_adj.tv.secs = val;
451
452     /* now collect the partial seconds, if any */
453     if (*frac != '\0') {             /* chars left, so get fractional part */
454         val = strtol(&(frac[1]), &end, 10);
455         /* if more than 9 fractional digits truncate to 9 */
456         if ((end - &(frac[1])) > 9) {
457             frac[10] = 't'; /* 't' for truncate */
458             val = strtol(&(frac[1]), &end, 10);
459         }
460         if (*frac != '.' || end == NULL || end == frac || val < 0
461             || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
462             fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
463                     optarg_str_p);
464             return FALSE;
465         }
466     } else {
467         return TRUE;                     /* no fractional digits */
468     }
469
470     /* adjust fractional portion from fractional to numerator
471      * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
472     frac_digits = end - frac - 1;   /* fractional digit count (remember '.') */
473     while(frac_digits < 9) {    /* this is frac of 10^9 */
474         val *= 10;
475         frac_digits++;
476     }
477
478     strict_time_adj.tv.nsecs = (int)val;
479     return TRUE;
480 }
481
482 static gboolean
483 set_rel_time(char *optarg_str_p)
484 {
485     char   *frac, *end;
486     long    val;
487     size_t  frac_digits;
488
489     if (!optarg_str_p)
490         return TRUE;
491
492     /* skip leading whitespace */
493     while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
494         optarg_str_p++;
495
496     /* ignore negative adjustment  */
497     if (*optarg_str_p == '-')
498         optarg_str_p++;
499
500     /* collect whole number of seconds, if any */
501     if (*optarg_str_p == '.') {         /* only fractional (i.e., .5 is ok) */
502         val  = 0;
503         frac = optarg_str_p;
504     } else {
505         val = strtol(optarg_str_p, &frac, 10);
506         if (frac == NULL || frac == optarg_str_p
507             || val == LONG_MIN || val == LONG_MAX) {
508             fprintf(stderr, "1: editcap: \"%s\" isn't a valid rel time value\n",
509                     optarg_str_p);
510             return FALSE;
511         }
512         if (val < 0) {            /* implies '--' since we caught '-' above  */
513             fprintf(stderr, "2: editcap: \"%s\" isn't a valid rel time value\n",
514                     optarg_str_p);
515             return FALSE;
516         }
517     }
518     relative_time_window.secs = val;
519
520     /* now collect the partial seconds, if any */
521     if (*frac != '\0') {             /* chars left, so get fractional part */
522         val = strtol(&(frac[1]), &end, 10);
523         /* if more than 9 fractional digits truncate to 9 */
524         if ((end - &(frac[1])) > 9) {
525             frac[10] = 't'; /* 't' for truncate */
526             val = strtol(&(frac[1]), &end, 10);
527         }
528         if (*frac != '.' || end == NULL || end == frac || val < 0
529             || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
530             fprintf(stderr, "3: editcap: \"%s\" isn't a valid rel time value\n",
531                     optarg_str_p);
532             return FALSE;
533         }
534     } else {
535         return TRUE;                     /* no fractional digits */
536     }
537
538     /* adjust fractional portion from fractional to numerator
539      * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
540     frac_digits = end - frac - 1;   /* fractional digit count (remember '.') */
541     while(frac_digits < 9) {    /* this is frac of 10^9 */
542         val *= 10;
543         frac_digits++;
544     }
545
546     relative_time_window.nsecs = (int)val;
547     return TRUE;
548 }
549
550 #define LINUX_SLL_OFFSETP 14
551 #define VLAN_SIZE 4
552 static void
553 sll_remove_vlan_info(guint8* fd, guint32* len) {
554     if (pntoh16(fd + LINUX_SLL_OFFSETP) == ETHERTYPE_VLAN) {
555         int rest_len;
556         /* point to start of vlan */
557         fd = fd + LINUX_SLL_OFFSETP;
558         /* bytes to read after vlan info */
559         rest_len = *len - (LINUX_SLL_OFFSETP + VLAN_SIZE);
560         /* remove vlan info from packet */
561         memmove(fd, fd + VLAN_SIZE, rest_len);
562         *len -= 4;
563     }
564 }
565
566 static void
567 remove_vlan_info(const wtap_packet_header *phdr, guint8* fd, guint32* len) {
568     switch (phdr->pkt_encap) {
569         case WTAP_ENCAP_SLL:
570             sll_remove_vlan_info(fd, len);
571             break;
572         default:
573             /* no support for current pkt_encap */
574             break;
575     }
576 }
577
578 static gboolean
579 is_duplicate(guint8* fd, guint32 len) {
580     int i;
581     const struct ieee80211_radiotap_header* tap_header;
582
583     /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
584     guint32 offset = ignored_bytes;
585     guint32 new_len;
586     guint8 *new_fd;
587
588     if (len <= ignored_bytes) {
589         offset = 0;
590     }
591
592     /* Get the size of radiotap header and use that as offset (-p option) */
593     if (skip_radiotap == TRUE) {
594         tap_header = (const struct ieee80211_radiotap_header*)fd;
595         offset = pletoh16(&tap_header->it_len);
596         if (offset >= len)
597             offset = 0;
598     }
599
600     new_fd  = &fd[offset];
601     new_len = len - (offset);
602
603     cur_dup_entry++;
604     if (cur_dup_entry >= dup_window)
605         cur_dup_entry = 0;
606
607     /* Calculate our digest */
608     gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
609
610     fd_hash[cur_dup_entry].len = len;
611
612     /* Look for duplicates */
613     for (i = 0; i < dup_window; i++) {
614         if (i == cur_dup_entry)
615             continue;
616
617         if (fd_hash[i].len == fd_hash[cur_dup_entry].len
618             && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
619             return TRUE;
620         }
621     }
622
623     return FALSE;
624 }
625
626 static gboolean
627 is_duplicate_rel_time(guint8* fd, guint32 len, const nstime_t *current) {
628     int i;
629
630     /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
631     guint32 offset = ignored_bytes;
632     guint32 new_len;
633     guint8 *new_fd;
634
635     if (len <= ignored_bytes) {
636         offset = 0;
637     }
638
639     new_fd  = &fd[offset];
640     new_len = len - (offset);
641
642     cur_dup_entry++;
643     if (cur_dup_entry >= dup_window)
644         cur_dup_entry = 0;
645
646     /* Calculate our digest */
647     gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
648
649     fd_hash[cur_dup_entry].len = len;
650     fd_hash[cur_dup_entry].frame_time.secs = current->secs;
651     fd_hash[cur_dup_entry].frame_time.nsecs = current->nsecs;
652
653     /*
654      * Look for relative time related duplicates.
655      * This is hopefully a reasonably efficient mechanism for
656      * finding duplicates by rel time in the fd_hash[] cache.
657      * We check starting from the most recently added hash
658      * entries and work backwards towards older packets.
659      * This approach allows the dup test to be terminated
660      * when the relative time of a cached entry is found to
661      * be beyond the dup time window.
662      *
663      * Of course this assumes that the input trace file is
664      * "well-formed" in the sense that the packet timestamps are
665      * in strict chronologically increasing order (which is NOT
666      * always the case!!).
667      *
668      * The fd_hash[] table was deliberately created large (1,000,000).
669      * Looking for time related duplicates in large trace files with
670      * non-fractional dup time window values can potentially take
671      * a long time to complete.
672      */
673
674     for (i = cur_dup_entry - 1;; i--) {
675         nstime_t delta;
676         int cmp;
677
678         if (i < 0)
679             i = dup_window - 1;
680
681         if (i == cur_dup_entry) {
682             /*
683              * We've decremented back to where we started.
684              * Check no more!
685              */
686             break;
687         }
688
689         if (nstime_is_unset(&(fd_hash[i].frame_time))) {
690             /*
691              * We've decremented to an unused fd_hash[] entry.
692              * Check no more!
693              */
694             break;
695         }
696
697         nstime_delta(&delta, current, &fd_hash[i].frame_time);
698
699         if (delta.secs < 0 || delta.nsecs < 0) {
700             /*
701              * A negative delta implies that the current packet
702              * has an absolute timestamp less than the cached packet
703              * that it is being compared to.  This is NOT a normal
704              * situation since trace files usually have packets in
705              * chronological order (oldest to newest).
706              *
707              * There are several possible ways to deal with this:
708              * 1. 'continue' dup checking with the next cached frame.
709              * 2. 'break' from looking for a duplicate of the current frame.
710              * 3. Take the absolute value of the delta and see if that
711              * falls within the specifed dup time window.
712              *
713              * Currently this code does option 1.  But it would pretty
714              * easy to add yet-another-editcap-option to select one of
715              * the other behaviors for dealing with out-of-sequence
716              * packets.
717              */
718             continue;
719         }
720
721         cmp = nstime_cmp(&delta, &relative_time_window);
722
723         if (cmp > 0) {
724             /*
725              * The delta time indicates that we are now looking at
726              * cached packets beyond the specified dup time window.
727              * Check no more!
728              */
729             break;
730         } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len
731                    && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
732             return TRUE;
733         }
734     }
735
736     return FALSE;
737 }
738
739 static void
740 print_usage(FILE *output)
741 {
742     fprintf(output, "\n");
743     fprintf(output, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
744     fprintf(output, "\n");
745     fprintf(output, "<infile> and <outfile> must both be present.\n");
746     fprintf(output, "A single packet or a range of packets can be selected.\n");
747     fprintf(output, "\n");
748     fprintf(output, "Packet selection:\n");
749     fprintf(output, "  -r                     keep the selected packets; default is to delete them.\n");
750     fprintf(output, "  -A <start time>        only output packets whose timestamp is after (or equal\n");
751     fprintf(output, "                         to) the given time (format as YYYY-MM-DD hh:mm:ss).\n");
752     fprintf(output, "  -B <stop time>         only output packets whose timestamp is before the\n");
753     fprintf(output, "                         given time (format as YYYY-MM-DD hh:mm:ss).\n");
754     fprintf(output, "\n");
755     fprintf(output, "Duplicate packet removal:\n");
756     fprintf(output, "  --novlan               remove vlan info from packets before checking for duplicates.\n");
757     fprintf(output, "  -d                     remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH);
758     fprintf(output, "  -D <dup window>        remove packet if duplicate; configurable <dup window>.\n");
759     fprintf(output, "                         Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH);
760     fprintf(output, "                         NOTE: A <dup window> of 0 with -v (verbose option) is\n");
761     fprintf(output, "                         useful to print MD5 hashes.\n");
762     fprintf(output, "  -w <dup time window>   remove packet if duplicate packet is found EQUAL TO OR\n");
763     fprintf(output, "                         LESS THAN <dup time window> prior to current packet.\n");
764     fprintf(output, "                         A <dup time window> is specified in relative seconds\n");
765     fprintf(output, "                         (e.g. 0.000001).\n");
766     fprintf(output, "           NOTE: The use of the 'Duplicate packet removal' options with\n");
767     fprintf(output, "           other editcap options except -v may not always work as expected.\n");
768     fprintf(output, "           Specifically the -r, -t or -S options will very likely NOT have the\n");
769     fprintf(output, "           desired effect if combined with the -d, -D or -w.\n");
770     fprintf(output, "  --skip-radiotap-header skip radiotap header when checking for packet duplicates.\n");
771     fprintf(output, "                         Useful when processing packets captured by multiple radios\n");
772     fprintf(output, "                         on the same channel in the vicinity of each other.\n");
773     fprintf(output, "\n");
774     fprintf(output, "Packet manipulation:\n");
775     fprintf(output, "  -s <snaplen>           truncate each packet to max. <snaplen> bytes of data.\n");
776     fprintf(output, "  -C [offset:]<choplen>  chop each packet by <choplen> bytes. Positive values\n");
777     fprintf(output, "                         chop at the packet beginning, negative values at the\n");
778     fprintf(output, "                         packet end. If an optional offset precedes the length,\n");
779     fprintf(output, "                         then the bytes chopped will be offset from that value.\n");
780     fprintf(output, "                         Positive offsets are from the packet beginning,\n");
781     fprintf(output, "                         negative offsets are from the packet end. You can use\n");
782     fprintf(output, "                         this option more than once, allowing up to 2 chopping\n");
783     fprintf(output, "                         regions within a packet provided that at least 1\n");
784     fprintf(output, "                         choplen is positive and at least 1 is negative.\n");
785     fprintf(output, "  -L                     adjust the frame (i.e. reported) length when chopping\n");
786     fprintf(output, "                         and/or snapping.\n");
787     fprintf(output, "  -t <time adjustment>   adjust the timestamp of each packet.\n");
788     fprintf(output, "                         <time adjustment> is in relative seconds (e.g. -0.5).\n");
789     fprintf(output, "  -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
790     fprintf(output, "                         strict chronological increasing order. The <strict\n");
791     fprintf(output, "                         adjustment> is specified in relative seconds with\n");
792     fprintf(output, "                         values of 0 or 0.000001 being the most reasonable.\n");
793     fprintf(output, "                         A negative adjustment value will modify timestamps so\n");
794     fprintf(output, "                         that each packet's delta time is the absolute value\n");
795     fprintf(output, "                         of the adjustment specified. A value of -0 will set\n");
796     fprintf(output, "                         all packets to the timestamp of the first packet.\n");
797     fprintf(output, "  -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
798     fprintf(output, "                         a particular packet byte will be randomly changed.\n");
799     fprintf(output, "  -o <change offset>     When used in conjunction with -E, skip some bytes from the\n");
800     fprintf(output, "                         beginning of the packet. This allows one to preserve some\n");
801     fprintf(output, "                         bytes, in order to have some headers untouched.\n");
802     fprintf(output, "  --seed <seed>          When used in conjunction with -E, set the seed to use for\n");
803     fprintf(output, "                         the pseudo-random number generator. This allows one to\n");
804     fprintf(output, "                         repeat a particular sequence of errors.\n");
805     fprintf(output, "  -I <bytes to ignore>   ignore the specified number of bytes at the beginning\n");
806     fprintf(output, "                         of the frame during MD5 hash calculation, unless the\n");
807     fprintf(output, "                         frame is too short, then the full frame is used.\n");
808     fprintf(output, "                         Useful to remove duplicated packets taken on\n");
809     fprintf(output, "                         several routers (different mac addresses for\n");
810     fprintf(output, "                         example).\n");
811     fprintf(output, "                         e.g. -I 26 in case of Ether/IP will ignore\n");
812     fprintf(output, "                         ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
813     fprintf(output, "  -a <framenum>:<comment> Add or replace comment for given frame number\n");
814     fprintf(output, "\n");
815     fprintf(output, "Output File(s):\n");
816     fprintf(output, "  -c <packets per file>  split the packet output to different files based on\n");
817     fprintf(output, "                         uniform packet counts with a maximum of\n");
818     fprintf(output, "                         <packets per file> each.\n");
819     fprintf(output, "  -i <seconds per file>  split the packet output to different files based on\n");
820     fprintf(output, "                         uniform time intervals with a maximum of\n");
821     fprintf(output, "                         <seconds per file> each.\n");
822     fprintf(output, "  -F <capture type>      set the output file type; default is pcapng. An empty\n");
823     fprintf(output, "                         \"-F\" option will list the file types.\n");
824     fprintf(output, "  -T <encap type>        set the output file encapsulation type; default is the\n");
825     fprintf(output, "                         same as the input file. An empty \"-T\" option will\n");
826     fprintf(output, "                         list the encapsulation types.\n");
827     fprintf(output, "\n");
828     fprintf(output, "Miscellaneous:\n");
829     fprintf(output, "  -h                     display this help and exit.\n");
830     fprintf(output, "  -v                     verbose output.\n");
831     fprintf(output, "                         If -v is used with any of the 'Duplicate Packet\n");
832     fprintf(output, "                         Removal' options (-d, -D or -w) then Packet lengths\n");
833     fprintf(output, "                         and MD5 hashes are printed to standard-error.\n");
834 }
835
836 struct string_elem {
837     const char *sstr;   /* The short string */
838     const char *lstr;   /* The long string */
839 };
840
841 static gint
842 string_compare(gconstpointer a, gconstpointer b)
843 {
844     return strcmp(((const struct string_elem *)a)->sstr,
845         ((const struct string_elem *)b)->sstr);
846 }
847
848 static gint
849 string_nat_compare(gconstpointer a, gconstpointer b)
850 {
851     return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
852         ((const struct string_elem *)b)->sstr);
853 }
854
855 static void
856 string_elem_print(gpointer data, gpointer stream_ptr)
857 {
858     fprintf((FILE *) stream_ptr, "    %s - %s\n",
859         ((struct string_elem *)data)->sstr,
860         ((struct string_elem *)data)->lstr);
861 }
862
863 static void
864 list_capture_types(FILE *stream) {
865     int i;
866     struct string_elem *captypes;
867     GSList *list = NULL;
868
869     captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES_SUBTYPES);
870     fprintf(stream, "editcap: The available capture file types for the \"-F\" flag are:\n");
871     for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
872         if (wtap_dump_can_open(i)) {
873             captypes[i].sstr = wtap_file_type_subtype_short_string(i);
874             captypes[i].lstr = wtap_file_type_subtype_string(i);
875             list = g_slist_insert_sorted(list, &captypes[i], string_compare);
876         }
877     }
878     g_slist_foreach(list, string_elem_print, stream);
879     g_slist_free(list);
880     g_free(captypes);
881 }
882
883 static void
884 list_encap_types(FILE *stream) {
885     int i;
886     struct string_elem *encaps;
887     GSList *list = NULL;
888
889     encaps = (struct string_elem *)g_malloc(sizeof(struct string_elem) * WTAP_NUM_ENCAP_TYPES);
890     fprintf(stream, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
891     for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
892         encaps[i].sstr = wtap_encap_short_string(i);
893         if (encaps[i].sstr != NULL) {
894             encaps[i].lstr = wtap_encap_string(i);
895             list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
896         }
897     }
898     g_slist_foreach(list, string_elem_print, stream);
899     g_slist_free(list);
900     g_free(encaps);
901 }
902
903 static int
904 framenum_compare(gconstpointer a, gconstpointer b, gpointer user_data _U_)
905 {
906     if (GPOINTER_TO_UINT(a) < GPOINTER_TO_UINT(b))
907         return -1;
908
909     if (GPOINTER_TO_UINT(a) > GPOINTER_TO_UINT(b))
910         return 1;
911
912     return 0;
913 }
914
915 /*
916  * General errors and warnings are reported with an console message
917  * in editcap.
918  */
919 static void
920 failure_warning_message(const char *msg_format, va_list ap)
921 {
922   fprintf(stderr, "editcap: ");
923   vfprintf(stderr, msg_format, ap);
924   fprintf(stderr, "\n");
925 }
926
927 /*
928  * Report additional information for an error in command-line arguments.
929  */
930 static void
931 failure_message_cont(const char *msg_format, va_list ap)
932 {
933   vfprintf(stderr, msg_format, ap);
934   fprintf(stderr, "\n");
935 }
936
937 static wtap_dumper *
938 editcap_dump_open(const char *filename, guint32 snaplen,
939                   GArray* shb_hdrs,
940                   wtapng_iface_descriptions_t *idb_inf,
941                   GArray* nrb_hdrs, int *write_err)
942 {
943   wtap_dumper *pdh;
944
945   if (strcmp(filename, "-") == 0) {
946     /* Write to the standard output. */
947     pdh = wtap_dump_open_stdout_ng(out_file_type_subtype, out_frame_type,
948                                    snaplen, FALSE /* compressed */,
949                                    shb_hdrs, idb_inf, nrb_hdrs, write_err);
950   } else {
951     pdh = wtap_dump_open_ng(filename, out_file_type_subtype, out_frame_type,
952                             snaplen, FALSE /* compressed */,
953                             shb_hdrs, idb_inf, nrb_hdrs, write_err);
954   }
955   return pdh;
956 }
957
958 static int
959 real_main(int argc, char *argv[])
960 {
961     GString      *comp_info_str;
962     GString      *runtime_info_str;
963     char         *init_progfile_dir_error;
964     wtap         *wth = NULL;
965     int           i, j, read_err, write_err;
966     gchar        *read_err_info, *write_err_info;
967     int           opt;
968     static const struct option long_options[] = {
969         {"novlan", no_argument, NULL, 0x8100},
970         {"skip-radiotap-header", no_argument, NULL, 0x8101},
971         {"seed", required_argument, NULL, 0x8102},
972         {"help", no_argument, NULL, 'h'},
973         {"version", no_argument, NULL, 'V'},
974         {0, 0, 0, 0 }
975     };
976
977     char         *p;
978     guint32       snaplen            = 0; /* No limit               */
979     chop_t        chop               = {0, 0, 0, 0, 0, 0}; /* No chop */
980     gboolean      adjlen             = FALSE;
981     wtap_dumper  *pdh                = NULL;
982     unsigned int  count              = 1;
983     unsigned int  duplicate_count    = 0;
984     gint64        data_offset;
985     int           err_type;
986     guint8       *buf;
987     guint32       read_count         = 0;
988     guint32       split_packet_count = 0;
989     int           written_count      = 0;
990     char         *filename           = NULL;
991     gboolean      ts_okay;
992     guint32       secs_per_block     = 0;
993     int           block_cnt          = 0;
994     nstime_t      block_start;
995     gchar        *fprefix            = NULL;
996     gchar        *fsuffix            = NULL;
997     guint32       change_offset      = 0;
998     guint         max_packet_number  = 0;
999     const wtap_rec              *rec;
1000     wtap_rec                     temp_rec;
1001     wtapng_iface_descriptions_t *idb_inf = NULL;
1002     GArray                      *shb_hdrs = NULL;
1003     GArray                      *nrb_hdrs = NULL;
1004     char                        *shb_user_appl;
1005     gboolean                     do_mutation;
1006     guint32                      caplen;
1007     int                          ret = EXIT_SUCCESS;
1008     gboolean                     valid_seed = FALSE;
1009     unsigned int                 seed = 0;
1010
1011     cmdarg_err_init(failure_warning_message, failure_message_cont);
1012
1013 #ifdef _WIN32
1014     create_app_running_mutex();
1015 #endif /* _WIN32 */
1016
1017     /* Get the compile-time version information string */
1018     comp_info_str = get_compiled_version_info(NULL, NULL);
1019
1020     /* Get the run-time version information string */
1021     runtime_info_str = get_runtime_version_info(NULL);
1022
1023     /* Add it to the information to be reported on a crash. */
1024     ws_add_crash_info("Editcap (Wireshark) %s\n"
1025          "\n"
1026          "%s"
1027          "\n"
1028          "%s",
1029       get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
1030     g_string_free(comp_info_str, TRUE);
1031     g_string_free(runtime_info_str, TRUE);
1032
1033     /*
1034      * Get credential information for later use.
1035      */
1036     init_process_policies();
1037
1038     /*
1039      * Attempt to get the pathname of the directory containing the
1040      * executable file.
1041      */
1042     init_progfile_dir_error = init_progfile_dir(argv[0]);
1043     if (init_progfile_dir_error != NULL) {
1044         fprintf(stderr,
1045                 "editcap: Can't get pathname of directory containing the editcap program: %s.\n",
1046                 init_progfile_dir_error);
1047         g_free(init_progfile_dir_error);
1048     }
1049
1050     init_report_message(failure_warning_message, failure_warning_message,
1051                         NULL, NULL, NULL);
1052
1053     wtap_init(TRUE);
1054
1055     /* Process the options */
1056     while ((opt = getopt_long(argc, argv, ":a:A:B:c:C:dD:E:F:hi:I:Lo:rs:S:t:T:vVw:", long_options, NULL)) != -1) {
1057         switch (opt) {
1058         case 0x8100:
1059         {
1060             rem_vlan = TRUE;
1061             break;
1062         }
1063
1064         case 0x8101:
1065         {
1066             skip_radiotap = TRUE;
1067             break;
1068         }
1069
1070         case 0x8102:
1071         {
1072             if (sscanf(optarg, "%u", &seed) != 1) {
1073                 fprintf(stderr, "editcap: \"%s\" isn't a valid seed\n\n",
1074                         optarg);
1075                 ret = INVALID_OPTION;
1076                 goto clean_exit;
1077             }
1078             valid_seed = TRUE;
1079             break;
1080         }
1081
1082         case 'a':
1083         {
1084             guint frame_number;
1085             gint string_start_index = 0;
1086
1087             if ((sscanf(optarg, "%u:%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1088                 fprintf(stderr, "editcap: \"%s\" isn't a valid <frame>:<comment>\n\n",
1089                         optarg);
1090                 ret = INVALID_OPTION;
1091                 goto clean_exit;
1092             }
1093
1094             /* Lazily create the table */
1095             if (!frames_user_comments) {
1096                 frames_user_comments = g_tree_new_full(framenum_compare, NULL, NULL, g_free);
1097             }
1098
1099             /* Insert this entry (framenum -> comment) */
1100             g_tree_replace(frames_user_comments, GUINT_TO_POINTER(frame_number), g_strdup(optarg+string_start_index));
1101             break;
1102         }
1103
1104         case 'A':
1105         {
1106             struct tm starttm;
1107
1108             memset(&starttm,0,sizeof(struct tm));
1109
1110             if (!strptime(optarg,"%Y-%m-%d %T", &starttm)) {
1111                 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1112                         optarg);
1113                 ret = INVALID_OPTION;
1114                 goto clean_exit;
1115             }
1116
1117             check_startstop = TRUE;
1118             starttm.tm_isdst = -1;
1119
1120             starttime = mktime(&starttm);
1121             break;
1122         }
1123
1124         case 'B':
1125         {
1126             struct tm stoptm;
1127
1128             memset(&stoptm,0,sizeof(struct tm));
1129
1130             if (!strptime(optarg,"%Y-%m-%d %T", &stoptm)) {
1131                 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1132                         optarg);
1133                 ret = INVALID_OPTION;
1134                 goto clean_exit;
1135             }
1136             check_startstop = TRUE;
1137             stoptm.tm_isdst = -1;
1138             stoptime = mktime(&stoptm);
1139             break;
1140         }
1141
1142         case 'c':
1143             split_packet_count = get_nonzero_guint32(optarg, "packet count");
1144             break;
1145
1146         case 'C':
1147         {
1148             int choplen = 0, chopoff = 0;
1149
1150             switch (sscanf(optarg, "%d:%d", &chopoff, &choplen)) {
1151             case 1: /* only the chop length was specififed */
1152                 choplen = chopoff;
1153                 chopoff = 0;
1154                 break;
1155
1156             case 2: /* both an offset and chop length was specified */
1157                 break;
1158
1159             default:
1160                 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length or offset:length\n",
1161                         optarg);
1162                 ret = INVALID_OPTION;
1163                 goto clean_exit;
1164                 break;
1165             }
1166
1167             if (choplen > 0) {
1168                 chop.len_begin += choplen;
1169                 if (chopoff > 0)
1170                     chop.off_begin_pos += chopoff;
1171                 else
1172                     chop.off_begin_neg += chopoff;
1173             } else if (choplen < 0) {
1174                 chop.len_end += choplen;
1175                 if (chopoff > 0)
1176                     chop.off_end_pos += chopoff;
1177                 else
1178                     chop.off_end_neg += chopoff;
1179             }
1180             break;
1181         }
1182
1183         case 'd':
1184             dup_detect = TRUE;
1185             dup_detect_by_time = FALSE;
1186             dup_window = DEFAULT_DUP_DEPTH;
1187             break;
1188
1189         case 'D':
1190             dup_detect = TRUE;
1191             dup_detect_by_time = FALSE;
1192             dup_window = get_guint32(optarg, "duplicate window");
1193             if (dup_window > MAX_DUP_DEPTH) {
1194                 fprintf(stderr, "editcap: \"%d\" duplicate window value must be between 0 and %d inclusive.\n",
1195                         dup_window, MAX_DUP_DEPTH);
1196                 ret = INVALID_OPTION;
1197                 goto clean_exit;
1198             }
1199             break;
1200
1201         case 'E':
1202             err_prob = g_ascii_strtod(optarg, &p);
1203             if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
1204                 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
1205                         optarg);
1206                 ret = INVALID_OPTION;
1207                 goto clean_exit;
1208             }
1209             break;
1210
1211         case 'F':
1212             out_file_type_subtype = wtap_short_string_to_file_type_subtype(optarg);
1213             if (out_file_type_subtype < 0) {
1214                 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
1215                         optarg);
1216                 list_capture_types(stderr);
1217                 ret = INVALID_OPTION;
1218                 goto clean_exit;
1219             }
1220             break;
1221
1222         case 'h':
1223             printf("Editcap (Wireshark) %s\n"
1224                    "Edit and/or translate the format of capture files.\n"
1225                    "See https://www.wireshark.org for more information.\n",
1226                get_ws_vcs_version_info());
1227             print_usage(stdout);
1228             goto clean_exit;
1229             break;
1230
1231         case 'i': /* break capture file based on time interval */
1232             secs_per_block = get_nonzero_guint32(optarg, "time interval");
1233             break;
1234
1235         case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1236             ignored_bytes = get_guint32(optarg, "number of bytes to ignore");
1237             break;
1238
1239         case 'L':
1240             adjlen = TRUE;
1241             break;
1242
1243         case 'o':
1244             change_offset = get_guint32(optarg, "change offset");
1245             break;
1246
1247         case 'r':
1248             keep_em = !keep_em;  /* Just invert */
1249             break;
1250
1251         case 's':
1252             snaplen = get_nonzero_guint32(optarg, "snapshot length");
1253             break;
1254
1255         case 'S':
1256             if (!set_strict_time_adj(optarg)) {
1257                 ret = INVALID_OPTION;
1258                 goto clean_exit;
1259             }
1260             do_strict_time_adjustment = TRUE;
1261             break;
1262
1263         case 't':
1264             if (!set_time_adjustment(optarg)) {
1265                 ret = INVALID_OPTION;
1266                 goto clean_exit;
1267             }
1268             break;
1269
1270         case 'T':
1271             out_frame_type = wtap_short_string_to_encap(optarg);
1272             if (out_frame_type < 0) {
1273                 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
1274                         optarg);
1275                 list_encap_types(stderr);
1276                 ret = INVALID_OPTION;
1277                 goto clean_exit;
1278             }
1279             break;
1280
1281         case 'v':
1282             verbose = !verbose;  /* Just invert */
1283             break;
1284
1285         case 'V':
1286             comp_info_str = get_compiled_version_info(NULL, NULL);
1287             runtime_info_str = get_runtime_version_info(NULL);
1288             show_version("Editcap (Wireshark)", comp_info_str, runtime_info_str);
1289             g_string_free(comp_info_str, TRUE);
1290             g_string_free(runtime_info_str, TRUE);
1291             goto clean_exit;
1292             break;
1293
1294         case 'w':
1295             dup_detect = FALSE;
1296             dup_detect_by_time = TRUE;
1297             dup_window = MAX_DUP_DEPTH;
1298             if (!set_rel_time(optarg)) {
1299                 ret = INVALID_OPTION;
1300                 goto clean_exit;
1301             }
1302             break;
1303
1304         case '?':              /* Bad options if GNU getopt */
1305         case ':':              /* missing option argument */
1306             switch(optopt) {
1307             case'F':
1308                 list_capture_types(stdout);
1309                 break;
1310             case'T':
1311                 list_encap_types(stdout);
1312                 break;
1313             default:
1314                 if (opt == '?') {
1315                     fprintf(stderr, "editcap: invalid option -- '%c'\n", optopt);
1316                 } else {
1317                     fprintf(stderr, "editcap: option requires an argument -- '%c'\n", optopt);
1318                 }
1319                 print_usage(stderr);
1320                 ret = INVALID_OPTION;
1321                 break;
1322             }
1323             goto clean_exit;
1324             break;
1325         }
1326     } /* processing commmand-line options */
1327
1328 #ifdef DEBUG
1329     fprintf(stderr, "Optind = %i, argc = %i\n", optind, argc);
1330 #endif
1331
1332     if ((argc - optind) < 1) {
1333         print_usage(stderr);
1334         ret = INVALID_OPTION;
1335         goto clean_exit;
1336
1337     }
1338
1339     if (err_prob >= 0.0) {
1340         if (!valid_seed) {
1341             seed = (unsigned int) (time(NULL) + ws_getpid());
1342         }
1343         if (verbose) {
1344             fprintf(stderr, "Using seed %u\n", seed);
1345         }
1346         srand(seed);
1347     }
1348
1349     if (check_startstop && !stoptime) {
1350         struct tm stoptm;
1351
1352         /* XXX: will work until 2035 */
1353         memset(&stoptm,0,sizeof(struct tm));
1354         stoptm.tm_year = 135;
1355         stoptm.tm_mday = 31;
1356         stoptm.tm_mon = 11;
1357         stoptm.tm_isdst = -1;
1358
1359         stoptime = mktime(&stoptm);
1360     }
1361
1362     nstime_set_unset(&block_start);
1363
1364     if (starttime > stoptime) {
1365         fprintf(stderr, "editcap: start time is after the stop time\n");
1366         ret = INVALID_OPTION;
1367         goto clean_exit;
1368     }
1369
1370     if (split_packet_count != 0 && secs_per_block != 0) {
1371         fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
1372         fprintf(stderr, "editcap: at the same time\n");
1373         ret = INVALID_OPTION;
1374         goto clean_exit;
1375     }
1376
1377     wth = wtap_open_offline(argv[optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, FALSE);
1378
1379     if (!wth) {
1380         cfile_open_failure_message("editcap", argv[optind], read_err,
1381                                    read_err_info);
1382         ret = INVALID_FILE;
1383         goto clean_exit;
1384     }
1385
1386     if (verbose) {
1387         fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
1388                 wtap_file_type_subtype_string(wtap_file_type_subtype(wth)));
1389     }
1390
1391     if (ignored_bytes != 0 && skip_radiotap == TRUE) {
1392         fprintf(stderr, "editcap: can't skip radiotap headers and %d byte(s)\n", ignored_bytes);
1393         fprintf(stderr, "editcap: at the start of packet at the same time\n");
1394         ret = INVALID_OPTION;
1395         goto clean_exit;
1396     }
1397
1398     if (skip_radiotap == TRUE && wtap_file_encap(wth) != WTAP_ENCAP_IEEE_802_11_RADIOTAP) {
1399         fprintf(stderr, "editcap: can't skip radiotap header because input file is incorrect\n");
1400         fprintf(stderr, "editcap: expected '%s', input is '%s'\n",
1401                 wtap_encap_string(WTAP_ENCAP_IEEE_802_11_RADIOTAP),
1402                 wtap_encap_string(wtap_file_type_subtype(wth)));
1403         ret = INVALID_OPTION;
1404         goto clean_exit;
1405     }
1406
1407     shb_hdrs = wtap_file_get_shb_for_new_file(wth);
1408     idb_inf = wtap_file_get_idb_info(wth);
1409     nrb_hdrs = wtap_file_get_nrb_for_new_file(wth);
1410
1411     /*
1412      * Now, process the rest, if any ... we only write if there is an extra
1413      * argument or so ...
1414      */
1415
1416     if ((argc - optind) >= 2) {
1417         if (out_frame_type == -2)
1418             out_frame_type = wtap_file_encap(wth);
1419
1420         for (i = optind + 2; i < argc; i++)
1421             if (add_selection(argv[i], &max_packet_number) == FALSE)
1422                 break;
1423
1424         if (keep_em == FALSE)
1425             max_packet_number = G_MAXUINT;
1426
1427         if (dup_detect || dup_detect_by_time) {
1428             for (i = 0; i < dup_window; i++) {
1429                 memset(&fd_hash[i].digest, 0, 16);
1430                 fd_hash[i].len = 0;
1431                 nstime_set_unset(&fd_hash[i].frame_time);
1432             }
1433         }
1434
1435         /* Read all of the packets in turn */
1436         while (wtap_read(wth, &read_err, &read_err_info, &data_offset)) {
1437             if (max_packet_number <= read_count)
1438                 break;
1439
1440             read_count++;
1441
1442             rec = wtap_get_rec(wth);
1443
1444             /* Extra actions for the first packet */
1445             if (read_count == 1) {
1446                 if (split_packet_count != 0 || secs_per_block != 0) {
1447                     if (!fileset_extract_prefix_suffix(argv[optind+1], &fprefix, &fsuffix)) {
1448                         ret = CANT_EXTRACT_PREFIX;
1449                         goto clean_exit;
1450                     }
1451
1452                     filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1453                 } else {
1454                     filename = g_strdup(argv[optind+1]);
1455                 }
1456                 g_assert(filename);
1457
1458                 /* If we don't have an application name add Editcap */
1459                 if (wtap_block_get_string_option_value(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
1460                     wtap_block_add_string_option_format(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "Editcap " VERSION);
1461                 }
1462
1463                 pdh = editcap_dump_open(filename,
1464                                         snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1465                                         shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1466
1467                 if (pdh == NULL) {
1468                     cfile_dump_open_failure_message("editcap", filename,
1469                                                     write_err,
1470                                                     out_file_type_subtype);
1471                     ret = INVALID_FILE;
1472                     goto clean_exit;
1473                 }
1474             } /* first packet only handling */
1475
1476
1477             buf = wtap_get_buf_ptr(wth);
1478
1479             /*
1480              * Not all packets have time stamps. Only process the time
1481              * stamp if we have one.
1482              */
1483             if (rec->presence_flags & WTAP_HAS_TS) {
1484                 if (nstime_is_unset(&block_start)) {
1485                     block_start = rec->ts;
1486                 }
1487                 if (secs_per_block != 0) {
1488                     while (((guint32)(rec->ts.secs - block_start.secs) >  secs_per_block)
1489                            || ((guint32)(rec->ts.secs - block_start.secs) == secs_per_block
1490                                && rec->ts.nsecs >= block_start.nsecs )) { /* time for the next file */
1491
1492                         if (!wtap_dump_close(pdh, &write_err)) {
1493                             cfile_close_failure_message(filename, write_err);
1494                             ret = WRITE_ERROR;
1495                             goto clean_exit;
1496                         }
1497                         block_start.secs = block_start.secs +  secs_per_block; /* reset for next interval */
1498                         g_free(filename);
1499                         filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1500                         g_assert(filename);
1501
1502                         if (verbose)
1503                             fprintf(stderr, "Continuing writing in file %s\n", filename);
1504
1505                         pdh = editcap_dump_open(filename,
1506                                                 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1507                                                 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1508
1509                         if (pdh == NULL) {
1510                             cfile_dump_open_failure_message("editcap", filename,
1511                                                             write_err,
1512                                                             out_file_type_subtype);
1513                             ret = INVALID_FILE;
1514                             goto clean_exit;
1515                         }
1516                     }
1517                 }
1518             }  /* time stamp handling */
1519
1520             if (split_packet_count != 0) {
1521                 /* time for the next file? */
1522                 if (written_count > 0 && (written_count % split_packet_count) == 0) {
1523                     if (!wtap_dump_close(pdh, &write_err)) {
1524                         cfile_close_failure_message(filename, write_err);
1525                         ret = WRITE_ERROR;
1526                         goto clean_exit;
1527                     }
1528
1529                     g_free(filename);
1530                     filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1531                     g_assert(filename);
1532
1533                     if (verbose)
1534                         fprintf(stderr, "Continuing writing in file %s\n", filename);
1535
1536                     pdh = editcap_dump_open(filename,
1537                                             snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1538                                             shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1539                     if (pdh == NULL) {
1540                         cfile_dump_open_failure_message("editcap", filename,
1541                                                         write_err,
1542                                                         out_file_type_subtype);
1543                         ret = INVALID_FILE;
1544                         goto clean_exit;
1545                     }
1546                 }
1547             } /* split packet handling */
1548
1549             if (check_startstop) {
1550                 /*
1551                  * Is the packet in the selected timeframe?
1552                  * If the packet has no time stamp, the answer is "no".
1553                  */
1554                 if (rec->presence_flags & WTAP_HAS_TS)
1555                     ts_okay = (rec->ts.secs >= starttime) && (rec->ts.secs < stoptime);
1556                 else
1557                     ts_okay = FALSE;
1558             } else {
1559                 /*
1560                  * No selected timeframe, so all packets are "in the
1561                  * selected timeframe".
1562                  */
1563                 ts_okay = TRUE;
1564             }
1565
1566             if (ts_okay && ((!selected(count) && !keep_em)
1567                             || (selected(count) && keep_em))) {
1568
1569                 if (verbose && !dup_detect && !dup_detect_by_time)
1570                     fprintf(stderr, "Packet: %u\n", count);
1571
1572                 /* We simply write it, perhaps after truncating it; we could
1573                  * do other things, like modify it. */
1574
1575                 rec = wtap_get_rec(wth);
1576
1577                 if (rec->presence_flags & WTAP_HAS_TS) {
1578                     /* Do we adjust timestamps to ensure strict chronological
1579                      * order? */
1580                     if (do_strict_time_adjustment) {
1581                         if (previous_time.secs || previous_time.nsecs) {
1582                             if (!strict_time_adj.is_negative) {
1583                                 nstime_t current;
1584                                 nstime_t delta;
1585
1586                                 current = rec->ts;
1587
1588                                 nstime_delta(&delta, &current, &previous_time);
1589
1590                                 if (delta.secs < 0 || delta.nsecs < 0) {
1591                                     /*
1592                                      * A negative delta indicates that the current packet
1593                                      * has an absolute timestamp less than the previous packet
1594                                      * that it is being compared to.  This is NOT a normal
1595                                      * situation since trace files usually have packets in
1596                                      * chronological order (oldest to newest).
1597                                      * Copy and change rather than modify
1598                                      * returned rec.
1599                                      */
1600                                     /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
1601                                     temp_rec = *rec;
1602                                     temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1603                                     temp_rec.ts.nsecs = previous_time.nsecs;
1604                                     if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1605                                         /* carry */
1606                                         temp_rec.ts.secs++;
1607                                         temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1608                                     } else {
1609                                         temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1610                                     }
1611                                     rec = &temp_rec;
1612                                 }
1613                             } else {
1614                                 /*
1615                                  * A negative strict time adjustment is requested.
1616                                  * Unconditionally set each timestamp to previous
1617                                  * packet's timestamp plus delta.
1618                                  * Copy and change rather than modify returned
1619                                  * rec.
1620                                  */
1621                                 temp_rec = *rec;
1622                                 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1623                                 temp_rec.ts.nsecs = previous_time.nsecs;
1624                                 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1625                                     /* carry */
1626                                     temp_rec.ts.secs++;
1627                                     temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1628                                 } else {
1629                                     temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1630                                 }
1631                                 rec = &temp_rec;
1632                             }
1633                         }
1634                         previous_time = rec->ts;
1635                     }
1636
1637                     if (time_adj.tv.secs != 0) {
1638                         /* Copy and change rather than modify returned rec */
1639                         temp_rec = *rec;
1640                         if (time_adj.is_negative)
1641                             temp_rec.ts.secs -= time_adj.tv.secs;
1642                         else
1643                             temp_rec.ts.secs += time_adj.tv.secs;
1644                         rec = &temp_rec;
1645                     }
1646
1647                     if (time_adj.tv.nsecs != 0) {
1648                         /* Copy and change rather than modify returned rec */
1649                         temp_rec = *rec;
1650                         if (time_adj.is_negative) { /* subtract */
1651                             if (temp_rec.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
1652                                 temp_rec.ts.secs--;
1653                                 temp_rec.ts.nsecs += ONE_BILLION;
1654                             }
1655                             temp_rec.ts.nsecs -= time_adj.tv.nsecs;
1656                         } else {                  /* add */
1657                             if (temp_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
1658                                 /* carry */
1659                                 temp_rec.ts.secs++;
1660                                 temp_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
1661                             } else {
1662                                 temp_rec.ts.nsecs += time_adj.tv.nsecs;
1663                             }
1664                         }
1665                         rec = &temp_rec;
1666                     }
1667                 } /* time stamp adjustment */
1668
1669                 if (rec->rec_type == REC_TYPE_PACKET) {
1670                     if (snaplen != 0) {
1671                         /* Limit capture length to snaplen */
1672                         if (rec->rec_header.packet_header.caplen > snaplen) {
1673                             /* Copy and change rather than modify returned wtap_rec */
1674                             temp_rec = *rec;
1675                             temp_rec.rec_header.packet_header.caplen = snaplen;
1676                             rec = &temp_rec;
1677                         }
1678                         /* If -L, also set reported length to snaplen */
1679                         if (adjlen && rec->rec_header.packet_header.len > snaplen) {
1680                             /* Copy and change rather than modify returned phdr */
1681                             temp_rec = *rec;
1682                             temp_rec.rec_header.packet_header.len = snaplen;
1683                             rec = &temp_rec;
1684                         }
1685                     }
1686
1687                     /*
1688                      * CHOP
1689                      * Copy and change rather than modify returned phdr.
1690                      */
1691                     temp_rec = *rec;
1692                     handle_chopping(chop, &temp_rec.rec_header.packet_header,
1693                                     &rec->rec_header.packet_header, &buf,
1694                                     adjlen);
1695                     rec = &temp_rec;
1696
1697                     /* remove vlan info */
1698                     if (rem_vlan) {
1699                         /* Copy and change rather than modify returned rec */
1700                         temp_rec = *rec;
1701                         remove_vlan_info(&rec->rec_header.packet_header, buf,
1702                                          &temp_rec.rec_header.packet_header.caplen);
1703                         rec = &temp_rec;
1704                     }
1705
1706                     /* suppress duplicates by packet window */
1707                     if (dup_detect) {
1708                         if (is_duplicate(buf, rec->rec_header.packet_header.caplen)) {
1709                             if (verbose) {
1710                                 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1711                                         count,
1712                                         rec->rec_header.packet_header.caplen);
1713                                 for (i = 0; i < 16; i++)
1714                                     fprintf(stderr, "%02x",
1715                                             (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1716                                 fprintf(stderr, "\n");
1717                             }
1718                             duplicate_count++;
1719                             count++;
1720                             continue;
1721                         } else {
1722                             if (verbose) {
1723                                 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1724                                         count,
1725                                         rec->rec_header.packet_header.caplen);
1726                                 for (i = 0; i < 16; i++)
1727                                     fprintf(stderr, "%02x",
1728                                             (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1729                                 fprintf(stderr, "\n");
1730                             }
1731                         }
1732                     } /* suppression of duplicates */
1733
1734                     if (rec->presence_flags & WTAP_HAS_TS) {
1735                         /* suppress duplicates by time window */
1736                         if (dup_detect_by_time) {
1737                             nstime_t current;
1738
1739                             current.secs  = rec->ts.secs;
1740                             current.nsecs = rec->ts.nsecs;
1741
1742                             if (is_duplicate_rel_time(buf,
1743                                                       rec->rec_header.packet_header.caplen,
1744                                                       &current)) {
1745                                 if (verbose) {
1746                                     fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1747                                             count,
1748                                             rec->rec_header.packet_header.caplen);
1749                                     for (i = 0; i < 16; i++)
1750                                         fprintf(stderr, "%02x",
1751                                                 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1752                                     fprintf(stderr, "\n");
1753                                 }
1754                                 duplicate_count++;
1755                                 count++;
1756                                 continue;
1757                             } else {
1758                                 if (verbose) {
1759                                     fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1760                                             count,
1761                                             rec->rec_header.packet_header.caplen);
1762                                     for (i = 0; i < 16; i++)
1763                                         fprintf(stderr, "%02x",
1764                                                 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1765                                     fprintf(stderr, "\n");
1766                                 }
1767                             }
1768                         }
1769                     } /* suppress duplicates by time window */
1770                 }
1771
1772                 /* Random error mutation */
1773                 do_mutation = FALSE;
1774                 caplen = 0;
1775                 if (err_prob > 0.0) {
1776                     switch (rec->rec_type) {
1777
1778                     case REC_TYPE_PACKET:
1779                         caplen = rec->rec_header.packet_header.caplen;
1780                         do_mutation = TRUE;
1781                         break;
1782
1783                     case REC_TYPE_FT_SPECIFIC_EVENT:
1784                     case REC_TYPE_FT_SPECIFIC_REPORT:
1785                         caplen = rec->rec_header.ft_specific_header.record_len;
1786                         do_mutation = TRUE;
1787                         break;
1788
1789                     case REC_TYPE_SYSCALL:
1790                         caplen = rec->rec_header.syscall_header.event_filelen;
1791                         do_mutation = TRUE;
1792                         break;
1793                     }
1794
1795                     if (change_offset > caplen) {
1796                         fprintf(stderr, "change offset %u is longer than caplen %u in packet %u\n",
1797                             change_offset, caplen, count);
1798                         do_mutation = FALSE;
1799                     }
1800                 }
1801
1802                 if (do_mutation) {
1803                     int real_data_start = 0;
1804
1805                     /* Protect non-protocol data */
1806                     switch (rec->rec_type) {
1807
1808                     case REC_TYPE_PACKET:
1809                         if (wtap_file_type_subtype(wth) == WTAP_FILE_TYPE_SUBTYPE_CATAPULT_DCT2000)
1810                             real_data_start = find_dct2000_real_data(buf);
1811                         break;
1812                     }
1813
1814                     real_data_start += change_offset;
1815
1816                     for (i = real_data_start; i < (int) caplen; i++) {
1817                         if (rand() <= err_prob * RAND_MAX) {
1818                             err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
1819
1820                             if (err_type < ERR_WT_BIT) {
1821                                 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
1822                                 err_type = ERR_WT_TOTAL;
1823                             } else {
1824                                 err_type -= ERR_WT_BYTE;
1825                             }
1826
1827                             if (err_type < ERR_WT_BYTE) {
1828                                 buf[i] = rand() / (RAND_MAX / 255 + 1);
1829                                 err_type = ERR_WT_TOTAL;
1830                             } else {
1831                                 err_type -= ERR_WT_BYTE;
1832                             }
1833
1834                             if (err_type < ERR_WT_ALNUM) {
1835                                 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
1836                                 err_type = ERR_WT_TOTAL;
1837                             } else {
1838                                 err_type -= ERR_WT_ALNUM;
1839                             }
1840
1841                             if (err_type < ERR_WT_FMT) {
1842                                 if ((unsigned int)i < caplen - 2)
1843                                     g_strlcpy((char*) &buf[i], "%s", 2);
1844                                 err_type = ERR_WT_TOTAL;
1845                             } else {
1846                                 err_type -= ERR_WT_FMT;
1847                             }
1848
1849                             if (err_type < ERR_WT_AA) {
1850                                 for (j = i; j < (int) caplen; j++)
1851                                     buf[j] = 0xAA;
1852                                 i = caplen;
1853                             }
1854                         }
1855                     }
1856                 } /* random error mutation */
1857
1858                 /* Find a packet comment we may need to write */
1859                 if (frames_user_comments) {
1860                     const char *comment =
1861                         (const char*)g_tree_lookup(frames_user_comments, GUINT_TO_POINTER(read_count));
1862                     /* XXX: What about comment changed to no comment? */
1863                     if (comment != NULL) {
1864                         /* Copy and change rather than modify returned rec */
1865                         temp_rec = *rec;
1866                         temp_rec.opt_comment = g_strdup(comment);
1867                         temp_rec.has_comment_changed = TRUE;
1868                         rec = &temp_rec;
1869                     } else {
1870                         /* Copy and change rather than modify returned rec */
1871                         temp_rec = *rec;
1872                         temp_rec.has_comment_changed = FALSE;
1873                         rec = &temp_rec;
1874                     }
1875                 }
1876
1877                 /* Attempt to dump out current frame to the output file */
1878                 if (!wtap_dump(pdh, rec, buf, &write_err, &write_err_info)) {
1879                     cfile_write_failure_message("editcap", argv[optind],
1880                                                 filename,
1881                                                 write_err, write_err_info,
1882                                                 read_count,
1883                                                 out_file_type_subtype);
1884                     ret = DUMP_ERROR;
1885                     goto clean_exit;
1886                 }
1887                 written_count++;
1888             }
1889             count++;
1890         }
1891
1892         g_free(fprefix);
1893         g_free(fsuffix);
1894
1895         if (read_err != 0) {
1896             /* Print a message noting that the read failed somewhere along the
1897              * line. */
1898             cfile_read_failure_message("editcap", argv[optind], read_err,
1899                                        read_err_info);
1900         }
1901
1902         if (!pdh) {
1903             /* No valid packages found, open the outfile so we can write an
1904              * empty header */
1905             g_free (filename);
1906             filename = g_strdup(argv[optind+1]);
1907
1908             pdh = editcap_dump_open(filename,
1909                                     snaplen ? MIN(snaplen, wtap_snapshot_length(wth)): wtap_snapshot_length(wth),
1910                                     shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1911             if (pdh == NULL) {
1912                 cfile_dump_open_failure_message("editcap", filename,
1913                                                 write_err,
1914                                                 out_file_type_subtype);
1915                 ret = INVALID_FILE;
1916                 goto clean_exit;
1917             }
1918         }
1919
1920         if (!wtap_dump_close(pdh, &write_err)) {
1921             cfile_close_failure_message(filename, write_err);
1922             ret = WRITE_ERROR;
1923             goto clean_exit;
1924         }
1925         g_free(filename);
1926
1927         if (frames_user_comments) {
1928             g_tree_destroy(frames_user_comments);
1929         }
1930     }
1931
1932     if (dup_detect) {
1933         fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate window of %i packets.\n",
1934                 count - 1, plurality(count - 1, "", "s"), duplicate_count,
1935                 plurality(duplicate_count, "", "s"), dup_window);
1936     } else if (dup_detect_by_time) {
1937         fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
1938                 count - 1, plurality(count - 1, "", "s"), duplicate_count,
1939                 plurality(duplicate_count, "", "s"),
1940                 (long)relative_time_window.secs,
1941                 (long int)relative_time_window.nsecs);
1942     }
1943
1944 clean_exit:
1945     wtap_block_array_free(shb_hdrs);
1946     wtap_block_array_free(nrb_hdrs);
1947     g_free(idb_inf);
1948     if (wth != NULL)
1949         wtap_close(wth);
1950     wtap_cleanup();
1951     free_progdirs();
1952     return ret;
1953 }
1954
1955 #ifdef _WIN32
1956 int
1957 wmain(int argc, wchar_t *wc_argv[])
1958 {
1959     char **argv;
1960
1961     argv = arg_list_utf_16to8(argc, wc_argv);
1962     return real_main(argc, argv);
1963 }
1964 #else
1965 int
1966 main(int argc, char *argv[])
1967 {
1968     return real_main(argc, argv);
1969 }
1970 #endif
1971
1972 /* Skip meta-information read from file to return offset of real
1973  * protocol data */
1974 static int
1975 find_dct2000_real_data(guint8 *buf)
1976 {
1977     int n = 0;
1978
1979     for (n = 0; buf[n] != '\0'; n++);   /* Context name */
1980     n++;
1981     n++;                                /* Context port number */
1982     for (; buf[n] != '\0'; n++);        /* Timestamp */
1983     n++;
1984     for (; buf[n] != '\0'; n++);        /* Protocol name */
1985     n++;
1986     for (; buf[n] != '\0'; n++);        /* Variant number (as string) */
1987     n++;
1988     for (; buf[n] != '\0'; n++);        /* Outhdr (as string) */
1989     n++;
1990     n += 2;                             /* Direction & encap */
1991
1992     return n;
1993 }
1994
1995 /*
1996  * We support up to 2 chopping regions in a single pass: one specified by the
1997  * positive chop length, and one by the negative chop length.
1998  */
1999 static void
2000 handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
2001                 const wtap_packet_header *in_phdr, guint8 **buf,
2002                 gboolean adjlen)
2003 {
2004     /* If we're not chopping anything from one side, then the offset for that
2005      * side is meaningless. */
2006     if (chop.len_begin == 0)
2007         chop.off_begin_pos = chop.off_begin_neg = 0;
2008     if (chop.len_end == 0)
2009         chop.off_end_pos = chop.off_end_neg = 0;
2010
2011     if (chop.off_begin_neg < 0) {
2012         chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
2013         chop.off_begin_neg = 0;
2014     }
2015     if (chop.off_end_pos > 0) {
2016         chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
2017         chop.off_end_pos = 0;
2018     }
2019
2020     /* If we've crossed chopping regions, swap them */
2021     if (chop.len_begin && chop.len_end) {
2022         if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
2023             int tmp_len, tmp_off;
2024
2025             tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
2026             tmp_len = -chop.len_end;
2027
2028             chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
2029             chop.len_end = -chop.len_begin;
2030
2031             chop.len_begin = tmp_len;
2032             chop.off_begin_pos = tmp_off;
2033         }
2034     }
2035
2036     /* Make sure we don't chop off more than we have available */
2037     if (in_phdr->caplen < (guint32)(chop.off_begin_pos - chop.off_end_neg)) {
2038         chop.len_begin = 0;
2039         chop.len_end = 0;
2040     }
2041     if ((guint32)(chop.len_begin - chop.len_end) >
2042         (in_phdr->caplen - (guint32)(chop.off_begin_pos - chop.off_end_neg))) {
2043         chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
2044         chop.len_end = 0;
2045     }
2046
2047     /* Handle chopping from the beginning.  Note that if a beginning offset
2048      * was specified, we need to keep that piece */
2049     if (chop.len_begin > 0) {
2050         *out_phdr = *in_phdr;
2051
2052         if (chop.off_begin_pos > 0) {
2053             memmove(*buf + chop.off_begin_pos,
2054                     *buf + chop.off_begin_pos + chop.len_begin,
2055                     out_phdr->caplen - chop.len_begin);
2056         } else {
2057             *buf += chop.len_begin;
2058         }
2059         out_phdr->caplen -= chop.len_begin;
2060
2061         if (adjlen) {
2062             if (in_phdr->len > (guint32)chop.len_begin)
2063                 out_phdr->len -= chop.len_begin;
2064             else
2065                 out_phdr->len = 0;
2066         }
2067         in_phdr = out_phdr;
2068     }
2069
2070     /* Handle chopping from the end.  Note that if an ending offset was
2071      * specified, we need to keep that piece */
2072     if (chop.len_end < 0) {
2073         *out_phdr = *in_phdr;
2074
2075         if (chop.off_end_neg < 0) {
2076             memmove(*buf + (gint)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2077                     *buf + (gint)out_phdr->caplen + chop.off_end_neg,
2078                     -chop.off_end_neg);
2079         }
2080         out_phdr->caplen += chop.len_end;
2081
2082         if (adjlen) {
2083             if (((signed int) in_phdr->len + chop.len_end) > 0)
2084                 out_phdr->len += chop.len_end;
2085             else
2086                 out_phdr->len = 0;
2087         }
2088         /*in_phdr = out_phdr;*/
2089     }
2090 }
2091
2092 /*
2093  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
2094  *
2095  * Local variables:
2096  * c-basic-offset: 4
2097  * tab-width: 8
2098  * indent-tabs-mode: nil
2099  * End:
2100  *
2101  * vi: set shiftwidth=4 tabstop=8 expandtab:
2102  * :indentSize=4:tabSize=8:noTabs=true:
2103  */