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