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