HTTPS (almost) everywhere.
[metze/wireshark/wip.git] / editcap.c
1 /* editcap.c
2  * Edit capture files.  We can delete packets, adjust timestamps, or
3  * simply convert from one format to another format.
4  *
5  * Originally written by Richard Sharpe.
6  * Improved by Guy Harris.
7  * Further improved by Richard Sharpe.
8  *
9  * Copyright 2013, Richard Sharpe <realrichardsharpe[AT]gmail.com>
10  *
11  * Wireshark - Network traffic analyzer
12  * By Gerald Combs <gerald@wireshark.org>
13  * Copyright 1998 Gerald Combs
14  *
15  * SPDX-License-Identifier: GPL-2.0-or-later
16  */
17
18 #include <config.h>
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <stdarg.h>
24 #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 #define LONGOPT_NO_VLAN              0x8100
1021 #define LONGOPT_SKIP_RADIOTAP_HEADER 0x8101
1022 #define LONGOPT_SEED                 0x8102
1023 #define LONGOPT_INJECT_SECRETS       0x8103
1024 #define LONGOPT_DISCARD_ALL_SECRETS  0x8104
1025     static const struct option long_options[] = {
1026         {"novlan", no_argument, NULL, LONGOPT_NO_VLAN},
1027         {"skip-radiotap-header", no_argument, NULL, LONGOPT_SKIP_RADIOTAP_HEADER},
1028         {"seed", required_argument, NULL, LONGOPT_SEED},
1029         {"inject-secrets", required_argument, NULL, LONGOPT_INJECT_SECRETS},
1030         {"discard-all-secrets", no_argument, NULL, LONGOPT_DISCARD_ALL_SECRETS},
1031         {"help", no_argument, NULL, 'h'},
1032         {"version", no_argument, NULL, 'V'},
1033         {0, 0, 0, 0 }
1034     };
1035
1036     char         *p;
1037     guint32       snaplen            = 0; /* No limit               */
1038     chop_t        chop               = {0, 0, 0, 0, 0, 0}; /* No chop */
1039     gboolean      adjlen             = FALSE;
1040     wtap_dumper  *pdh                = NULL;
1041     unsigned int  count              = 1;
1042     unsigned int  duplicate_count    = 0;
1043     gint64        data_offset;
1044     int           err_type;
1045     guint8       *buf;
1046     guint32       read_count         = 0;
1047     guint32       split_packet_count = 0;
1048     int           written_count      = 0;
1049     char         *filename           = NULL;
1050     gboolean      ts_okay;
1051     nstime_t      secs_per_block     = NSTIME_INIT_UNSET;
1052     int           block_cnt          = 0;
1053     nstime_t      block_next         = NSTIME_INIT_UNSET;
1054     gchar        *fprefix            = NULL;
1055     gchar        *fsuffix            = NULL;
1056     guint32       change_offset      = 0;
1057     guint         max_packet_number  = 0;
1058     GArray       *dsb_types          = NULL;
1059     GPtrArray    *dsb_filenames      = NULL;
1060     wtap_rec                     read_rec;
1061     Buffer                       read_buf;
1062     const wtap_rec              *rec;
1063     wtap_rec                     temp_rec;
1064     wtap_dump_params             params = WTAP_DUMP_PARAMS_INIT;
1065     char                        *shb_user_appl;
1066     gboolean                     do_mutation;
1067     guint32                      caplen;
1068     int                          ret = EXIT_SUCCESS;
1069     gboolean                     valid_seed = FALSE;
1070     unsigned int                 seed = 0;
1071
1072     cmdarg_err_init(failure_warning_message, failure_message_cont);
1073
1074 #ifdef _WIN32
1075     create_app_running_mutex();
1076 #endif /* _WIN32 */
1077
1078     /* Initialize the version information. */
1079     ws_init_version_info("Editcap (Wireshark)", NULL, NULL, NULL);
1080
1081     /*
1082      * Get credential information for later use.
1083      */
1084     init_process_policies();
1085
1086     /*
1087      * Attempt to get the pathname of the directory containing the
1088      * executable file.
1089      */
1090     init_progfile_dir_error = init_progfile_dir(argv[0]);
1091     if (init_progfile_dir_error != NULL) {
1092         fprintf(stderr,
1093                 "editcap: Can't get pathname of directory containing the editcap program: %s.\n",
1094                 init_progfile_dir_error);
1095         g_free(init_progfile_dir_error);
1096     }
1097
1098     init_report_message(failure_warning_message, failure_warning_message,
1099                         NULL, NULL, NULL);
1100
1101     wtap_init(TRUE);
1102
1103     /* Process the options */
1104     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) {
1105         switch (opt) {
1106         case LONGOPT_NO_VLAN:
1107         {
1108             rem_vlan = TRUE;
1109             break;
1110         }
1111
1112         case LONGOPT_SKIP_RADIOTAP_HEADER:
1113         {
1114             skip_radiotap = TRUE;
1115             break;
1116         }
1117
1118         case LONGOPT_SEED:
1119         {
1120             if (sscanf(optarg, "%u", &seed) != 1) {
1121                 fprintf(stderr, "editcap: \"%s\" isn't a valid seed\n\n",
1122                         optarg);
1123                 ret = INVALID_OPTION;
1124                 goto clean_exit;
1125             }
1126             valid_seed = TRUE;
1127             break;
1128         }
1129
1130         case LONGOPT_INJECT_SECRETS:
1131         {
1132             guint32 secrets_type_id = 0;
1133             const char *secrets_filename = NULL;
1134             if (strcmp("help", optarg) == 0) {
1135                 list_secrets_types(stdout);
1136                 goto clean_exit;
1137             }
1138             gchar **splitted = g_strsplit(optarg, ",", 2);
1139             if (splitted[0] && splitted[0][0] != '\0') {
1140                 secrets_type_id = lookup_secrets_type(splitted[0]);
1141                 if (secrets_type_id == 0) {
1142                     fprintf(stderr, "editcap: \"%s\" isn't a valid secrets type\n", splitted[0]);
1143                     g_strfreev(splitted);
1144                     ret = INVALID_OPTION;
1145                     goto clean_exit;
1146                 }
1147                 secrets_filename = splitted[1];
1148             } else {
1149                 fprintf(stderr, "editcap: no secrets type was specified for --inject-secrets\n");
1150                 g_strfreev(splitted);
1151                 ret = INVALID_OPTION;
1152                 goto clean_exit;
1153             }
1154             if (!dsb_filenames) {
1155                 dsb_types = g_array_new(FALSE, FALSE, sizeof(guint32));
1156                 dsb_filenames = g_ptr_array_new_with_free_func(g_free);
1157             }
1158             g_array_append_val(dsb_types, secrets_type_id);
1159             g_ptr_array_add(dsb_filenames, g_strdup(secrets_filename));
1160             g_strfreev(splitted);
1161             break;
1162         }
1163
1164         case LONGOPT_DISCARD_ALL_SECRETS:
1165         {
1166             discard_all_secrets = TRUE;
1167             break;
1168         }
1169
1170         case 'a':
1171         {
1172             guint frame_number;
1173             gint string_start_index = 0;
1174
1175             if ((sscanf(optarg, "%u:%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1176                 fprintf(stderr, "editcap: \"%s\" isn't a valid <frame>:<comment>\n\n",
1177                         optarg);
1178                 ret = INVALID_OPTION;
1179                 goto clean_exit;
1180             }
1181
1182             /* Lazily create the table */
1183             if (!frames_user_comments) {
1184                 frames_user_comments = g_tree_new_full(framenum_compare, NULL, NULL, g_free);
1185             }
1186
1187             /* Insert this entry (framenum -> comment) */
1188             g_tree_replace(frames_user_comments, GUINT_TO_POINTER(frame_number), g_strdup(optarg+string_start_index));
1189             break;
1190         }
1191
1192         case 'A':
1193         {
1194             struct tm starttm;
1195
1196             memset(&starttm,0,sizeof(struct tm));
1197
1198             if (!strptime(optarg,"%Y-%m-%d %T", &starttm)) {
1199                 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1200                         optarg);
1201                 ret = INVALID_OPTION;
1202                 goto clean_exit;
1203             }
1204
1205             check_startstop = TRUE;
1206             starttm.tm_isdst = -1;
1207
1208             starttime = mktime(&starttm);
1209             break;
1210         }
1211
1212         case 'B':
1213         {
1214             struct tm stoptm;
1215
1216             memset(&stoptm,0,sizeof(struct tm));
1217
1218             if (!strptime(optarg,"%Y-%m-%d %T", &stoptm)) {
1219                 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1220                         optarg);
1221                 ret = INVALID_OPTION;
1222                 goto clean_exit;
1223             }
1224             check_startstop = TRUE;
1225             stoptm.tm_isdst = -1;
1226             stoptime = mktime(&stoptm);
1227             break;
1228         }
1229
1230         case 'c':
1231             split_packet_count = get_nonzero_guint32(optarg, "packet count");
1232             break;
1233
1234         case 'C':
1235         {
1236             int choplen = 0, chopoff = 0;
1237
1238             switch (sscanf(optarg, "%d:%d", &chopoff, &choplen)) {
1239             case 1: /* only the chop length was specififed */
1240                 choplen = chopoff;
1241                 chopoff = 0;
1242                 break;
1243
1244             case 2: /* both an offset and chop length was specified */
1245                 break;
1246
1247             default:
1248                 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length or offset:length\n",
1249                         optarg);
1250                 ret = INVALID_OPTION;
1251                 goto clean_exit;
1252                 break;
1253             }
1254
1255             if (choplen > 0) {
1256                 chop.len_begin += choplen;
1257                 if (chopoff > 0)
1258                     chop.off_begin_pos += chopoff;
1259                 else
1260                     chop.off_begin_neg += chopoff;
1261             } else if (choplen < 0) {
1262                 chop.len_end += choplen;
1263                 if (chopoff > 0)
1264                     chop.off_end_pos += chopoff;
1265                 else
1266                     chop.off_end_neg += chopoff;
1267             }
1268             break;
1269         }
1270
1271         case 'd':
1272             dup_detect = TRUE;
1273             dup_detect_by_time = FALSE;
1274             dup_window = DEFAULT_DUP_DEPTH;
1275             break;
1276
1277         case 'D':
1278             dup_detect = TRUE;
1279             dup_detect_by_time = FALSE;
1280             dup_window = get_guint32(optarg, "duplicate window");
1281             if (dup_window > MAX_DUP_DEPTH) {
1282                 fprintf(stderr, "editcap: \"%d\" duplicate window value must be between 0 and %d inclusive.\n",
1283                         dup_window, MAX_DUP_DEPTH);
1284                 ret = INVALID_OPTION;
1285                 goto clean_exit;
1286             }
1287             break;
1288
1289         case 'E':
1290             err_prob = g_ascii_strtod(optarg, &p);
1291             if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
1292                 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
1293                         optarg);
1294                 ret = INVALID_OPTION;
1295                 goto clean_exit;
1296             }
1297             break;
1298
1299         case 'F':
1300             out_file_type_subtype = wtap_short_string_to_file_type_subtype(optarg);
1301             if (out_file_type_subtype < 0) {
1302                 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
1303                         optarg);
1304                 list_capture_types(stderr);
1305                 ret = INVALID_OPTION;
1306                 goto clean_exit;
1307             }
1308             break;
1309
1310         case 'h':
1311             show_help_header("Edit and/or translate the format of capture files.");
1312             print_usage(stdout);
1313             goto clean_exit;
1314             break;
1315
1316         case 'i': /* break capture file based on time interval */
1317         {
1318             double spb = get_positive_double(optarg, "time interval");
1319             if (spb == 0.0) {
1320               cmdarg_err("The specified interval is zero");
1321               ret = INVALID_OPTION;
1322               goto clean_exit;
1323             }
1324
1325             double spb_int, spb_frac;
1326             spb_frac = modf(spb, &spb_int);
1327             secs_per_block.secs = (time_t) spb_int;
1328             secs_per_block.nsecs = (int) (NANOSECS_PER_SEC * spb_frac);
1329         }
1330             break;
1331
1332         case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1333             ignored_bytes = get_guint32(optarg, "number of bytes to ignore");
1334             break;
1335
1336         case 'L':
1337             adjlen = TRUE;
1338             break;
1339
1340         case 'o':
1341             change_offset = get_guint32(optarg, "change offset");
1342             break;
1343
1344         case 'r':
1345             keep_em = !keep_em;  /* Just invert */
1346             break;
1347
1348         case 's':
1349             snaplen = get_nonzero_guint32(optarg, "snapshot length");
1350             break;
1351
1352         case 'S':
1353             if (!set_strict_time_adj(optarg)) {
1354                 ret = INVALID_OPTION;
1355                 goto clean_exit;
1356             }
1357             do_strict_time_adjustment = TRUE;
1358             break;
1359
1360         case 't':
1361             if (!set_time_adjustment(optarg)) {
1362                 ret = INVALID_OPTION;
1363                 goto clean_exit;
1364             }
1365             break;
1366
1367         case 'T':
1368             out_frame_type = wtap_name_to_encap(optarg);
1369             if (out_frame_type < 0) {
1370                 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
1371                         optarg);
1372                 list_encap_types(stderr);
1373                 ret = INVALID_OPTION;
1374                 goto clean_exit;
1375             }
1376             break;
1377
1378         case 'v':
1379             verbose = !verbose;  /* Just invert */
1380             break;
1381
1382         case 'V':
1383             show_version();
1384             goto clean_exit;
1385             break;
1386
1387         case 'w':
1388             dup_detect = FALSE;
1389             dup_detect_by_time = TRUE;
1390             dup_window = MAX_DUP_DEPTH;
1391             if (!set_rel_time(optarg)) {
1392                 ret = INVALID_OPTION;
1393                 goto clean_exit;
1394             }
1395             break;
1396
1397         case '?':              /* Bad options if GNU getopt */
1398         case ':':              /* missing option argument */
1399             switch(optopt) {
1400             case'F':
1401                 list_capture_types(stdout);
1402                 break;
1403             case'T':
1404                 list_encap_types(stdout);
1405                 break;
1406             default:
1407                 if (opt == '?') {
1408                     fprintf(stderr, "editcap: invalid option -- '%c'\n", optopt);
1409                 } else {
1410                     fprintf(stderr, "editcap: option requires an argument -- '%c'\n", optopt);
1411                 }
1412                 print_usage(stderr);
1413                 ret = INVALID_OPTION;
1414                 break;
1415             }
1416             goto clean_exit;
1417             break;
1418         }
1419     } /* processing commmand-line options */
1420
1421 #ifdef DEBUG
1422     fprintf(stderr, "Optind = %i, argc = %i\n", optind, argc);
1423 #endif
1424
1425     if ((argc - optind) < 2) {
1426         print_usage(stderr);
1427         ret = INVALID_OPTION;
1428         goto clean_exit;
1429
1430     }
1431
1432     if (err_prob >= 0.0) {
1433         if (!valid_seed) {
1434             seed = (unsigned int) (time(NULL) + ws_getpid());
1435         }
1436         if (verbose) {
1437             fprintf(stderr, "Using seed %u\n", seed);
1438         }
1439         srand(seed);
1440     }
1441
1442     if (check_startstop && !stoptime) {
1443         struct tm stoptm;
1444
1445         /* XXX: will work until 2035 */
1446         memset(&stoptm,0,sizeof(struct tm));
1447         stoptm.tm_year = 135;
1448         stoptm.tm_mday = 31;
1449         stoptm.tm_mon = 11;
1450         stoptm.tm_isdst = -1;
1451
1452         stoptime = mktime(&stoptm);
1453     }
1454
1455     if (starttime > stoptime) {
1456         fprintf(stderr, "editcap: start time is after the stop time\n");
1457         ret = INVALID_OPTION;
1458         goto clean_exit;
1459     }
1460
1461     if (split_packet_count != 0 && !nstime_is_unset(&secs_per_block)) {
1462         fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
1463         fprintf(stderr, "editcap: at the same time\n");
1464         ret = INVALID_OPTION;
1465         goto clean_exit;
1466     }
1467
1468     wth = wtap_open_offline(argv[optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, FALSE);
1469
1470     if (!wth) {
1471         cfile_open_failure_message("editcap", argv[optind], read_err,
1472                                    read_err_info);
1473         ret = INVALID_FILE;
1474         goto clean_exit;
1475     }
1476
1477     if (verbose) {
1478         fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
1479                 wtap_file_type_subtype_string(wtap_file_type_subtype(wth)));
1480     }
1481
1482     if (ignored_bytes != 0 && skip_radiotap == TRUE) {
1483         fprintf(stderr, "editcap: can't skip radiotap headers and %d byte(s)\n", ignored_bytes);
1484         fprintf(stderr, "editcap: at the start of packet at the same time\n");
1485         ret = INVALID_OPTION;
1486         goto clean_exit;
1487     }
1488
1489     if (skip_radiotap == TRUE && wtap_file_encap(wth) != WTAP_ENCAP_IEEE_802_11_RADIOTAP) {
1490         fprintf(stderr, "editcap: can't skip radiotap header because input file is incorrect\n");
1491         fprintf(stderr, "editcap: expected '%s', input is '%s'\n",
1492                 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP),
1493                 wtap_encap_description(wtap_file_type_subtype(wth)));
1494         ret = INVALID_OPTION;
1495         goto clean_exit;
1496     }
1497
1498     wtap_dump_params_init(&params, wth);
1499
1500     /*
1501      * Discard any secrets we read in while opening the file.
1502      */
1503     if (discard_all_secrets) {
1504         wtap_dump_params_discard_decryption_secrets(&params);
1505     }
1506
1507     if (dsb_filenames) {
1508         for (guint k = 0; k < dsb_filenames->len; k++) {
1509             guint32 secrets_type_id = g_array_index(dsb_types, guint32, k);
1510             const char *secrets_filename = (const char *)g_ptr_array_index(dsb_filenames, k);
1511             char *data;
1512             gsize data_len;
1513             wtap_block_t block;
1514             wtapng_dsb_mandatory_t *dsb;
1515             GError *err = NULL;
1516
1517             if (!g_file_get_contents(secrets_filename, &data, &data_len, &err)) {
1518                 fprintf(stderr, "editcap: \"%s\" could not be read: %s\n", secrets_filename, err->message);
1519                 g_clear_error(&err);
1520                 ret = INVALID_OPTION;
1521                 goto clean_exit;
1522             }
1523             if (data_len == 0) {
1524                 fprintf(stderr, "editcap: \"%s\" is an empty file, ignoring\n", secrets_filename);
1525                 g_free(data);
1526                 continue;
1527             }
1528             if (data_len >= G_MAXINT) {
1529                 fprintf(stderr, "editcap: \"%s\" is too large, ignoring\n", secrets_filename);
1530                 g_free(data);
1531                 continue;
1532             }
1533
1534             /* Warn for badly formatted files, but proceed anyway. */
1535             validate_secrets_file(secrets_filename, secrets_type_id, data);
1536
1537             block = wtap_block_create(WTAP_BLOCK_DSB);
1538             dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(block);
1539             dsb->secrets_type = secrets_type_id;
1540             dsb->secrets_len = (guint)data_len;
1541             dsb->secrets_data = data;
1542             if (params.dsbs_initial == NULL) {
1543                 params.dsbs_initial = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
1544             }
1545             g_array_append_val(params.dsbs_initial, block);
1546         }
1547     }
1548
1549     /*
1550      * If an encapsulation type was specified, override the encapsulation
1551      * type of the input file.
1552      */
1553     if (out_frame_type != -2)
1554         params.encap = out_frame_type;
1555
1556     /*
1557      * If a snapshot length was specified, and it's less than the snapshot
1558      * length of the input file, override the snapshot length of the input
1559      * file.
1560      */
1561     if (snaplen != 0 && snaplen < wtap_snapshot_length(wth))
1562         params.snaplen = snaplen;
1563
1564     /*
1565      * Now process the arguments following the input and output file
1566      * names, if any; they specify packets to include/exclude.
1567      */
1568     for (i = optind + 2; i < argc; i++)
1569         if (add_selection(argv[i], &max_packet_number) == FALSE)
1570             break;
1571
1572     if (keep_em == FALSE)
1573         max_packet_number = G_MAXUINT;
1574
1575     if (dup_detect || dup_detect_by_time) {
1576         for (i = 0; i < dup_window; i++) {
1577             memset(&fd_hash[i].digest, 0, 16);
1578             fd_hash[i].len = 0;
1579             nstime_set_unset(&fd_hash[i].frame_time);
1580         }
1581     }
1582
1583     /* Read all of the packets in turn */
1584     wtap_rec_init(&read_rec);
1585     ws_buffer_init(&read_buf, 1514);
1586     while (wtap_read(wth, &read_rec, &read_buf, &read_err, &read_err_info, &data_offset)) {
1587         if (max_packet_number <= read_count)
1588             break;
1589
1590         read_count++;
1591
1592         rec = &read_rec;
1593
1594         /* Extra actions for the first packet */
1595         if (read_count == 1) {
1596             if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
1597                 if (!fileset_extract_prefix_suffix(argv[optind+1], &fprefix, &fsuffix)) {
1598                     ret = CANT_EXTRACT_PREFIX;
1599                     goto clean_exit;
1600                 }
1601
1602                 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1603             } else {
1604                 filename = g_strdup(argv[optind+1]);
1605             }
1606             g_assert(filename);
1607
1608             /* If we don't have an application name add one */
1609             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) {
1610                 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
1611             }
1612
1613             pdh = editcap_dump_open(filename, &params, &write_err);
1614
1615             if (pdh == NULL) {
1616                 cfile_dump_open_failure_message("editcap", filename,
1617                                                 write_err,
1618                                                 out_file_type_subtype);
1619                 ret = INVALID_FILE;
1620                 goto clean_exit;
1621             }
1622         } /* first packet only handling */
1623
1624
1625         buf = ws_buffer_start_ptr(&read_buf);
1626
1627         /*
1628          * Not all packets have time stamps. Only process the time
1629          * stamp if we have one.
1630          */
1631         if (rec->presence_flags & WTAP_HAS_TS) {
1632             if (!nstime_is_unset(&secs_per_block)) {
1633                 if (nstime_is_unset(&block_next)) {
1634                     block_next = rec->ts;
1635                     nstime_add(&block_next, &secs_per_block);
1636                 }
1637                 while (nstime_cmp(&rec->ts, &block_next) > 0) { /* time for the next file */
1638
1639                     if (!wtap_dump_close(pdh, &write_err)) {
1640                         cfile_close_failure_message(filename, write_err);
1641                         ret = WRITE_ERROR;
1642                         goto clean_exit;
1643                     }
1644                     nstime_add(&block_next, &secs_per_block); /* reset for next interval */
1645                     g_free(filename);
1646                     filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1647                     g_assert(filename);
1648
1649                     if (verbose)
1650                         fprintf(stderr, "Continuing writing in file %s\n", filename);
1651
1652                     pdh = editcap_dump_open(filename, &params, &write_err);
1653
1654                     if (pdh == NULL) {
1655                         cfile_dump_open_failure_message("editcap", filename,
1656                                                         write_err,
1657                                                         out_file_type_subtype);
1658                         ret = INVALID_FILE;
1659                         goto clean_exit;
1660                     }
1661                 }
1662             }
1663         }  /* time stamp handling */
1664
1665         if (split_packet_count != 0) {
1666             /* time for the next file? */
1667             if (written_count > 0 && (written_count % split_packet_count) == 0) {
1668                 if (!wtap_dump_close(pdh, &write_err)) {
1669                     cfile_close_failure_message(filename, write_err);
1670                     ret = WRITE_ERROR;
1671                     goto clean_exit;
1672                 }
1673
1674                 g_free(filename);
1675                 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1676                 g_assert(filename);
1677
1678                 if (verbose)
1679                     fprintf(stderr, "Continuing writing in file %s\n", filename);
1680
1681                 pdh = editcap_dump_open(filename, &params, &write_err);
1682                 if (pdh == NULL) {
1683                     cfile_dump_open_failure_message("editcap", filename,
1684                                                     write_err,
1685                                                     out_file_type_subtype);
1686                     ret = INVALID_FILE;
1687                     goto clean_exit;
1688                 }
1689             }
1690         } /* split packet handling */
1691
1692         if (check_startstop) {
1693             /*
1694              * Is the packet in the selected timeframe?
1695              * If the packet has no time stamp, the answer is "no".
1696              */
1697             if (rec->presence_flags & WTAP_HAS_TS)
1698                 ts_okay = (rec->ts.secs >= starttime) && (rec->ts.secs < stoptime);
1699             else
1700                 ts_okay = FALSE;
1701         } else {
1702             /*
1703              * No selected timeframe, so all packets are "in the
1704              * selected timeframe".
1705              */
1706             ts_okay = TRUE;
1707         }
1708
1709         if (ts_okay && ((!selected(count) && !keep_em)
1710                         || (selected(count) && keep_em))) {
1711
1712             if (verbose && !dup_detect && !dup_detect_by_time)
1713                 fprintf(stderr, "Packet: %u\n", count);
1714
1715             /* We simply write it, perhaps after truncating it; we could
1716              * do other things, like modify it. */
1717
1718             rec = &read_rec;
1719
1720             if (rec->presence_flags & WTAP_HAS_TS) {
1721                 /* Do we adjust timestamps to ensure strict chronological
1722                  * order? */
1723                 if (do_strict_time_adjustment) {
1724                     if (previous_time.secs || previous_time.nsecs) {
1725                         if (!strict_time_adj.is_negative) {
1726                             nstime_t current;
1727                             nstime_t delta;
1728
1729                             current = rec->ts;
1730
1731                             nstime_delta(&delta, &current, &previous_time);
1732
1733                             if (delta.secs < 0 || delta.nsecs < 0) {
1734                                 /*
1735                                  * A negative delta indicates that the current packet
1736                                  * has an absolute timestamp less than the previous packet
1737                                  * that it is being compared to.  This is NOT a normal
1738                                  * situation since trace files usually have packets in
1739                                  * chronological order (oldest to newest).
1740                                  * Copy and change rather than modify
1741                                  * returned rec.
1742                                  */
1743                                 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
1744                                 temp_rec = *rec;
1745                                 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1746                                 temp_rec.ts.nsecs = previous_time.nsecs;
1747                                 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1748                                     /* carry */
1749                                     temp_rec.ts.secs++;
1750                                     temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1751                                 } else {
1752                                     temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1753                                 }
1754                                 rec = &temp_rec;
1755                             }
1756                         } else {
1757                             /*
1758                              * A negative strict time adjustment is requested.
1759                              * Unconditionally set each timestamp to previous
1760                              * packet's timestamp plus delta.
1761                              * Copy and change rather than modify returned
1762                              * rec.
1763                              */
1764                             temp_rec = *rec;
1765                             temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1766                             temp_rec.ts.nsecs = previous_time.nsecs;
1767                             if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1768                                 /* carry */
1769                                 temp_rec.ts.secs++;
1770                                 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1771                             } else {
1772                                 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1773                             }
1774                             rec = &temp_rec;
1775                         }
1776                     }
1777                     previous_time = rec->ts;
1778                 }
1779
1780                 if (time_adj.tv.secs != 0) {
1781                     /* Copy and change rather than modify returned rec */
1782                     temp_rec = *rec;
1783                     if (time_adj.is_negative)
1784                         temp_rec.ts.secs -= time_adj.tv.secs;
1785                     else
1786                         temp_rec.ts.secs += time_adj.tv.secs;
1787                     rec = &temp_rec;
1788                 }
1789
1790                 if (time_adj.tv.nsecs != 0) {
1791                     /* Copy and change rather than modify returned rec */
1792                     temp_rec = *rec;
1793                     if (time_adj.is_negative) { /* subtract */
1794                         if (temp_rec.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
1795                             temp_rec.ts.secs--;
1796                             temp_rec.ts.nsecs += ONE_BILLION;
1797                         }
1798                         temp_rec.ts.nsecs -= time_adj.tv.nsecs;
1799                     } else {                  /* add */
1800                         if (temp_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
1801                             /* carry */
1802                             temp_rec.ts.secs++;
1803                             temp_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
1804                         } else {
1805                             temp_rec.ts.nsecs += time_adj.tv.nsecs;
1806                         }
1807                     }
1808                     rec = &temp_rec;
1809                 }
1810             } /* time stamp adjustment */
1811
1812             if (rec->rec_type == REC_TYPE_PACKET) {
1813                 if (snaplen != 0) {
1814                     /* Limit capture length to snaplen */
1815                     if (rec->rec_header.packet_header.caplen > snaplen) {
1816                         /* Copy and change rather than modify returned wtap_rec */
1817                         temp_rec = *rec;
1818                         temp_rec.rec_header.packet_header.caplen = snaplen;
1819                         rec = &temp_rec;
1820                     }
1821                     /* If -L, also set reported length to snaplen */
1822                     if (adjlen && rec->rec_header.packet_header.len > snaplen) {
1823                         /* Copy and change rather than modify returned phdr */
1824                         temp_rec = *rec;
1825                         temp_rec.rec_header.packet_header.len = snaplen;
1826                         rec = &temp_rec;
1827                     }
1828                 }
1829
1830                 /*
1831                  * If an encapsulation type was specified, override the
1832                  * encapsulation type of the packet.
1833                  * Copy and change rather than modify returned rec.
1834                  */
1835                 if (out_frame_type != -2) {
1836                     temp_rec = *rec;
1837                     temp_rec.rec_header.packet_header.pkt_encap = out_frame_type;
1838                     rec = &temp_rec;
1839                 }
1840
1841                 /*
1842                  * CHOP
1843                  * Copy and change rather than modify returned rec.
1844                  */
1845                 temp_rec = *rec;
1846                 handle_chopping(chop, &temp_rec.rec_header.packet_header,
1847                                 &rec->rec_header.packet_header, &buf,
1848                                 adjlen);
1849                 rec = &temp_rec;
1850
1851                 /* remove vlan info */
1852                 if (rem_vlan) {
1853                     /* Copy and change rather than modify returned rec */
1854                     temp_rec = *rec;
1855                     remove_vlan_info(&rec->rec_header.packet_header, buf,
1856                                      &temp_rec.rec_header.packet_header.caplen);
1857                     rec = &temp_rec;
1858                 }
1859
1860                 /* suppress duplicates by packet window */
1861                 if (dup_detect) {
1862                     if (is_duplicate(buf, rec->rec_header.packet_header.caplen)) {
1863                         if (verbose) {
1864                             fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1865                                     count,
1866                                     rec->rec_header.packet_header.caplen);
1867                             for (i = 0; i < 16; i++)
1868                                 fprintf(stderr, "%02x",
1869                                         (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1870                             fprintf(stderr, "\n");
1871                         }
1872                         duplicate_count++;
1873                         count++;
1874                         continue;
1875                     } else {
1876                         if (verbose) {
1877                             fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1878                                     count,
1879                                     rec->rec_header.packet_header.caplen);
1880                             for (i = 0; i < 16; i++)
1881                                 fprintf(stderr, "%02x",
1882                                         (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1883                             fprintf(stderr, "\n");
1884                         }
1885                     }
1886                 } /* suppression of duplicates */
1887
1888                 if (rec->presence_flags & WTAP_HAS_TS) {
1889                     /* suppress duplicates by time window */
1890                     if (dup_detect_by_time) {
1891                         nstime_t current;
1892
1893                         current.secs  = rec->ts.secs;
1894                         current.nsecs = rec->ts.nsecs;
1895
1896                         if (is_duplicate_rel_time(buf,
1897                                                   rec->rec_header.packet_header.caplen,
1898                                                   &current)) {
1899                             if (verbose) {
1900                                 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1901                                         count,
1902                                         rec->rec_header.packet_header.caplen);
1903                                 for (i = 0; i < 16; i++)
1904                                     fprintf(stderr, "%02x",
1905                                             (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1906                                 fprintf(stderr, "\n");
1907                             }
1908                             duplicate_count++;
1909                             count++;
1910                             continue;
1911                         } else {
1912                             if (verbose) {
1913                                 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1914                                         count,
1915                                         rec->rec_header.packet_header.caplen);
1916                                 for (i = 0; i < 16; i++)
1917                                     fprintf(stderr, "%02x",
1918                                             (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1919                                 fprintf(stderr, "\n");
1920                             }
1921                         }
1922                     }
1923                 } /* suppress duplicates by time window */
1924             }
1925
1926             /* Random error mutation */
1927             do_mutation = FALSE;
1928             caplen = 0;
1929             if (err_prob > 0.0) {
1930                 switch (rec->rec_type) {
1931
1932                 case REC_TYPE_PACKET:
1933                     caplen = rec->rec_header.packet_header.caplen;
1934                     do_mutation = TRUE;
1935                     break;
1936
1937                 case REC_TYPE_FT_SPECIFIC_EVENT:
1938                 case REC_TYPE_FT_SPECIFIC_REPORT:
1939                     caplen = rec->rec_header.ft_specific_header.record_len;
1940                     do_mutation = TRUE;
1941                     break;
1942
1943                 case REC_TYPE_SYSCALL:
1944                     caplen = rec->rec_header.syscall_header.event_filelen;
1945                     do_mutation = TRUE;
1946                     break;
1947                 }
1948
1949                 if (change_offset > caplen) {
1950                     fprintf(stderr, "change offset %u is longer than caplen %u in packet %u\n",
1951                         change_offset, caplen, count);
1952                     do_mutation = FALSE;
1953                 }
1954             }
1955
1956             if (do_mutation) {
1957                 int real_data_start = 0;
1958
1959                 /* Protect non-protocol data */
1960                 switch (rec->rec_type) {
1961
1962                 case REC_TYPE_PACKET:
1963                     if (wtap_file_type_subtype(wth) == WTAP_FILE_TYPE_SUBTYPE_CATAPULT_DCT2000)
1964                         real_data_start = find_dct2000_real_data(buf);
1965                     break;
1966                 }
1967
1968                 real_data_start += change_offset;
1969
1970                 for (i = real_data_start; i < (int) caplen; i++) {
1971                     if (rand() <= err_prob * RAND_MAX) {
1972                         err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
1973
1974                         if (err_type < ERR_WT_BIT) {
1975                             buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
1976                             err_type = ERR_WT_TOTAL;
1977                         } else {
1978                             err_type -= ERR_WT_BYTE;
1979                         }
1980
1981                         if (err_type < ERR_WT_BYTE) {
1982                             buf[i] = rand() / (RAND_MAX / 255 + 1);
1983                             err_type = ERR_WT_TOTAL;
1984                         } else {
1985                             err_type -= ERR_WT_BYTE;
1986                         }
1987
1988                         if (err_type < ERR_WT_ALNUM) {
1989                             buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
1990                             err_type = ERR_WT_TOTAL;
1991                         } else {
1992                             err_type -= ERR_WT_ALNUM;
1993                         }
1994
1995                         if (err_type < ERR_WT_FMT) {
1996                             if ((unsigned int)i < caplen - 2)
1997                                 g_strlcpy((char*) &buf[i], "%s", 2);
1998                             err_type = ERR_WT_TOTAL;
1999                         } else {
2000                             err_type -= ERR_WT_FMT;
2001                         }
2002
2003                         if (err_type < ERR_WT_AA) {
2004                             for (j = i; j < (int) caplen; j++)
2005                                 buf[j] = 0xAA;
2006                             i = caplen;
2007                         }
2008                     }
2009                 }
2010             } /* random error mutation */
2011
2012             /* Find a packet comment we may need to write */
2013             if (frames_user_comments) {
2014                 const char *comment =
2015                     (const char*)g_tree_lookup(frames_user_comments, GUINT_TO_POINTER(read_count));
2016                 /* XXX: What about comment changed to no comment? */
2017                 if (comment != NULL) {
2018                     /* Copy and change rather than modify returned rec */
2019                     temp_rec = *rec;
2020                     /* The comment is not modified by dumper, cast away. */
2021                     temp_rec.opt_comment = (char *)comment;
2022                     temp_rec.has_comment_changed = TRUE;
2023                     rec = &temp_rec;
2024                 } else {
2025                     /* Copy and change rather than modify returned rec */
2026                     temp_rec = *rec;
2027                     temp_rec.has_comment_changed = FALSE;
2028                     rec = &temp_rec;
2029                 }
2030             }
2031
2032             if (discard_all_secrets) {
2033                 /*
2034                  * Discard any secrets we've read since the last packet
2035                  * we wrote.
2036                  */
2037                 wtap_dump_discard_decryption_secrets(pdh);
2038             }
2039
2040             /* Attempt to dump out current frame to the output file */
2041             if (!wtap_dump(pdh, rec, buf, &write_err, &write_err_info)) {
2042                 cfile_write_failure_message("editcap", argv[optind],
2043                                             filename,
2044                                             write_err, write_err_info,
2045                                             read_count,
2046                                             out_file_type_subtype);
2047                 ret = DUMP_ERROR;
2048                 goto clean_exit;
2049             }
2050             written_count++;
2051         }
2052         count++;
2053     }
2054     wtap_rec_cleanup(&read_rec);
2055     ws_buffer_free(&read_buf);
2056
2057     g_free(fprefix);
2058     g_free(fsuffix);
2059
2060     if (read_err != 0) {
2061         /* Print a message noting that the read failed somewhere along the
2062          * line. */
2063         cfile_read_failure_message("editcap", argv[optind], read_err,
2064                                    read_err_info);
2065     }
2066
2067     if (!pdh) {
2068         /* No valid packages found, open the outfile so we can write an
2069          * empty header */
2070         g_free (filename);
2071         filename = g_strdup(argv[optind+1]);
2072
2073         pdh = editcap_dump_open(filename, &params, &write_err);
2074         if (pdh == NULL) {
2075             cfile_dump_open_failure_message("editcap", filename,
2076                                             write_err,
2077                                             out_file_type_subtype);
2078             ret = INVALID_FILE;
2079             goto clean_exit;
2080         }
2081     }
2082
2083     if (!wtap_dump_close(pdh, &write_err)) {
2084         cfile_close_failure_message(filename, write_err);
2085         ret = WRITE_ERROR;
2086         goto clean_exit;
2087     }
2088     g_free(filename);
2089
2090     if (frames_user_comments) {
2091         g_tree_destroy(frames_user_comments);
2092     }
2093
2094     if (dup_detect) {
2095         fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate window of %i packets.\n",
2096                 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2097                 plurality(duplicate_count, "", "s"), dup_window);
2098     } else if (dup_detect_by_time) {
2099         fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2100                 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2101                 plurality(duplicate_count, "", "s"),
2102                 (long)relative_time_window.secs,
2103                 (long int)relative_time_window.nsecs);
2104     }
2105
2106 clean_exit:
2107     if (dsb_filenames) {
2108         g_array_free(dsb_types, TRUE);
2109         g_ptr_array_free(dsb_filenames, TRUE);
2110     }
2111     g_free(params.idb_inf);
2112     wtap_dump_params_cleanup(&params);
2113     if (wth != NULL)
2114         wtap_close(wth);
2115     wtap_cleanup();
2116     free_progdirs();
2117     return ret;
2118 }
2119
2120 /* Skip meta-information read from file to return offset of real
2121  * protocol data */
2122 static int
2123 find_dct2000_real_data(guint8 *buf)
2124 {
2125     int n = 0;
2126
2127     for (n = 0; buf[n] != '\0'; n++);   /* Context name */
2128     n++;
2129     n++;                                /* Context port number */
2130     for (; buf[n] != '\0'; n++);        /* Timestamp */
2131     n++;
2132     for (; buf[n] != '\0'; n++);        /* Protocol name */
2133     n++;
2134     for (; buf[n] != '\0'; n++);        /* Variant number (as string) */
2135     n++;
2136     for (; buf[n] != '\0'; n++);        /* Outhdr (as string) */
2137     n++;
2138     n += 2;                             /* Direction & encap */
2139
2140     return n;
2141 }
2142
2143 /*
2144  * We support up to 2 chopping regions in a single pass: one specified by the
2145  * positive chop length, and one by the negative chop length.
2146  */
2147 static void
2148 handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
2149                 const wtap_packet_header *in_phdr, guint8 **buf,
2150                 gboolean adjlen)
2151 {
2152     /* If we're not chopping anything from one side, then the offset for that
2153      * side is meaningless. */
2154     if (chop.len_begin == 0)
2155         chop.off_begin_pos = chop.off_begin_neg = 0;
2156     if (chop.len_end == 0)
2157         chop.off_end_pos = chop.off_end_neg = 0;
2158
2159     if (chop.off_begin_neg < 0) {
2160         chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
2161         chop.off_begin_neg = 0;
2162     }
2163     if (chop.off_end_pos > 0) {
2164         chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
2165         chop.off_end_pos = 0;
2166     }
2167
2168     /* If we've crossed chopping regions, swap them */
2169     if (chop.len_begin && chop.len_end) {
2170         if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
2171             int tmp_len, tmp_off;
2172
2173             tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
2174             tmp_len = -chop.len_end;
2175
2176             chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
2177             chop.len_end = -chop.len_begin;
2178
2179             chop.len_begin = tmp_len;
2180             chop.off_begin_pos = tmp_off;
2181         }
2182     }
2183
2184     /* Make sure we don't chop off more than we have available */
2185     if (in_phdr->caplen < (guint32)(chop.off_begin_pos - chop.off_end_neg)) {
2186         chop.len_begin = 0;
2187         chop.len_end = 0;
2188     }
2189     if ((guint32)(chop.len_begin - chop.len_end) >
2190         (in_phdr->caplen - (guint32)(chop.off_begin_pos - chop.off_end_neg))) {
2191         chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
2192         chop.len_end = 0;
2193     }
2194
2195     /* Handle chopping from the beginning.  Note that if a beginning offset
2196      * was specified, we need to keep that piece */
2197     if (chop.len_begin > 0) {
2198         *out_phdr = *in_phdr;
2199
2200         if (chop.off_begin_pos > 0) {
2201             memmove(*buf + chop.off_begin_pos,
2202                     *buf + chop.off_begin_pos + chop.len_begin,
2203                     out_phdr->caplen - chop.len_begin);
2204         } else {
2205             *buf += chop.len_begin;
2206         }
2207         out_phdr->caplen -= chop.len_begin;
2208
2209         if (adjlen) {
2210             if (in_phdr->len > (guint32)chop.len_begin)
2211                 out_phdr->len -= chop.len_begin;
2212             else
2213                 out_phdr->len = 0;
2214         }
2215         in_phdr = out_phdr;
2216     }
2217
2218     /* Handle chopping from the end.  Note that if an ending offset was
2219      * specified, we need to keep that piece */
2220     if (chop.len_end < 0) {
2221         *out_phdr = *in_phdr;
2222
2223         if (chop.off_end_neg < 0) {
2224             memmove(*buf + (gint)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2225                     *buf + (gint)out_phdr->caplen + chop.off_end_neg,
2226                     -chop.off_end_neg);
2227         }
2228         out_phdr->caplen += chop.len_end;
2229
2230         if (adjlen) {
2231             if (((signed int) in_phdr->len + chop.len_end) > 0)
2232                 out_phdr->len += chop.len_end;
2233             else
2234                 out_phdr->len = 0;
2235         }
2236         /*in_phdr = out_phdr;*/
2237     }
2238 }
2239
2240 /*
2241  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
2242  *
2243  * Local variables:
2244  * c-basic-offset: 4
2245  * tab-width: 8
2246  * indent-tabs-mode: nil
2247  * End:
2248  *
2249  * vi: set shiftwidth=4 tabstop=8 expandtab:
2250  * :indentSize=4:tabSize=8:noTabs=true:
2251  */