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