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