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