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