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