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