2 * Edit capture files. We can delete packets, adjust timestamps, or
3 * simply convert from one format to another format.
5 * Originally written by Richard Sharpe.
6 * Improved by Guy Harris.
7 * Further improved by Richard Sharpe.
9 * Copyright 2013, Richard Sharpe <realrichardsharpe[AT]gmail.com>
11 * Wireshark - Network traffic analyzer
12 * By Gerald Combs <gerald@wireshark.org>
13 * Copyright 1998 Gerald Combs
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 2 of the License, or
18 * (at your option) any later version.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License along
26 * with this program; if not, write to the Free Software Foundation, Inc.,
27 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
38 * Just make sure we include the prototype for strptime as well
39 * (needed for glibc 2.2) but make sure we do this only if not
58 #include <wiretap/wtap.h>
60 #include "epan/etypes.h"
62 #ifndef HAVE_GETOPT_LONG
63 #include "wsutil/wsgetopt.h"
67 #include <wsutil/unicode-utils.h>
68 #include <process.h> /* getpid */
69 #ifdef HAVE_WINSOCK2_H
75 # include "wsutil/strptime.h"
78 #include <wsutil/crash_info.h>
79 #include <wsutil/clopts_common.h>
80 #include <wsutil/cmdarg_err.h>
81 #include <wsutil/filesystem.h>
82 #include <wsutil/file_util.h>
83 #include <wsutil/wsgcrypt.h>
84 #include <wsutil/plugins.h>
85 #include <wsutil/privileges.h>
86 #include <wsutil/report_err.h>
87 #include <wsutil/strnatcmp.h>
88 #include <wsutil/str_util.h>
89 #include <ws_version_info.h>
90 #include <wsutil/pint.h>
91 #include <wsutil/strtoi.h>
92 #include <wiretap/wtap_opttypes.h>
93 #include <wiretap/pcapng.h>
95 #include "ringbuffer.h" /* For RINGBUFFER_MAX_NUM_FILES */
97 #define INVALID_OPTION 1
98 #define INVALID_FILE 2
99 #define CANT_EXTRACT_PREFIX 2
100 #define WRITE_ERROR 2
104 * Some globals so we can pass things to various routines
113 * Duplicate frame detection
115 typedef struct _fd_hash_t {
121 #define DEFAULT_DUP_DEPTH 5 /* Used with -d */
122 #define MAX_DUP_DEPTH 1000000 /* the maximum window (and actual size of fd_hash[]) for de-duplication */
124 static fd_hash_t fd_hash[MAX_DUP_DEPTH];
125 static int dup_window = DEFAULT_DUP_DEPTH;
126 static int cur_dup_entry = 0;
128 static guint32 ignored_bytes = 0; /* Used with -I */
130 #define ONE_BILLION 1000000000
132 /* Weights of different errors we can introduce */
133 /* We should probably make these command-line arguments */
134 /* XXX - Should we add a bit-level error? */
135 #define ERR_WT_BIT 5 /* Flip a random bit */
136 #define ERR_WT_BYTE 5 /* Substitute a random byte */
137 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
138 #define ERR_WT_FMT 2 /* Substitute "%s" */
139 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
140 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
142 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
143 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
145 struct time_adjustment {
150 typedef struct _chop_t {
160 /* Table of user comments */
161 GTree *frames_user_comments = NULL;
163 #define MAX_SELECTIONS 512
164 static struct select_item selectfrm[MAX_SELECTIONS];
165 static guint max_selected = 0;
166 static int keep_em = 0;
167 #ifdef PCAP_NG_DEFAULT
168 static int out_file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcapng */
170 static int out_file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcap */
172 static int out_frame_type = -2; /* Leave frame type alone */
173 static int verbose = 0; /* Not so verbose */
174 static struct time_adjustment time_adj = {{0, 0}, 0}; /* no adjustment */
175 static nstime_t relative_time_window = {0, 0}; /* de-dup time window */
176 static double err_prob = 0.0;
177 static time_t starttime = 0;
178 static time_t stoptime = 0;
179 static gboolean check_startstop = FALSE;
180 static gboolean rem_vlan = FALSE;
181 static gboolean dup_detect = FALSE;
182 static gboolean dup_detect_by_time = FALSE;
184 static int do_strict_time_adjustment = FALSE;
185 static struct time_adjustment strict_time_adj = {{0, 0}, 0}; /* strict time adjustment */
186 static nstime_t previous_time = {0, 0}; /* previous time */
188 static int find_dct2000_real_data(guint8 *buf);
189 static void handle_chopping(chop_t chop, struct wtap_pkthdr *out_phdr,
190 const struct wtap_pkthdr *in_phdr, guint8 **buf,
194 abs_time_to_str_with_sec_resolution(const nstime_t *abs_time)
197 gchar *buf = (gchar *)g_malloc(16);
199 tmp = localtime(&abs_time->secs);
202 g_snprintf(buf, 16, "%d%02d%02d%02d%02d%02d",
217 fileset_get_filename_by_pattern(guint idx, const struct wtap_pkthdr *phdr,
218 gchar *fprefix, gchar *fsuffix)
224 g_snprintf(filenum, sizeof(filenum), "%05u", idx % RINGBUFFER_MAX_NUM_FILES);
225 if (phdr->presence_flags & WTAP_HAS_TS) {
226 timestr = abs_time_to_str_with_sec_resolution(&phdr->ts);
227 abs_str = g_strconcat(fprefix, "_", filenum, "_", timestr, fsuffix, NULL);
230 abs_str = g_strconcat(fprefix, "_", filenum, fsuffix, NULL);
236 fileset_extract_prefix_suffix(const char *fname, gchar **fprefix, gchar **fsuffix)
238 char *pfx, *last_pathsep;
241 save_file = g_strdup(fname);
242 if (save_file == NULL) {
243 fprintf(stderr, "editcap: Out of memory\n");
247 last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
248 pfx = strrchr(save_file,'.');
249 if (pfx != NULL && (last_pathsep == NULL || pfx > last_pathsep)) {
250 /* The pathname has a "." in it, and it's in the last component
251 * of the pathname (because there is either only one component,
252 * i.e. last_pathsep is null as there are no path separators,
253 * or the "." is after the path separator before the last
256 * Treat it as a separator between the rest of the file name and
257 * the file name suffix, and arrange that the names given to the
258 * ring buffer files have the specified suffix, i.e. put the
259 * changing part of the name *before* the suffix. */
261 *fprefix = g_strdup(save_file);
262 pfx[0] = '.'; /* restore capfile_name */
263 *fsuffix = g_strdup(pfx);
265 /* Either there's no "." in the pathname, or it's in a directory
266 * component, so the last component has no suffix. */
267 *fprefix = g_strdup(save_file);
274 /* Add a selection item, a simple parser for now */
276 add_selection(char *sel, guint* max_selection)
281 if (max_selected >= MAX_SELECTIONS) {
282 /* Let the user know we stopped selecting */
283 fprintf(stderr, "Out of room for packet selections.\n");
288 fprintf(stderr, "Add_Selected: %s\n", sel);
290 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
292 fprintf(stderr, "Not inclusive ...");
294 selectfrm[max_selected].inclusive = FALSE;
295 selectfrm[max_selected].first = get_guint32(sel, "packet number");
296 if (selectfrm[max_selected].first > *max_selection)
297 *max_selection = selectfrm[max_selected].first;
300 fprintf(stderr, " %u\n", selectfrm[max_selected].first);
303 fprintf(stderr, "Inclusive ...");
306 selectfrm[max_selected].inclusive = TRUE;
307 selectfrm[max_selected].first = get_guint32(sel, "beginning of packet range");
308 selectfrm[max_selected].second = get_guint32(next, "end of packet range");
310 if (selectfrm[max_selected].second == 0)
312 /* Not a valid number, presume all */
313 selectfrm[max_selected].second = *max_selection = G_MAXUINT;
315 else if (selectfrm[max_selected].second > *max_selection)
316 *max_selection = selectfrm[max_selected].second;
319 fprintf(stderr, " %u, %u\n", selectfrm[max_selected].first,
320 selectfrm[max_selected].second);
327 /* Was the packet selected? */
330 selected(guint recno)
334 for (i = 0; i < max_selected; i++) {
335 if (selectfrm[i].inclusive) {
336 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
339 if (recno == selectfrm[i].first)
348 set_time_adjustment(char *optarg_str_p)
357 /* skip leading whitespace */
358 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
361 /* check for a negative adjustment */
362 if (*optarg_str_p == '-') {
363 time_adj.is_negative = 1;
367 /* collect whole number of seconds, if any */
368 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
372 val = strtol(optarg_str_p, &frac, 10);
373 if (frac == NULL || frac == optarg_str_p
374 || val == LONG_MIN || val == LONG_MAX) {
375 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
379 if (val < 0) { /* implies '--' since we caught '-' above */
380 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
385 time_adj.tv.secs = val;
387 /* now collect the partial seconds, if any */
388 if (*frac != '\0') { /* chars left, so get fractional part */
389 val = strtol(&(frac[1]), &end, 10);
390 /* if more than 9 fractional digits truncate to 9 */
391 if ((end - &(frac[1])) > 9) {
392 frac[10] = 't'; /* 't' for truncate */
393 val = strtol(&(frac[1]), &end, 10);
395 if (*frac != '.' || end == NULL || end == frac || val < 0
396 || val > ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
397 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
402 return TRUE; /* no fractional digits */
405 /* adjust fractional portion from fractional to numerator
406 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
407 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
408 while(frac_digits < 9) { /* this is frac of 10^9 */
413 time_adj.tv.nsecs = (int)val;
418 set_strict_time_adj(char *optarg_str_p)
427 /* skip leading whitespace */
428 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
432 * check for a negative adjustment
433 * A negative strict adjustment value is a flag
434 * to adjust all frames by the specifed delta time.
436 if (*optarg_str_p == '-') {
437 strict_time_adj.is_negative = 1;
441 /* collect whole number of seconds, if any */
442 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
446 val = strtol(optarg_str_p, &frac, 10);
447 if (frac == NULL || frac == optarg_str_p
448 || val == LONG_MIN || val == LONG_MAX) {
449 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
453 if (val < 0) { /* implies '--' since we caught '-' above */
454 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
459 strict_time_adj.tv.secs = val;
461 /* now collect the partial seconds, if any */
462 if (*frac != '\0') { /* chars left, so get fractional part */
463 val = strtol(&(frac[1]), &end, 10);
464 /* if more than 9 fractional digits truncate to 9 */
465 if ((end - &(frac[1])) > 9) {
466 frac[10] = 't'; /* 't' for truncate */
467 val = strtol(&(frac[1]), &end, 10);
469 if (*frac != '.' || end == NULL || end == frac || val < 0
470 || val > ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
471 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
476 return TRUE; /* no fractional digits */
479 /* adjust fractional portion from fractional to numerator
480 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
481 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
482 while(frac_digits < 9) { /* this is frac of 10^9 */
487 strict_time_adj.tv.nsecs = (int)val;
492 set_rel_time(char *optarg_str_p)
501 /* skip leading whitespace */
502 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
505 /* ignore negative adjustment */
506 if (*optarg_str_p == '-')
509 /* collect whole number of seconds, if any */
510 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
514 val = strtol(optarg_str_p, &frac, 10);
515 if (frac == NULL || frac == optarg_str_p
516 || val == LONG_MIN || val == LONG_MAX) {
517 fprintf(stderr, "1: editcap: \"%s\" isn't a valid rel time value\n",
521 if (val < 0) { /* implies '--' since we caught '-' above */
522 fprintf(stderr, "2: editcap: \"%s\" isn't a valid rel time value\n",
527 relative_time_window.secs = val;
529 /* now collect the partial seconds, if any */
530 if (*frac != '\0') { /* chars left, so get fractional part */
531 val = strtol(&(frac[1]), &end, 10);
532 /* if more than 9 fractional digits truncate to 9 */
533 if ((end - &(frac[1])) > 9) {
534 frac[10] = 't'; /* 't' for truncate */
535 val = strtol(&(frac[1]), &end, 10);
537 if (*frac != '.' || end == NULL || end == frac || val < 0
538 || val > ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
539 fprintf(stderr, "3: editcap: \"%s\" isn't a valid rel time value\n",
544 return TRUE; /* no fractional digits */
547 /* adjust fractional portion from fractional to numerator
548 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
549 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
550 while(frac_digits < 9) { /* this is frac of 10^9 */
555 relative_time_window.nsecs = (int)val;
559 #define LINUX_SLL_OFFSETP 14
562 sll_remove_vlan_info(guint8* fd, guint32* len) {
563 if (pntoh16(fd + LINUX_SLL_OFFSETP) == ETHERTYPE_VLAN) {
565 /* point to start of vlan */
566 fd = fd + LINUX_SLL_OFFSETP;
567 /* bytes to read after vlan info */
568 rest_len = *len - (LINUX_SLL_OFFSETP + VLAN_SIZE);
569 /* remove vlan info from packet */
570 memmove(fd, fd + VLAN_SIZE, rest_len);
576 remove_vlan_info(const struct wtap_pkthdr *phdr, guint8* fd, guint32* len) {
577 switch (phdr->pkt_encap) {
579 sll_remove_vlan_info(fd, len);
582 /* no support for current pkt_encap */
588 is_duplicate(guint8* fd, guint32 len) {
591 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
592 guint32 offset = ignored_bytes;
596 if (len <= ignored_bytes) {
600 new_fd = &fd[offset];
601 new_len = len - (offset);
604 if (cur_dup_entry >= dup_window)
607 /* Calculate our digest */
608 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
610 fd_hash[cur_dup_entry].len = len;
612 /* Look for duplicates */
613 for (i = 0; i < dup_window; i++) {
614 if (i == cur_dup_entry)
617 if (fd_hash[i].len == fd_hash[cur_dup_entry].len
618 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
627 is_duplicate_rel_time(guint8* fd, guint32 len, const nstime_t *current) {
630 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
631 guint32 offset = ignored_bytes;
635 if (len <= ignored_bytes) {
639 new_fd = &fd[offset];
640 new_len = len - (offset);
643 if (cur_dup_entry >= dup_window)
646 /* Calculate our digest */
647 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
649 fd_hash[cur_dup_entry].len = len;
650 fd_hash[cur_dup_entry].frame_time.secs = current->secs;
651 fd_hash[cur_dup_entry].frame_time.nsecs = current->nsecs;
654 * Look for relative time related duplicates.
655 * This is hopefully a reasonably efficient mechanism for
656 * finding duplicates by rel time in the fd_hash[] cache.
657 * We check starting from the most recently added hash
658 * entries and work backwards towards older packets.
659 * This approach allows the dup test to be terminated
660 * when the relative time of a cached entry is found to
661 * be beyond the dup time window.
663 * Of course this assumes that the input trace file is
664 * "well-formed" in the sense that the packet timestamps are
665 * in strict chronologically increasing order (which is NOT
666 * always the case!!).
668 * The fd_hash[] table was deliberately created large (1,000,000).
669 * Looking for time related duplicates in large trace files with
670 * non-fractional dup time window values can potentially take
671 * a long time to complete.
674 for (i = cur_dup_entry - 1;; i--) {
681 if (i == cur_dup_entry) {
683 * We've decremented back to where we started.
689 if (nstime_is_unset(&(fd_hash[i].frame_time))) {
691 * We've decremented to an unused fd_hash[] entry.
697 nstime_delta(&delta, current, &fd_hash[i].frame_time);
699 if (delta.secs < 0 || delta.nsecs < 0) {
701 * A negative delta implies that the current packet
702 * has an absolute timestamp less than the cached packet
703 * that it is being compared to. This is NOT a normal
704 * situation since trace files usually have packets in
705 * chronological order (oldest to newest).
707 * There are several possible ways to deal with this:
708 * 1. 'continue' dup checking with the next cached frame.
709 * 2. 'break' from looking for a duplicate of the current frame.
710 * 3. Take the absolute value of the delta and see if that
711 * falls within the specifed dup time window.
713 * Currently this code does option 1. But it would pretty
714 * easy to add yet-another-editcap-option to select one of
715 * the other behaviors for dealing with out-of-sequence
721 cmp = nstime_cmp(&delta, &relative_time_window);
725 * The delta time indicates that we are now looking at
726 * cached packets beyond the specified dup time window.
730 } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len
731 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
740 print_usage(FILE *output)
742 fprintf(output, "\n");
743 fprintf(output, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
744 fprintf(output, "\n");
745 fprintf(output, "<infile> and <outfile> must both be present.\n");
746 fprintf(output, "A single packet or a range of packets can be selected.\n");
747 fprintf(output, "\n");
748 fprintf(output, "Packet selection:\n");
749 fprintf(output, " -r keep the selected packets; default is to delete them.\n");
750 fprintf(output, " -A <start time> only output packets whose timestamp is after (or equal\n");
751 fprintf(output, " to) the given time (format as YYYY-MM-DD hh:mm:ss).\n");
752 fprintf(output, " -B <stop time> only output packets whose timestamp is before the\n");
753 fprintf(output, " given time (format as YYYY-MM-DD hh:mm:ss).\n");
754 fprintf(output, "\n");
755 fprintf(output, "Duplicate packet removal:\n");
756 fprintf(output, " --novlan remove vlan info from packets before checking for duplicates.\n");
757 fprintf(output, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH);
758 fprintf(output, " -D <dup window> remove packet if duplicate; configurable <dup window>.\n");
759 fprintf(output, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH);
760 fprintf(output, " NOTE: A <dup window> of 0 with -v (verbose option) is\n");
761 fprintf(output, " useful to print MD5 hashes.\n");
762 fprintf(output, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
763 fprintf(output, " LESS THAN <dup time window> prior to current packet.\n");
764 fprintf(output, " A <dup time window> is specified in relative seconds\n");
765 fprintf(output, " (e.g. 0.000001).\n");
766 fprintf(output, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
767 fprintf(output, "\n");
768 fprintf(output, " -I <bytes to ignore> ignore the specified number of bytes at the beginning\n");
769 fprintf(output, " of the frame during MD5 hash calculation, unless the\n");
770 fprintf(output, " frame is too short, then the full frame is used.\n");
771 fprintf(output, " Useful to remove duplicated packets taken on\n");
772 fprintf(output, " several routers (different mac addresses for\n");
773 fprintf(output, " example).\n");
774 fprintf(output, " e.g. -I 26 in case of Ether/IP will ignore\n");
775 fprintf(output, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
776 fprintf(output, "\n");
777 fprintf(output, " NOTE: The use of the 'Duplicate packet removal' options with\n");
778 fprintf(output, " other editcap options except -v may not always work as expected.\n");
779 fprintf(output, " Specifically the -r, -t or -S options will very likely NOT have the\n");
780 fprintf(output, " desired effect if combined with the -d, -D or -w.\n");
781 fprintf(output, "\n");
782 fprintf(output, "Packet manipulation:\n");
783 fprintf(output, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
784 fprintf(output, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
785 fprintf(output, " chop at the packet beginning, negative values at the\n");
786 fprintf(output, " packet end. If an optional offset precedes the length,\n");
787 fprintf(output, " then the bytes chopped will be offset from that value.\n");
788 fprintf(output, " Positive offsets are from the packet beginning,\n");
789 fprintf(output, " negative offsets are from the packet end. You can use\n");
790 fprintf(output, " this option more than once, allowing up to 2 chopping\n");
791 fprintf(output, " regions within a packet provided that at least 1\n");
792 fprintf(output, " choplen is positive and at least 1 is negative.\n");
793 fprintf(output, " -L adjust the frame (i.e. reported) length when chopping\n");
794 fprintf(output, " and/or snapping.\n");
795 fprintf(output, " -t <time adjustment> adjust the timestamp of each packet.\n");
796 fprintf(output, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
797 fprintf(output, " -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
798 fprintf(output, " strict chronological increasing order. The <strict\n");
799 fprintf(output, " adjustment> is specified in relative seconds with\n");
800 fprintf(output, " values of 0 or 0.000001 being the most reasonable.\n");
801 fprintf(output, " A negative adjustment value will modify timestamps so\n");
802 fprintf(output, " that each packet's delta time is the absolute value\n");
803 fprintf(output, " of the adjustment specified. A value of -0 will set\n");
804 fprintf(output, " all packets to the timestamp of the first packet.\n");
805 fprintf(output, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
806 fprintf(output, " a particular packet byte will be randomly changed.\n");
807 fprintf(output, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
808 fprintf(output, " beginning of the packet. This allows one to preserve some\n");
809 fprintf(output, " bytes, in order to have some headers untouched.\n");
810 fprintf(output, "\n");
811 fprintf(output, "Output File(s):\n");
812 fprintf(output, " -c <packets per file> split the packet output to different files based on\n");
813 fprintf(output, " uniform packet counts with a maximum of\n");
814 fprintf(output, " <packets per file> each.\n");
815 fprintf(output, " -i <seconds per file> split the packet output to different files based on\n");
816 fprintf(output, " uniform time intervals with a maximum of\n");
817 fprintf(output, " <seconds per file> each.\n");
818 fprintf(output, " -F <capture type> set the output file type; default is pcapng. An empty\n");
819 fprintf(output, " \"-F\" option will list the file types.\n");
820 fprintf(output, " -T <encap type> set the output file encapsulation type; default is the\n");
821 fprintf(output, " same as the input file. An empty \"-T\" option will\n");
822 fprintf(output, " list the encapsulation types.\n");
823 fprintf(output, "\n");
824 fprintf(output, "Miscellaneous:\n");
825 fprintf(output, " -h display this help and exit.\n");
826 fprintf(output, " -v verbose output.\n");
827 fprintf(output, " If -v is used with any of the 'Duplicate Packet\n");
828 fprintf(output, " Removal' options (-d, -D or -w) then Packet lengths\n");
829 fprintf(output, " and MD5 hashes are printed to standard-error.\n");
830 fprintf(output, "\n");
834 const char *sstr; /* The short string */
835 const char *lstr; /* The long string */
839 string_compare(gconstpointer a, gconstpointer b)
841 return strcmp(((const struct string_elem *)a)->sstr,
842 ((const struct string_elem *)b)->sstr);
846 string_nat_compare(gconstpointer a, gconstpointer b)
848 return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
849 ((const struct string_elem *)b)->sstr);
853 string_elem_print(gpointer data, gpointer not_used _U_)
855 fprintf(stderr, " %s - %s\n",
856 ((struct string_elem *)data)->sstr,
857 ((struct string_elem *)data)->lstr);
861 list_capture_types(void) {
863 struct string_elem *captypes;
866 captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES_SUBTYPES);
867 fprintf(stderr, "editcap: The available capture file types for the \"-F\" flag are:\n");
868 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
869 if (wtap_dump_can_open(i)) {
870 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
871 captypes[i].lstr = wtap_file_type_subtype_string(i);
872 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
875 g_slist_foreach(list, string_elem_print, NULL);
881 list_encap_types(void) {
883 struct string_elem *encaps;
886 encaps = (struct string_elem *)g_malloc(sizeof(struct string_elem) * WTAP_NUM_ENCAP_TYPES);
887 fprintf(stderr, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
888 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
889 encaps[i].sstr = wtap_encap_short_string(i);
890 if (encaps[i].sstr != NULL) {
891 encaps[i].lstr = wtap_encap_string(i);
892 list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
895 g_slist_foreach(list, string_elem_print, NULL);
901 framenum_compare(gconstpointer a, gconstpointer b, gpointer user_data _U_)
903 if (GPOINTER_TO_UINT(a) < GPOINTER_TO_UINT(b))
906 if (GPOINTER_TO_UINT(a) > GPOINTER_TO_UINT(b))
913 * General errors are reported with an console message in editcap.
916 failure_message(const char *msg_format, va_list ap)
918 fprintf(stderr, "editcap: ");
919 vfprintf(stderr, msg_format, ap);
920 fprintf(stderr, "\n");
924 * Report additional information for an error in command-line arguments.
927 failure_message_cont(const char *msg_format, va_list ap)
929 vfprintf(stderr, msg_format, ap);
930 fprintf(stderr, "\n");
934 editcap_dump_open(const char *filename, guint32 snaplen,
936 wtapng_iface_descriptions_t *idb_inf,
937 GArray* nrb_hdrs, int *write_err)
941 if (strcmp(filename, "-") == 0) {
942 /* Write to the standard output. */
943 pdh = wtap_dump_open_stdout_ng(out_file_type_subtype, out_frame_type,
944 snaplen, FALSE /* compressed */,
945 shb_hdrs, idb_inf, nrb_hdrs, write_err);
947 pdh = wtap_dump_open_ng(filename, out_file_type_subtype, out_frame_type,
948 snaplen, FALSE /* compressed */,
949 shb_hdrs, idb_inf, nrb_hdrs, write_err);
955 main(int argc, char *argv[])
957 GString *comp_info_str;
958 GString *runtime_info_str;
959 char *init_progfile_dir_error;
961 int i, j, read_err, write_err;
962 gchar *read_err_info, *write_err_info;
964 static const struct option long_options[] = {
965 {"novlan", no_argument, NULL, 0x8100},
966 {"help", no_argument, NULL, 'h'},
967 {"version", no_argument, NULL, 'V'},
972 guint32 snaplen = 0; /* No limit */
973 chop_t chop = {0, 0, 0, 0, 0, 0}; /* No chop */
974 gboolean adjlen = FALSE;
975 wtap_dumper *pdh = NULL;
976 unsigned int count = 1;
977 unsigned int duplicate_count = 0;
981 guint32 read_count = 0;
982 guint32 split_packet_count = 0;
983 int written_count = 0;
984 char *filename = NULL;
986 guint32 secs_per_block = 0;
988 nstime_t block_start;
989 gchar *fprefix = NULL;
990 gchar *fsuffix = NULL;
991 guint32 change_offset = 0;
992 guint max_packet_number = 0;
993 const struct wtap_pkthdr *phdr;
994 struct wtap_pkthdr temp_phdr;
995 wtapng_iface_descriptions_t *idb_inf = NULL;
996 GArray *shb_hdrs = NULL;
997 GArray *nrb_hdrs = NULL;
999 int ret = EXIT_SUCCESS;
1001 cmdarg_err_init(failure_message, failure_message_cont);
1004 arg_list_utf_16to8(argc, argv);
1005 create_app_running_mutex();
1008 /* Get the compile-time version information string */
1009 comp_info_str = get_compiled_version_info(NULL, NULL);
1011 /* Get the run-time version information string */
1012 runtime_info_str = get_runtime_version_info(NULL);
1014 /* Add it to the information to be reported on a crash. */
1015 ws_add_crash_info("Editcap (Wireshark) %s\n"
1020 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
1021 g_string_free(comp_info_str, TRUE);
1022 g_string_free(runtime_info_str, TRUE);
1025 * Get credential information for later use.
1027 init_process_policies();
1030 * Attempt to get the pathname of the directory containing the
1033 init_progfile_dir_error = init_progfile_dir(argv[0], main);
1034 if (init_progfile_dir_error != NULL) {
1036 "editcap: Can't get pathname of directory containing the editcap program: %s.\n",
1037 init_progfile_dir_error);
1038 g_free(init_progfile_dir_error);
1044 /* Register wiretap plugins */
1045 init_report_err(failure_message,NULL,NULL,NULL);
1047 /* Scan for plugins. This does *not* call their registration routines;
1050 Don't report failures to load plugins because most (non-wiretap)
1051 plugins *should* fail to load (because we're not linked against
1052 libwireshark and dissector plugins need libwireshark). */
1053 scan_plugins(DONT_REPORT_LOAD_FAILURE);
1055 /* Register all libwiretap plugin modules. */
1056 register_all_wiretap_modules();
1059 /* Process the options */
1060 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) {
1071 gint string_start_index = 0;
1073 if ((sscanf(optarg, "%u:%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1074 fprintf(stderr, "editcap: \"%s\" isn't a valid <frame>:<comment>\n\n",
1076 ret = INVALID_OPTION;
1080 /* Lazily create the table */
1081 if (!frames_user_comments) {
1082 frames_user_comments = g_tree_new_full(framenum_compare, NULL, NULL, g_free);
1085 /* Insert this entry (framenum -> comment) */
1086 g_tree_replace(frames_user_comments, GUINT_TO_POINTER(frame_number), g_strdup(optarg+string_start_index));
1094 memset(&starttm,0,sizeof(struct tm));
1096 if (!strptime(optarg,"%Y-%m-%d %T", &starttm)) {
1097 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1099 ret = INVALID_OPTION;
1103 check_startstop = TRUE;
1104 starttm.tm_isdst = -1;
1106 starttime = mktime(&starttm);
1114 memset(&stoptm,0,sizeof(struct tm));
1116 if (!strptime(optarg,"%Y-%m-%d %T", &stoptm)) {
1117 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1119 ret = INVALID_OPTION;
1122 check_startstop = TRUE;
1123 stoptm.tm_isdst = -1;
1124 stoptime = mktime(&stoptm);
1129 split_packet_count = get_nonzero_guint32(optarg, "packet count");
1134 int choplen = 0, chopoff = 0;
1136 switch (sscanf(optarg, "%d:%d", &chopoff, &choplen)) {
1137 case 1: /* only the chop length was specififed */
1142 case 2: /* both an offset and chop length was specified */
1146 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length or offset:length\n",
1148 ret = INVALID_OPTION;
1154 chop.len_begin += choplen;
1156 chop.off_begin_pos += chopoff;
1158 chop.off_begin_neg += chopoff;
1159 } else if (choplen < 0) {
1160 chop.len_end += choplen;
1162 chop.off_end_pos += chopoff;
1164 chop.off_end_neg += chopoff;
1171 dup_detect_by_time = FALSE;
1172 dup_window = DEFAULT_DUP_DEPTH;
1177 dup_detect_by_time = FALSE;
1178 dup_window = get_guint32(optarg, "duplicate window");
1179 if (dup_window > MAX_DUP_DEPTH) {
1180 fprintf(stderr, "editcap: \"%d\" duplicate window value must be between 0 and %d inclusive.\n",
1181 dup_window, MAX_DUP_DEPTH);
1182 ret = INVALID_OPTION;
1188 err_prob = g_ascii_strtod(optarg, &p);
1189 if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
1190 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
1192 ret = INVALID_OPTION;
1195 srand( (unsigned int) (time(NULL) + ws_getpid()) );
1199 out_file_type_subtype = wtap_short_string_to_file_type_subtype(optarg);
1200 if (out_file_type_subtype < 0) {
1201 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
1203 list_capture_types();
1204 ret = INVALID_OPTION;
1210 printf("Editcap (Wireshark) %s\n"
1211 "Edit and/or translate the format of capture files.\n"
1212 "See https://www.wireshark.org for more information.\n",
1213 get_ws_vcs_version_info());
1214 print_usage(stdout);
1218 case 'i': /* break capture file based on time interval */
1219 secs_per_block = get_nonzero_guint32(optarg, "time interval");
1222 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1223 ignored_bytes = get_guint32(optarg, "number of bytes to ignore");
1231 change_offset = get_guint32(optarg, "change offset");
1235 keep_em = !keep_em; /* Just invert */
1239 snaplen = get_nonzero_guint32(optarg, "snapshot length");
1243 if (!set_strict_time_adj(optarg)) {
1244 ret = INVALID_OPTION;
1247 do_strict_time_adjustment = TRUE;
1251 if (!set_time_adjustment(optarg)) {
1252 ret = INVALID_OPTION;
1258 out_frame_type = wtap_short_string_to_encap(optarg);
1259 if (out_frame_type < 0) {
1260 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
1263 ret = INVALID_OPTION;
1269 verbose = !verbose; /* Just invert */
1273 comp_info_str = get_compiled_version_info(NULL, NULL);
1274 runtime_info_str = get_runtime_version_info(NULL);
1275 show_version("Editcap (Wireshark)", comp_info_str, runtime_info_str);
1276 g_string_free(comp_info_str, TRUE);
1277 g_string_free(runtime_info_str, TRUE);
1283 dup_detect_by_time = TRUE;
1284 dup_window = MAX_DUP_DEPTH;
1285 if (!set_rel_time(optarg)) {
1286 ret = INVALID_OPTION;
1291 case '?': /* Bad options if GNU getopt */
1294 list_capture_types();
1300 print_usage(stderr);
1303 ret = INVALID_OPTION;
1307 } /* processing commmand-line options */
1310 fprintf(stderr, "Optind = %i, argc = %i\n", optind, argc);
1313 if ((argc - optind) < 1) {
1314 print_usage(stderr);
1315 ret = INVALID_OPTION;
1319 if (check_startstop && !stoptime) {
1322 /* XXX: will work until 2035 */
1323 memset(&stoptm,0,sizeof(struct tm));
1324 stoptm.tm_year = 135;
1325 stoptm.tm_mday = 31;
1328 stoptime = mktime(&stoptm);
1331 nstime_set_unset(&block_start);
1333 if (starttime > stoptime) {
1334 fprintf(stderr, "editcap: start time is after the stop time\n");
1335 ret = INVALID_OPTION;
1339 if (split_packet_count != 0 && secs_per_block != 0) {
1340 fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
1341 fprintf(stderr, "editcap: at the same time\n");
1342 ret = INVALID_OPTION;
1346 wth = wtap_open_offline(argv[optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, FALSE);
1349 fprintf(stderr, "editcap: Can't open %s: %s\n", argv[optind],
1350 wtap_strerror(read_err));
1351 if (read_err_info != NULL) {
1352 fprintf(stderr, "(%s)\n", read_err_info);
1353 g_free(read_err_info);
1360 fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
1361 wtap_file_type_subtype_string(wtap_file_type_subtype(wth)));
1364 shb_hdrs = wtap_file_get_shb_for_new_file(wth);
1365 idb_inf = wtap_file_get_idb_info(wth);
1366 nrb_hdrs = wtap_file_get_nrb_for_new_file(wth);
1369 * Now, process the rest, if any ... we only write if there is an extra
1370 * argument or so ...
1373 if ((argc - optind) >= 2) {
1374 if (out_frame_type == -2)
1375 out_frame_type = wtap_file_encap(wth);
1377 for (i = optind + 2; i < argc; i++)
1378 if (add_selection(argv[i], &max_packet_number) == FALSE)
1381 if (keep_em == FALSE)
1382 max_packet_number = G_MAXUINT;
1384 if (dup_detect || dup_detect_by_time) {
1385 for (i = 0; i < dup_window; i++) {
1386 memset(&fd_hash[i].digest, 0, 16);
1388 nstime_set_unset(&fd_hash[i].frame_time);
1392 /* Read all of the packets in turn */
1393 while (wtap_read(wth, &read_err, &read_err_info, &data_offset)) {
1394 if (max_packet_number <= read_count)
1399 phdr = wtap_phdr(wth);
1401 /* Extra actions for the first packet */
1402 if (read_count == 1) {
1403 if (split_packet_count != 0 || secs_per_block != 0) {
1404 if (!fileset_extract_prefix_suffix(argv[optind+1], &fprefix, &fsuffix)) {
1405 ret = CANT_EXTRACT_PREFIX;
1409 filename = fileset_get_filename_by_pattern(block_cnt++, phdr, fprefix, fsuffix);
1411 filename = g_strdup(argv[optind+1]);
1415 /* If we don't have an application name add Editcap */
1416 if (wtap_block_get_string_option_value(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
1417 wtap_block_add_string_option_format(g_array_index(shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "Editcap " VERSION);
1420 pdh = editcap_dump_open(filename,
1421 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1422 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1425 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1426 filename, wtap_strerror(write_err));
1430 } /* first packet only handling */
1433 buf = wtap_buf_ptr(wth);
1436 * Not all packets have time stamps. Only process the time
1437 * stamp if we have one.
1439 if (phdr->presence_flags & WTAP_HAS_TS) {
1440 if (nstime_is_unset(&block_start)) {
1441 block_start = phdr->ts;
1443 if (secs_per_block != 0) {
1444 while (((guint32)(phdr->ts.secs - block_start.secs) > secs_per_block)
1445 || ((guint32)(phdr->ts.secs - block_start.secs) == secs_per_block
1446 && phdr->ts.nsecs >= block_start.nsecs )) { /* time for the next file */
1448 if (!wtap_dump_close(pdh, &write_err)) {
1449 fprintf(stderr, "editcap: Error writing to %s: %s\n",
1450 filename, wtap_strerror(write_err));
1454 block_start.secs = block_start.secs + secs_per_block; /* reset for next interval */
1456 filename = fileset_get_filename_by_pattern(block_cnt++, phdr, fprefix, fsuffix);
1460 fprintf(stderr, "Continuing writing in file %s\n", filename);
1462 pdh = editcap_dump_open(filename,
1463 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1464 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1467 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1468 filename, wtap_strerror(write_err));
1474 } /* time stamp handling */
1476 if (split_packet_count != 0) {
1477 /* time for the next file? */
1478 if (written_count > 0 && (written_count % split_packet_count) == 0) {
1479 if (!wtap_dump_close(pdh, &write_err)) {
1480 fprintf(stderr, "editcap: Error writing to %s: %s\n",
1481 filename, wtap_strerror(write_err));
1487 filename = fileset_get_filename_by_pattern(block_cnt++, phdr, fprefix, fsuffix);
1491 fprintf(stderr, "Continuing writing in file %s\n", filename);
1493 pdh = editcap_dump_open(filename,
1494 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1495 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1497 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1498 filename, wtap_strerror(write_err));
1503 } /* split packet handling */
1505 if (check_startstop) {
1507 * Is the packet in the selected timeframe?
1508 * If the packet has no time stamp, the answer is "no".
1510 if (phdr->presence_flags & WTAP_HAS_TS)
1511 ts_okay = (phdr->ts.secs >= starttime) && (phdr->ts.secs < stoptime);
1516 * No selected timeframe, so all packets are "in the
1517 * selected timeframe".
1522 if (ts_okay && ((!selected(count) && !keep_em)
1523 || (selected(count) && keep_em))) {
1525 if (verbose && !dup_detect && !dup_detect_by_time)
1526 fprintf(stderr, "Packet: %u\n", count);
1528 /* We simply write it, perhaps after truncating it; we could
1529 * do other things, like modify it. */
1531 phdr = wtap_phdr(wth);
1534 /* Limit capture length to snaplen */
1535 if (phdr->caplen > snaplen) {
1536 /* Copy and change rather than modify returned phdr */
1538 temp_phdr.caplen = snaplen;
1541 /* If -L, also set reported length to snaplen */
1542 if (adjlen && phdr->len > snaplen) {
1543 /* Copy and change rather than modify returned phdr */
1545 temp_phdr.len = snaplen;
1552 handle_chopping(chop, &temp_phdr, phdr, &buf, adjlen);
1555 if (phdr->presence_flags & WTAP_HAS_TS) {
1556 /* Do we adjust timestamps to ensure strict chronological
1558 if (do_strict_time_adjustment) {
1559 if (previous_time.secs || previous_time.nsecs) {
1560 if (!strict_time_adj.is_negative) {
1566 nstime_delta(&delta, ¤t, &previous_time);
1568 if (delta.secs < 0 || delta.nsecs < 0) {
1570 * A negative delta indicates that the current packet
1571 * has an absolute timestamp less than the previous packet
1572 * that it is being compared to. This is NOT a normal
1573 * situation since trace files usually have packets in
1574 * chronological order (oldest to newest).
1576 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
1578 temp_phdr.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1579 temp_phdr.ts.nsecs = previous_time.nsecs;
1580 if (temp_phdr.ts.nsecs + strict_time_adj.tv.nsecs > ONE_BILLION) {
1582 temp_phdr.ts.secs++;
1583 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1585 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs;
1591 * A negative strict time adjustment is requested.
1592 * Unconditionally set each timestamp to previous
1593 * packet's timestamp plus delta.
1596 temp_phdr.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1597 temp_phdr.ts.nsecs = previous_time.nsecs;
1598 if (temp_phdr.ts.nsecs + strict_time_adj.tv.nsecs > ONE_BILLION) {
1600 temp_phdr.ts.secs++;
1601 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1603 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs;
1608 previous_time = phdr->ts;
1611 if (time_adj.tv.secs != 0) {
1613 if (time_adj.is_negative)
1614 temp_phdr.ts.secs -= time_adj.tv.secs;
1616 temp_phdr.ts.secs += time_adj.tv.secs;
1620 if (time_adj.tv.nsecs != 0) {
1622 if (time_adj.is_negative) { /* subtract */
1623 if (temp_phdr.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
1624 temp_phdr.ts.secs--;
1625 temp_phdr.ts.nsecs += ONE_BILLION;
1627 temp_phdr.ts.nsecs -= time_adj.tv.nsecs;
1629 if (temp_phdr.ts.nsecs + time_adj.tv.nsecs > ONE_BILLION) {
1631 temp_phdr.ts.secs++;
1632 temp_phdr.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
1634 temp_phdr.ts.nsecs += time_adj.tv.nsecs;
1639 } /* time stamp adjustment */
1641 /* remove vlan info */
1643 /* TODO: keep casting const like this? change pointer instead of value? */
1644 remove_vlan_info(phdr, buf, (guint32 *) &phdr->caplen);
1647 /* suppress duplicates by packet window */
1649 if (is_duplicate(buf, phdr->caplen)) {
1651 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1652 count, phdr->caplen);
1653 for (i = 0; i < 16; i++)
1654 fprintf(stderr, "%02x",
1655 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1656 fprintf(stderr, "\n");
1663 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1664 count, phdr->caplen);
1665 for (i = 0; i < 16; i++)
1666 fprintf(stderr, "%02x",
1667 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1668 fprintf(stderr, "\n");
1671 } /* suppression of duplicates */
1673 if (phdr->presence_flags & WTAP_HAS_TS) {
1674 /* suppress duplicates by time window */
1675 if (dup_detect_by_time) {
1678 current.secs = phdr->ts.secs;
1679 current.nsecs = phdr->ts.nsecs;
1681 if (is_duplicate_rel_time(buf, phdr->caplen, ¤t)) {
1683 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1684 count, phdr->caplen);
1685 for (i = 0; i < 16; i++)
1686 fprintf(stderr, "%02x",
1687 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1688 fprintf(stderr, "\n");
1695 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1696 count, phdr->caplen);
1697 for (i = 0; i < 16; i++)
1698 fprintf(stderr, "%02x",
1699 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1700 fprintf(stderr, "\n");
1704 } /* suppress duplicates by time window */
1706 if (change_offset > phdr->caplen) {
1707 fprintf(stderr, "change offset %u is longer than caplen %u in packet %u\n",
1708 change_offset, phdr->caplen, count);
1711 /* Random error mutation */
1712 if (err_prob > 0.0 && change_offset <= phdr->caplen) {
1713 int real_data_start = 0;
1715 /* Protect non-protocol data */
1716 if (wtap_file_type_subtype(wth) == WTAP_FILE_TYPE_SUBTYPE_CATAPULT_DCT2000)
1717 real_data_start = find_dct2000_real_data(buf);
1719 real_data_start += change_offset;
1721 for (i = real_data_start; i < (int) phdr->caplen; i++) {
1722 if (rand() <= err_prob * RAND_MAX) {
1723 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
1725 if (err_type < ERR_WT_BIT) {
1726 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
1727 err_type = ERR_WT_TOTAL;
1729 err_type -= ERR_WT_BYTE;
1732 if (err_type < ERR_WT_BYTE) {
1733 buf[i] = rand() / (RAND_MAX / 255 + 1);
1734 err_type = ERR_WT_TOTAL;
1736 err_type -= ERR_WT_BYTE;
1739 if (err_type < ERR_WT_ALNUM) {
1740 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
1741 err_type = ERR_WT_TOTAL;
1743 err_type -= ERR_WT_ALNUM;
1746 if (err_type < ERR_WT_FMT) {
1747 if ((unsigned int)i < phdr->caplen - 2)
1748 g_strlcpy((char*) &buf[i], "%s", 2);
1749 err_type = ERR_WT_TOTAL;
1751 err_type -= ERR_WT_FMT;
1754 if (err_type < ERR_WT_AA) {
1755 for (j = i; j < (int) phdr->caplen; j++)
1761 } /* random error mutation */
1763 /* Find a packet comment we may need to write */
1764 if (frames_user_comments) {
1765 const char *comment =
1766 (const char*)g_tree_lookup(frames_user_comments, GUINT_TO_POINTER(read_count));
1767 if (comment != NULL) {
1768 /* Copy and change rather than modify returned phdr */
1770 temp_phdr.opt_comment = g_strdup(comment);
1775 /* Attempt to dump out current frame to the output file */
1776 if (!wtap_dump(pdh, phdr, buf, &write_err, &write_err_info)) {
1777 switch (write_err) {
1778 case WTAP_ERR_UNWRITABLE_ENCAP:
1780 * This is a problem with the particular frame we're
1781 * writing and the file type and subtype we're
1782 * writing; note that, and report the frame number
1783 * and file type/subtype.
1786 "editcap: Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
1787 read_count, argv[optind],
1788 wtap_file_type_subtype_string(out_file_type_subtype));
1791 case WTAP_ERR_PACKET_TOO_LARGE:
1793 * This is a problem with the particular frame we're
1794 * writing and the file type and subtype we're
1795 * writing; note that, and report the frame number
1796 * and file type/subtype.
1799 "editcap: Frame %u of \"%s\" is too large for a \"%s\" file.\n",
1800 read_count, argv[optind],
1801 wtap_file_type_subtype_string(out_file_type_subtype));
1804 case WTAP_ERR_UNWRITABLE_REC_TYPE:
1806 * This is a problem with the particular record we're
1807 * writing and the file type and subtype we're
1808 * writing; note that, and report the record number
1809 * and file type/subtype.
1812 "editcap: Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
1813 read_count, argv[optind],
1814 wtap_file_type_subtype_string(out_file_type_subtype));
1817 case WTAP_ERR_UNWRITABLE_REC_DATA:
1819 * This is a problem with the particular record we're
1820 * writing and the file type and subtype we're
1821 * writing; note that, and report the record number
1822 * and file type/subtype.
1825 "editcap: Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
1826 read_count, argv[optind],
1827 wtap_file_type_subtype_string(out_file_type_subtype),
1828 write_err_info != NULL ? write_err_info : "no information supplied");
1829 g_free(write_err_info);
1833 fprintf(stderr, "editcap: Error writing to %s: %s\n",
1834 filename, wtap_strerror(write_err));
1848 if (read_err != 0) {
1849 /* Print a message noting that the read failed somewhere along the
1852 "editcap: An error occurred while reading \"%s\": %s.\n",
1853 argv[optind], wtap_strerror(read_err));
1854 if (read_err_info != NULL) {
1855 fprintf(stderr, "(%s)\n", read_err_info);
1856 g_free(read_err_info);
1861 /* No valid packages found, open the outfile so we can write an
1864 filename = g_strdup(argv[optind+1]);
1866 pdh = editcap_dump_open(filename,
1867 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)): wtap_snapshot_length(wth),
1868 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1870 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1871 filename, wtap_strerror(write_err));
1877 if (!wtap_dump_close(pdh, &write_err)) {
1878 fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
1879 wtap_strerror(write_err));
1885 if (frames_user_comments) {
1886 g_tree_destroy(frames_user_comments);
1891 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate window of %i packets.\n",
1892 count - 1, plurality(count - 1, "", "s"), duplicate_count,
1893 plurality(duplicate_count, "", "s"), dup_window);
1894 } else if (dup_detect_by_time) {
1895 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
1896 count - 1, plurality(count - 1, "", "s"), duplicate_count,
1897 plurality(duplicate_count, "", "s"),
1898 (long)relative_time_window.secs,
1899 (long int)relative_time_window.nsecs);
1903 wtap_block_array_free(shb_hdrs);
1904 wtap_block_array_free(nrb_hdrs);
1915 /* Skip meta-information read from file to return offset of real
1918 find_dct2000_real_data(guint8 *buf)
1922 for (n = 0; buf[n] != '\0'; n++); /* Context name */
1924 n++; /* Context port number */
1925 for (; buf[n] != '\0'; n++); /* Timestamp */
1927 for (; buf[n] != '\0'; n++); /* Protocol name */
1929 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
1931 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
1933 n += 2; /* Direction & encap */
1939 * We support up to 2 chopping regions in a single pass: one specified by the
1940 * positive chop length, and one by the negative chop length.
1943 handle_chopping(chop_t chop, struct wtap_pkthdr *out_phdr,
1944 const struct wtap_pkthdr *in_phdr, guint8 **buf,
1947 /* Only packets can be chopped. */
1948 if (in_phdr->rec_type != REC_TYPE_PACKET)
1951 /* If we're not chopping anything from one side, then the offset for that
1952 * side is meaningless. */
1953 if (chop.len_begin == 0)
1954 chop.off_begin_pos = chop.off_begin_neg = 0;
1955 if (chop.len_end == 0)
1956 chop.off_end_pos = chop.off_end_neg = 0;
1958 if (chop.off_begin_neg < 0) {
1959 chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
1960 chop.off_begin_neg = 0;
1962 if (chop.off_end_pos > 0) {
1963 chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
1964 chop.off_end_pos = 0;
1967 /* If we've crossed chopping regions, swap them */
1968 if (chop.len_begin && chop.len_end) {
1969 if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
1970 int tmp_len, tmp_off;
1972 tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
1973 tmp_len = -chop.len_end;
1975 chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
1976 chop.len_end = -chop.len_begin;
1978 chop.len_begin = tmp_len;
1979 chop.off_begin_pos = tmp_off;
1983 /* Make sure we don't chop off more than we have available */
1984 if (in_phdr->caplen < (guint32)(chop.off_begin_pos - chop.off_end_neg)) {
1988 if ((guint32)(chop.len_begin - chop.len_end) >
1989 (in_phdr->caplen - (guint32)(chop.off_begin_pos - chop.off_end_neg))) {
1990 chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
1994 /* Handle chopping from the beginning. Note that if a beginning offset
1995 * was specified, we need to keep that piece */
1996 if (chop.len_begin > 0) {
1997 *out_phdr = *in_phdr;
1999 if (chop.off_begin_pos > 0) {
2000 memmove(*buf + chop.off_begin_pos,
2001 *buf + chop.off_begin_pos + chop.len_begin,
2002 out_phdr->caplen - chop.len_begin);
2004 *buf += chop.len_begin;
2006 out_phdr->caplen -= chop.len_begin;
2009 if (in_phdr->len > (guint32)chop.len_begin)
2010 out_phdr->len -= chop.len_begin;
2017 /* Handle chopping from the end. Note that if an ending offset was
2018 * specified, we need to keep that piece */
2019 if (chop.len_end < 0) {
2020 *out_phdr = *in_phdr;
2022 if (chop.off_end_neg < 0) {
2023 memmove(*buf + (gint)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2024 *buf + (gint)out_phdr->caplen + chop.off_end_neg,
2027 out_phdr->caplen += chop.len_end;
2030 if (((signed int) in_phdr->len + chop.len_end) > 0)
2031 out_phdr->len += chop.len_end;
2035 /*in_phdr = out_phdr;*/
2040 * Editor modelines - http://www.wireshark.org/tools/modelines.html
2045 * indent-tabs-mode: nil
2048 * vi: set shiftwidth=4 tabstop=8 expandtab:
2049 * :indentSize=4:tabSize=8:noTabs=true: