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