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