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