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