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