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