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