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