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