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