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 * SPDX-License-Identifier: GPL-2.0-or-later
27 * Just make sure we include the prototype for strptime as well
28 * (needed for glibc 2.2) but make sure we do this only if not
47 #include <wiretap/secrets-types.h>
48 #include <wiretap/wtap.h>
50 #include "epan/etypes.h"
51 #include "epan/dissectors/packet-ieee80211-radiotap-defs.h"
53 #ifndef HAVE_GETOPT_LONG
54 #include "wsutil/wsgetopt.h"
58 #include <process.h> /* getpid */
63 # include "wsutil/strptime.h"
66 #include <ui/clopts_common.h>
67 #include <ui/cmdarg_err.h>
68 #include <wsutil/filesystem.h>
69 #include <wsutil/file_util.h>
70 #include <wsutil/wsgcrypt.h>
71 #include <wsutil/plugins.h>
72 #include <wsutil/privileges.h>
73 #include <wsutil/report_message.h>
74 #include <wsutil/strnatcmp.h>
75 #include <wsutil/str_util.h>
77 #include <version_info.h>
78 #include <wsutil/pint.h>
79 #include <wsutil/strtoi.h>
80 #include <wiretap/wtap_opttypes.h>
81 #include <wiretap/pcapng.h>
83 #include "ui/failure_message.h"
85 #include "ringbuffer.h" /* For RINGBUFFER_MAX_NUM_FILES */
87 #define INVALID_OPTION 1
88 #define INVALID_FILE 2
89 #define CANT_EXTRACT_PREFIX 2
92 #define NANOSECS_PER_SEC 1000000000
95 * Some globals so we can pass things to various routines
104 * Duplicate frame detection
106 typedef struct _fd_hash_t {
112 #define DEFAULT_DUP_DEPTH 5 /* Used with -d */
113 #define MAX_DUP_DEPTH 1000000 /* the maximum window (and actual size of fd_hash[]) for de-duplication */
115 static fd_hash_t fd_hash[MAX_DUP_DEPTH];
116 static int dup_window = DEFAULT_DUP_DEPTH;
117 static int cur_dup_entry = 0;
119 static guint32 ignored_bytes = 0; /* Used with -I */
121 #define ONE_BILLION 1000000000
123 /* Weights of different errors we can introduce */
124 /* We should probably make these command-line arguments */
125 /* XXX - Should we add a bit-level error? */
126 #define ERR_WT_BIT 5 /* Flip a random bit */
127 #define ERR_WT_BYTE 5 /* Substitute a random byte */
128 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
129 #define ERR_WT_FMT 2 /* Substitute "%s" */
130 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
131 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
133 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
134 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
136 struct time_adjustment {
141 typedef struct _chop_t {
151 /* Table of user comments */
152 GTree *frames_user_comments = NULL;
154 #define MAX_SELECTIONS 512
155 static struct select_item selectfrm[MAX_SELECTIONS];
156 static guint max_selected = 0;
157 static int keep_em = 0;
158 #ifdef PCAP_NG_DEFAULT
159 static int out_file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcapng */
161 static int out_file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcap */
163 static int out_frame_type = -2; /* Leave frame type alone */
164 static int verbose = 0; /* Not so verbose */
165 static struct time_adjustment time_adj = {NSTIME_INIT_ZERO, 0}; /* no adjustment */
166 static nstime_t relative_time_window = NSTIME_INIT_ZERO; /* de-dup time window */
167 static double err_prob = -1.0;
168 static time_t starttime = 0;
169 static time_t stoptime = 0;
170 static gboolean check_startstop = FALSE;
171 static gboolean rem_vlan = FALSE;
172 static gboolean dup_detect = FALSE;
173 static gboolean dup_detect_by_time = FALSE;
174 static gboolean skip_radiotap = FALSE;
175 static gboolean discard_all_secrets = FALSE;
177 static int do_strict_time_adjustment = FALSE;
178 static struct time_adjustment strict_time_adj = {NSTIME_INIT_ZERO, 0}; /* strict time adjustment */
179 static nstime_t previous_time = NSTIME_INIT_ZERO; /* previous time */
181 static const struct {
184 } secrets_types[] = {
185 { "tls", SECRETS_TYPE_TLS },
186 { "wg", SECRETS_TYPE_WIREGUARD },
189 static int find_dct2000_real_data(guint8 *buf);
190 static void handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
191 const wtap_packet_header *in_phdr, guint8 **buf,
195 abs_time_to_str_with_sec_resolution(const nstime_t *abs_time)
198 gchar *buf = (gchar *)g_malloc(16);
200 tmp = localtime(&abs_time->secs);
203 g_snprintf(buf, 16, "%d%02d%02d%02d%02d%02d",
218 fileset_get_filename_by_pattern(guint idx, const wtap_rec *rec,
219 gchar *fprefix, gchar *fsuffix)
225 g_snprintf(filenum, sizeof(filenum), "%05u", idx % RINGBUFFER_MAX_NUM_FILES);
226 if (rec->presence_flags & WTAP_HAS_TS) {
227 timestr = abs_time_to_str_with_sec_resolution(&rec->ts);
228 abs_str = g_strconcat(fprefix, "_", filenum, "_", timestr, fsuffix, NULL);
231 abs_str = g_strconcat(fprefix, "_", filenum, fsuffix, NULL);
237 fileset_extract_prefix_suffix(const char *fname, gchar **fprefix, gchar **fsuffix)
239 char *pfx, *last_pathsep;
242 save_file = g_strdup(fname);
243 if (save_file == NULL) {
244 fprintf(stderr, "editcap: Out of memory\n");
248 last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
249 pfx = strrchr(save_file,'.');
250 if (pfx != NULL && (last_pathsep == NULL || pfx > last_pathsep)) {
251 /* The pathname has a "." in it, and it's in the last component
252 * of the pathname (because there is either only one component,
253 * i.e. last_pathsep is null as there are no path separators,
254 * or the "." is after the path separator before the last
257 * Treat it as a separator between the rest of the file name and
258 * the file name suffix, and arrange that the names given to the
259 * ring buffer files have the specified suffix, i.e. put the
260 * changing part of the name *before* the suffix. */
262 *fprefix = g_strdup(save_file);
263 pfx[0] = '.'; /* restore capfile_name */
264 *fsuffix = g_strdup(pfx);
266 /* Either there's no "." in the pathname, or it's in a directory
267 * component, so the last component has no suffix. */
268 *fprefix = g_strdup(save_file);
275 /* Add a selection item, a simple parser for now */
277 add_selection(char *sel, guint* max_selection)
282 if (max_selected >= MAX_SELECTIONS) {
283 /* Let the user know we stopped selecting */
284 fprintf(stderr, "Out of room for packet selections.\n");
289 fprintf(stderr, "Add_Selected: %s\n", sel);
291 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
293 fprintf(stderr, "Not inclusive ...");
295 selectfrm[max_selected].inclusive = FALSE;
296 selectfrm[max_selected].first = get_guint32(sel, "packet number");
297 if (selectfrm[max_selected].first > *max_selection)
298 *max_selection = selectfrm[max_selected].first;
301 fprintf(stderr, " %u\n", selectfrm[max_selected].first);
304 fprintf(stderr, "Inclusive ...");
306 *locn = '\0'; /* split the range */
308 selectfrm[max_selected].inclusive = TRUE;
309 selectfrm[max_selected].first = get_guint32(sel, "beginning of packet range");
310 selectfrm[max_selected].second = get_guint32(next, "end of packet range");
312 if (selectfrm[max_selected].second == 0)
314 /* Not a valid number, presume all */
315 selectfrm[max_selected].second = *max_selection = G_MAXUINT;
317 else if (selectfrm[max_selected].second > *max_selection)
318 *max_selection = selectfrm[max_selected].second;
321 fprintf(stderr, " %u, %u\n", selectfrm[max_selected].first,
322 selectfrm[max_selected].second);
329 /* Was the packet selected? */
332 selected(guint recno)
336 for (i = 0; i < max_selected; i++) {
337 if (selectfrm[i].inclusive) {
338 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
341 if (recno == selectfrm[i].first)
350 set_time_adjustment(char *optarg_str_p)
359 /* skip leading whitespace */
360 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
363 /* check for a negative adjustment */
364 if (*optarg_str_p == '-') {
365 time_adj.is_negative = 1;
369 /* collect whole number of seconds, if any */
370 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
374 val = strtol(optarg_str_p, &frac, 10);
375 if (frac == NULL || frac == optarg_str_p
376 || val == LONG_MIN || val == LONG_MAX) {
377 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
381 if (val < 0) { /* implies '--' since we caught '-' above */
382 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
387 time_adj.tv.secs = val;
389 /* now collect the partial seconds, if any */
390 if (*frac != '\0') { /* chars left, so get fractional part */
391 val = strtol(&(frac[1]), &end, 10);
392 /* if more than 9 fractional digits truncate to 9 */
393 if ((end - &(frac[1])) > 9) {
394 frac[10] = 't'; /* 't' for truncate */
395 val = strtol(&(frac[1]), &end, 10);
397 if (*frac != '.' || end == NULL || end == frac || val < 0
398 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
399 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
404 return TRUE; /* no fractional digits */
407 /* adjust fractional portion from fractional to numerator
408 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
409 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
410 while(frac_digits < 9) { /* this is frac of 10^9 */
415 time_adj.tv.nsecs = (int)val;
420 set_strict_time_adj(char *optarg_str_p)
429 /* skip leading whitespace */
430 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
434 * check for a negative adjustment
435 * A negative strict adjustment value is a flag
436 * to adjust all frames by the specifed delta time.
438 if (*optarg_str_p == '-') {
439 strict_time_adj.is_negative = 1;
443 /* collect whole number of seconds, if any */
444 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
448 val = strtol(optarg_str_p, &frac, 10);
449 if (frac == NULL || frac == optarg_str_p
450 || val == LONG_MIN || val == LONG_MAX) {
451 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
455 if (val < 0) { /* implies '--' since we caught '-' above */
456 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
461 strict_time_adj.tv.secs = val;
463 /* now collect the partial seconds, if any */
464 if (*frac != '\0') { /* chars left, so get fractional part */
465 val = strtol(&(frac[1]), &end, 10);
466 /* if more than 9 fractional digits truncate to 9 */
467 if ((end - &(frac[1])) > 9) {
468 frac[10] = 't'; /* 't' for truncate */
469 val = strtol(&(frac[1]), &end, 10);
471 if (*frac != '.' || end == NULL || end == frac || val < 0
472 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
473 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
478 return TRUE; /* no fractional digits */
481 /* adjust fractional portion from fractional to numerator
482 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
483 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
484 while(frac_digits < 9) { /* this is frac of 10^9 */
489 strict_time_adj.tv.nsecs = (int)val;
494 set_rel_time(char *optarg_str_p)
503 /* skip leading whitespace */
504 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
507 /* ignore negative adjustment */
508 if (*optarg_str_p == '-')
511 /* collect whole number of seconds, if any */
512 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
516 val = strtol(optarg_str_p, &frac, 10);
517 if (frac == NULL || frac == optarg_str_p
518 || val == LONG_MIN || val == LONG_MAX) {
519 fprintf(stderr, "1: editcap: \"%s\" isn't a valid rel time value\n",
523 if (val < 0) { /* implies '--' since we caught '-' above */
524 fprintf(stderr, "2: editcap: \"%s\" isn't a valid rel time value\n",
529 relative_time_window.secs = val;
531 /* now collect the partial seconds, if any */
532 if (*frac != '\0') { /* chars left, so get fractional part */
533 val = strtol(&(frac[1]), &end, 10);
534 /* if more than 9 fractional digits truncate to 9 */
535 if ((end - &(frac[1])) > 9) {
536 frac[10] = 't'; /* 't' for truncate */
537 val = strtol(&(frac[1]), &end, 10);
539 if (*frac != '.' || end == NULL || end == frac || val < 0
540 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
541 fprintf(stderr, "3: editcap: \"%s\" isn't a valid rel time value\n",
546 return TRUE; /* no fractional digits */
549 /* adjust fractional portion from fractional to numerator
550 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
551 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
552 while(frac_digits < 9) { /* this is frac of 10^9 */
557 relative_time_window.nsecs = (int)val;
561 #define LINUX_SLL_OFFSETP 14
564 sll_remove_vlan_info(guint8* fd, guint32* len) {
565 if (pntoh16(fd + LINUX_SLL_OFFSETP) == ETHERTYPE_VLAN) {
567 /* point to start of vlan */
568 fd = fd + LINUX_SLL_OFFSETP;
569 /* bytes to read after vlan info */
570 rest_len = *len - (LINUX_SLL_OFFSETP + VLAN_SIZE);
571 /* remove vlan info from packet */
572 memmove(fd, fd + VLAN_SIZE, rest_len);
578 remove_vlan_info(const wtap_packet_header *phdr, guint8* fd, guint32* len) {
579 switch (phdr->pkt_encap) {
581 sll_remove_vlan_info(fd, len);
584 /* no support for current pkt_encap */
590 is_duplicate(guint8* fd, guint32 len) {
592 const struct ieee80211_radiotap_header* tap_header;
594 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
595 guint32 offset = ignored_bytes;
599 if (len <= ignored_bytes) {
603 /* Get the size of radiotap header and use that as offset (-p option) */
604 if (skip_radiotap == TRUE) {
605 tap_header = (const struct ieee80211_radiotap_header*)fd;
606 offset = pletoh16(&tap_header->it_len);
611 new_fd = &fd[offset];
612 new_len = len - (offset);
615 if (cur_dup_entry >= dup_window)
618 /* Calculate our digest */
619 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
621 fd_hash[cur_dup_entry].len = len;
623 /* Look for duplicates */
624 for (i = 0; i < dup_window; i++) {
625 if (i == cur_dup_entry)
628 if (fd_hash[i].len == fd_hash[cur_dup_entry].len
629 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
638 is_duplicate_rel_time(guint8* fd, guint32 len, const nstime_t *current) {
641 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
642 guint32 offset = ignored_bytes;
646 if (len <= ignored_bytes) {
650 new_fd = &fd[offset];
651 new_len = len - (offset);
654 if (cur_dup_entry >= dup_window)
657 /* Calculate our digest */
658 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
660 fd_hash[cur_dup_entry].len = len;
661 fd_hash[cur_dup_entry].frame_time.secs = current->secs;
662 fd_hash[cur_dup_entry].frame_time.nsecs = current->nsecs;
665 * Look for relative time related duplicates.
666 * This is hopefully a reasonably efficient mechanism for
667 * finding duplicates by rel time in the fd_hash[] cache.
668 * We check starting from the most recently added hash
669 * entries and work backwards towards older packets.
670 * This approach allows the dup test to be terminated
671 * when the relative time of a cached entry is found to
672 * be beyond the dup time window.
674 * Of course this assumes that the input trace file is
675 * "well-formed" in the sense that the packet timestamps are
676 * in strict chronologically increasing order (which is NOT
677 * always the case!!).
679 * The fd_hash[] table was deliberately created large (1,000,000).
680 * Looking for time related duplicates in large trace files with
681 * non-fractional dup time window values can potentially take
682 * a long time to complete.
685 for (i = cur_dup_entry - 1;; i--) {
692 if (i == cur_dup_entry) {
694 * We've decremented back to where we started.
700 if (nstime_is_unset(&(fd_hash[i].frame_time))) {
702 * We've decremented to an unused fd_hash[] entry.
708 nstime_delta(&delta, current, &fd_hash[i].frame_time);
710 if (delta.secs < 0 || delta.nsecs < 0) {
712 * A negative delta implies that the current packet
713 * has an absolute timestamp less than the cached packet
714 * that it is being compared to. This is NOT a normal
715 * situation since trace files usually have packets in
716 * chronological order (oldest to newest).
718 * There are several possible ways to deal with this:
719 * 1. 'continue' dup checking with the next cached frame.
720 * 2. 'break' from looking for a duplicate of the current frame.
721 * 3. Take the absolute value of the delta and see if that
722 * falls within the specifed dup time window.
724 * Currently this code does option 1. But it would pretty
725 * easy to add yet-another-editcap-option to select one of
726 * the other behaviors for dealing with out-of-sequence
732 cmp = nstime_cmp(&delta, &relative_time_window);
736 * The delta time indicates that we are now looking at
737 * cached packets beyond the specified dup time window.
741 } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len
742 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
751 print_usage(FILE *output)
753 fprintf(output, "\n");
754 fprintf(output, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
755 fprintf(output, "\n");
756 fprintf(output, "<infile> and <outfile> must both be present.\n");
757 fprintf(output, "A single packet or a range of packets can be selected.\n");
758 fprintf(output, "\n");
759 fprintf(output, "Packet selection:\n");
760 fprintf(output, " -r keep the selected packets; default is to delete them.\n");
761 fprintf(output, " -A <start time> only output packets whose timestamp is after (or equal\n");
762 fprintf(output, " to) the given time (format as YYYY-MM-DD hh:mm:ss).\n");
763 fprintf(output, " -B <stop time> only output packets whose timestamp is before the\n");
764 fprintf(output, " given time (format as YYYY-MM-DD hh:mm:ss).\n");
765 fprintf(output, "\n");
766 fprintf(output, "Duplicate packet removal:\n");
767 fprintf(output, " --novlan remove vlan info from packets before checking for duplicates.\n");
768 fprintf(output, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH);
769 fprintf(output, " -D <dup window> remove packet if duplicate; configurable <dup window>.\n");
770 fprintf(output, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH);
771 fprintf(output, " NOTE: A <dup window> of 0 with -v (verbose option) is\n");
772 fprintf(output, " useful to print MD5 hashes.\n");
773 fprintf(output, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
774 fprintf(output, " LESS THAN <dup time window> prior to current packet.\n");
775 fprintf(output, " A <dup time window> is specified in relative seconds\n");
776 fprintf(output, " (e.g. 0.000001).\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, " --skip-radiotap-header skip radiotap header when checking for packet duplicates.\n");
782 fprintf(output, " Useful when processing packets captured by multiple radios\n");
783 fprintf(output, " on the same channel in the vicinity of each other.\n");
784 fprintf(output, "\n");
785 fprintf(output, "Packet manipulation:\n");
786 fprintf(output, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
787 fprintf(output, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
788 fprintf(output, " chop at the packet beginning, negative values at the\n");
789 fprintf(output, " packet end. If an optional offset precedes the length,\n");
790 fprintf(output, " then the bytes chopped will be offset from that value.\n");
791 fprintf(output, " Positive offsets are from the packet beginning,\n");
792 fprintf(output, " negative offsets are from the packet end. You can use\n");
793 fprintf(output, " this option more than once, allowing up to 2 chopping\n");
794 fprintf(output, " regions within a packet provided that at least 1\n");
795 fprintf(output, " choplen is positive and at least 1 is negative.\n");
796 fprintf(output, " -L adjust the frame (i.e. reported) length when chopping\n");
797 fprintf(output, " and/or snapping.\n");
798 fprintf(output, " -t <time adjustment> adjust the timestamp of each packet.\n");
799 fprintf(output, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
800 fprintf(output, " -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
801 fprintf(output, " strict chronological increasing order. The <strict\n");
802 fprintf(output, " adjustment> is specified in relative seconds with\n");
803 fprintf(output, " values of 0 or 0.000001 being the most reasonable.\n");
804 fprintf(output, " A negative adjustment value will modify timestamps so\n");
805 fprintf(output, " that each packet's delta time is the absolute value\n");
806 fprintf(output, " of the adjustment specified. A value of -0 will set\n");
807 fprintf(output, " all packets to the timestamp of the first packet.\n");
808 fprintf(output, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
809 fprintf(output, " a particular packet byte will be randomly changed.\n");
810 fprintf(output, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
811 fprintf(output, " beginning of the packet. This allows one to preserve some\n");
812 fprintf(output, " bytes, in order to have some headers untouched.\n");
813 fprintf(output, " --seed <seed> When used in conjunction with -E, set the seed to use for\n");
814 fprintf(output, " the pseudo-random number generator. This allows one to\n");
815 fprintf(output, " repeat a particular sequence of errors.\n");
816 fprintf(output, " -I <bytes to ignore> ignore the specified number of bytes at the beginning\n");
817 fprintf(output, " of the frame during MD5 hash calculation, unless the\n");
818 fprintf(output, " frame is too short, then the full frame is used.\n");
819 fprintf(output, " Useful to remove duplicated packets taken on\n");
820 fprintf(output, " several routers (different mac addresses for\n");
821 fprintf(output, " example).\n");
822 fprintf(output, " e.g. -I 26 in case of Ether/IP will ignore\n");
823 fprintf(output, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
824 fprintf(output, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
825 fprintf(output, "\n");
826 fprintf(output, "Output File(s):\n");
827 fprintf(output, " -c <packets per file> split the packet output to different files based on\n");
828 fprintf(output, " uniform packet counts with a maximum of\n");
829 fprintf(output, " <packets per file> each.\n");
830 fprintf(output, " -i <seconds per file> split the packet output to different files based on\n");
831 fprintf(output, " uniform time intervals with a maximum of\n");
832 fprintf(output, " <seconds per file> each.\n");
833 #ifdef PCAP_NG_DEFAULT
834 fprintf(output, " -F <capture type> set the output file type; default is pcapng.\n");
836 fprintf(output, " -F <capture type> set the output file type; default is pcap.\n");
838 fprintf(output, " An empty \"-F\" option will list the file types.\n");
839 fprintf(output, " -T <encap type> set the output file encapsulation type; default is the\n");
840 fprintf(output, " same as the input file. An empty \"-T\" option will\n");
841 fprintf(output, " list the encapsulation types.\n");
842 fprintf(output, " --inject-secrets <type>,<file> Insert decryption secrets from <file>. List\n");
843 fprintf(output, " supported secret types with \"--inject-secrets help\".\n");
844 fprintf(output, " --discard-all-secrets Discard all decryption secrets from the input file\n");
845 fprintf(output, " when writing the output file. Does not discard\n");
846 fprintf(output, " secrets added by \"--inject-secrets\" in the same\n");
847 fprintf(output, " command line.\n");
848 fprintf(output, "\n");
849 fprintf(output, "Miscellaneous:\n");
850 fprintf(output, " -h display this help and exit.\n");
851 fprintf(output, " -v verbose output.\n");
852 fprintf(output, " If -v is used with any of the 'Duplicate Packet\n");
853 fprintf(output, " Removal' options (-d, -D or -w) then Packet lengths\n");
854 fprintf(output, " and MD5 hashes are printed to standard-error.\n");
858 const char *sstr; /* The short string */
859 const char *lstr; /* The long string */
863 string_compare(gconstpointer a, gconstpointer b)
865 return strcmp(((const struct string_elem *)a)->sstr,
866 ((const struct string_elem *)b)->sstr);
870 string_nat_compare(gconstpointer a, gconstpointer b)
872 return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
873 ((const struct string_elem *)b)->sstr);
877 string_elem_print(gpointer data, gpointer stream_ptr)
879 fprintf((FILE *) stream_ptr, " %s - %s\n",
880 ((struct string_elem *)data)->sstr,
881 ((struct string_elem *)data)->lstr);
885 list_capture_types(FILE *stream) {
887 struct string_elem *captypes;
890 captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES_SUBTYPES);
891 fprintf(stream, "editcap: The available capture file types for the \"-F\" flag are:\n");
892 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
893 if (wtap_dump_can_open(i)) {
894 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
895 captypes[i].lstr = wtap_file_type_subtype_string(i);
896 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
899 g_slist_foreach(list, string_elem_print, stream);
905 list_encap_types(FILE *stream) {
907 struct string_elem *encaps;
910 encaps = (struct string_elem *)g_malloc(sizeof(struct string_elem) * WTAP_NUM_ENCAP_TYPES);
911 fprintf(stream, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
912 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
913 encaps[i].sstr = wtap_encap_name(i);
914 if (encaps[i].sstr != NULL) {
915 encaps[i].lstr = wtap_encap_description(i);
916 list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
919 g_slist_foreach(list, string_elem_print, stream);
925 list_secrets_types(FILE *stream)
927 for (guint i = 0; i < G_N_ELEMENTS(secrets_types); i++) {
928 fprintf(stream, " %s\n", secrets_types[i].str);
933 lookup_secrets_type(const char *type)
935 for (guint i = 0; i < G_N_ELEMENTS(secrets_types); i++) {
936 if (!strcmp(secrets_types[i].str, type)) {
937 return secrets_types[i].id;
944 validate_secrets_file(const char *filename, guint32 secrets_type, const char *data)
946 if (secrets_type == SECRETS_TYPE_TLS) {
948 * A key log file is unlikely going to look like either:
949 * - a PEM-encoded private key file.
950 * - a BER-encoded PKCS #12 file ("PFX file"). (Look for a Constructed
951 * SEQUENCE tag, e.g. bytes 0x30 which happens to be ASCII '0'.)
953 if (g_str_has_prefix(data, "-----BEGIN ") || data[0] == 0x30) {
955 "editcap: Warning: \"%s\" is not a key log file, but an unsupported private key file. Decryption will not work.\n",
962 framenum_compare(gconstpointer a, gconstpointer b, gpointer user_data _U_)
964 if (GPOINTER_TO_UINT(a) < GPOINTER_TO_UINT(b))
967 if (GPOINTER_TO_UINT(a) > GPOINTER_TO_UINT(b))
974 * General errors and warnings are reported with an console message
978 failure_warning_message(const char *msg_format, va_list ap)
980 fprintf(stderr, "editcap: ");
981 vfprintf(stderr, msg_format, ap);
982 fprintf(stderr, "\n");
986 * Report additional information for an error in command-line arguments.
989 failure_message_cont(const char *msg_format, va_list ap)
991 vfprintf(stderr, msg_format, ap);
992 fprintf(stderr, "\n");
996 editcap_dump_open(const char *filename, const wtap_dump_params *params,
1001 if (strcmp(filename, "-") == 0) {
1002 /* Write to the standard output. */
1003 pdh = wtap_dump_open_stdout(out_file_type_subtype, WTAP_UNCOMPRESSED,
1006 pdh = wtap_dump_open(filename, out_file_type_subtype, WTAP_UNCOMPRESSED,
1013 main(int argc, char *argv[])
1015 char *init_progfile_dir_error;
1017 int i, j, read_err, write_err;
1018 gchar *read_err_info, *write_err_info;
1021 #define LONGOPT_NO_VLAN LONGOPT_BASE_APPLICATION+1
1022 #define LONGOPT_SKIP_RADIOTAP_HEADER LONGOPT_BASE_APPLICATION+2
1023 #define LONGOPT_SEED LONGOPT_BASE_APPLICATION+3
1024 #define LONGOPT_INJECT_SECRETS LONGOPT_BASE_APPLICATION+4
1025 #define LONGOPT_DISCARD_ALL_SECRETS LONGOPT_BASE_APPLICATION+5
1027 static const struct option long_options[] = {
1028 {"novlan", no_argument, NULL, LONGOPT_NO_VLAN},
1029 {"skip-radiotap-header", no_argument, NULL, LONGOPT_SKIP_RADIOTAP_HEADER},
1030 {"seed", required_argument, NULL, LONGOPT_SEED},
1031 {"inject-secrets", required_argument, NULL, LONGOPT_INJECT_SECRETS},
1032 {"discard-all-secrets", no_argument, NULL, LONGOPT_DISCARD_ALL_SECRETS},
1033 {"help", no_argument, NULL, 'h'},
1034 {"version", no_argument, NULL, 'V'},
1039 guint32 snaplen = 0; /* No limit */
1040 chop_t chop = {0, 0, 0, 0, 0, 0}; /* No chop */
1041 gboolean adjlen = FALSE;
1042 wtap_dumper *pdh = NULL;
1043 unsigned int count = 1;
1044 unsigned int duplicate_count = 0;
1048 guint32 read_count = 0;
1049 guint32 split_packet_count = 0;
1050 int written_count = 0;
1051 char *filename = NULL;
1053 nstime_t secs_per_block = NSTIME_INIT_UNSET;
1055 nstime_t block_next = NSTIME_INIT_UNSET;
1056 gchar *fprefix = NULL;
1057 gchar *fsuffix = NULL;
1058 guint32 change_offset = 0;
1059 guint max_packet_number = 0;
1060 GArray *dsb_types = NULL;
1061 GPtrArray *dsb_filenames = NULL;
1064 const wtap_rec *rec;
1066 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
1067 char *shb_user_appl;
1068 gboolean do_mutation;
1070 int ret = EXIT_SUCCESS;
1071 gboolean valid_seed = FALSE;
1072 unsigned int seed = 0;
1074 cmdarg_err_init(failure_warning_message, failure_message_cont);
1077 create_app_running_mutex();
1080 /* Initialize the version information. */
1081 ws_init_version_info("Editcap (Wireshark)", NULL, NULL, NULL);
1084 * Get credential information for later use.
1086 init_process_policies();
1089 * Attempt to get the pathname of the directory containing the
1092 init_progfile_dir_error = init_progfile_dir(argv[0]);
1093 if (init_progfile_dir_error != NULL) {
1095 "editcap: Can't get pathname of directory containing the editcap program: %s.\n",
1096 init_progfile_dir_error);
1097 g_free(init_progfile_dir_error);
1100 init_report_message(failure_warning_message, failure_warning_message,
1105 /* Process the options */
1106 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) {
1108 case LONGOPT_NO_VLAN:
1114 case LONGOPT_SKIP_RADIOTAP_HEADER:
1116 skip_radiotap = TRUE;
1122 if (sscanf(optarg, "%u", &seed) != 1) {
1123 fprintf(stderr, "editcap: \"%s\" isn't a valid seed\n\n",
1125 ret = INVALID_OPTION;
1132 case LONGOPT_INJECT_SECRETS:
1134 guint32 secrets_type_id = 0;
1135 const char *secrets_filename = NULL;
1136 if (strcmp("help", optarg) == 0) {
1137 list_secrets_types(stdout);
1140 gchar **splitted = g_strsplit(optarg, ",", 2);
1141 if (splitted[0] && splitted[0][0] != '\0') {
1142 secrets_type_id = lookup_secrets_type(splitted[0]);
1143 if (secrets_type_id == 0) {
1144 fprintf(stderr, "editcap: \"%s\" isn't a valid secrets type\n", splitted[0]);
1145 g_strfreev(splitted);
1146 ret = INVALID_OPTION;
1149 secrets_filename = splitted[1];
1151 fprintf(stderr, "editcap: no secrets type was specified for --inject-secrets\n");
1152 g_strfreev(splitted);
1153 ret = INVALID_OPTION;
1156 if (!dsb_filenames) {
1157 dsb_types = g_array_new(FALSE, FALSE, sizeof(guint32));
1158 dsb_filenames = g_ptr_array_new_with_free_func(g_free);
1160 g_array_append_val(dsb_types, secrets_type_id);
1161 g_ptr_array_add(dsb_filenames, g_strdup(secrets_filename));
1162 g_strfreev(splitted);
1166 case LONGOPT_DISCARD_ALL_SECRETS:
1168 discard_all_secrets = TRUE;
1175 gint string_start_index = 0;
1177 if ((sscanf(optarg, "%u:%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1178 fprintf(stderr, "editcap: \"%s\" isn't a valid <frame>:<comment>\n\n",
1180 ret = INVALID_OPTION;
1184 /* Lazily create the table */
1185 if (!frames_user_comments) {
1186 frames_user_comments = g_tree_new_full(framenum_compare, NULL, NULL, g_free);
1189 /* Insert this entry (framenum -> comment) */
1190 g_tree_replace(frames_user_comments, GUINT_TO_POINTER(frame_number), g_strdup(optarg+string_start_index));
1198 memset(&starttm,0,sizeof(struct tm));
1200 if (!strptime(optarg,"%Y-%m-%d %T", &starttm)) {
1201 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1203 ret = INVALID_OPTION;
1207 check_startstop = TRUE;
1208 starttm.tm_isdst = -1;
1210 starttime = mktime(&starttm);
1218 memset(&stoptm,0,sizeof(struct tm));
1220 if (!strptime(optarg,"%Y-%m-%d %T", &stoptm)) {
1221 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1223 ret = INVALID_OPTION;
1226 check_startstop = TRUE;
1227 stoptm.tm_isdst = -1;
1228 stoptime = mktime(&stoptm);
1233 split_packet_count = get_nonzero_guint32(optarg, "packet count");
1238 int choplen = 0, chopoff = 0;
1240 switch (sscanf(optarg, "%d:%d", &chopoff, &choplen)) {
1241 case 1: /* only the chop length was specififed */
1246 case 2: /* both an offset and chop length was specified */
1250 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length or offset:length\n",
1252 ret = INVALID_OPTION;
1258 chop.len_begin += choplen;
1260 chop.off_begin_pos += chopoff;
1262 chop.off_begin_neg += chopoff;
1263 } else if (choplen < 0) {
1264 chop.len_end += choplen;
1266 chop.off_end_pos += chopoff;
1268 chop.off_end_neg += chopoff;
1275 dup_detect_by_time = FALSE;
1276 dup_window = DEFAULT_DUP_DEPTH;
1281 dup_detect_by_time = FALSE;
1282 dup_window = get_guint32(optarg, "duplicate window");
1283 if (dup_window > MAX_DUP_DEPTH) {
1284 fprintf(stderr, "editcap: \"%d\" duplicate window value must be between 0 and %d inclusive.\n",
1285 dup_window, MAX_DUP_DEPTH);
1286 ret = INVALID_OPTION;
1292 err_prob = g_ascii_strtod(optarg, &p);
1293 if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
1294 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
1296 ret = INVALID_OPTION;
1302 out_file_type_subtype = wtap_short_string_to_file_type_subtype(optarg);
1303 if (out_file_type_subtype < 0) {
1304 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
1306 list_capture_types(stderr);
1307 ret = INVALID_OPTION;
1313 show_help_header("Edit and/or translate the format of capture files.");
1314 print_usage(stdout);
1318 case 'i': /* break capture file based on time interval */
1320 double spb = get_positive_double(optarg, "time interval");
1322 cmdarg_err("The specified interval is zero");
1323 ret = INVALID_OPTION;
1327 double spb_int, spb_frac;
1328 spb_frac = modf(spb, &spb_int);
1329 secs_per_block.secs = (time_t) spb_int;
1330 secs_per_block.nsecs = (int) (NANOSECS_PER_SEC * spb_frac);
1334 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1335 ignored_bytes = get_guint32(optarg, "number of bytes to ignore");
1343 change_offset = get_guint32(optarg, "change offset");
1347 keep_em = !keep_em; /* Just invert */
1351 snaplen = get_nonzero_guint32(optarg, "snapshot length");
1355 if (!set_strict_time_adj(optarg)) {
1356 ret = INVALID_OPTION;
1359 do_strict_time_adjustment = TRUE;
1363 if (!set_time_adjustment(optarg)) {
1364 ret = INVALID_OPTION;
1370 out_frame_type = wtap_name_to_encap(optarg);
1371 if (out_frame_type < 0) {
1372 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
1374 list_encap_types(stderr);
1375 ret = INVALID_OPTION;
1381 verbose = !verbose; /* Just invert */
1391 dup_detect_by_time = TRUE;
1392 dup_window = MAX_DUP_DEPTH;
1393 if (!set_rel_time(optarg)) {
1394 ret = INVALID_OPTION;
1399 case '?': /* Bad options if GNU getopt */
1400 case ':': /* missing option argument */
1403 list_capture_types(stdout);
1406 list_encap_types(stdout);
1410 fprintf(stderr, "editcap: invalid option -- '%c'\n", optopt);
1412 fprintf(stderr, "editcap: option requires an argument -- '%c'\n", optopt);
1414 print_usage(stderr);
1415 ret = INVALID_OPTION;
1421 } /* processing commmand-line options */
1424 fprintf(stderr, "Optind = %i, argc = %i\n", optind, argc);
1427 if ((argc - optind) < 2) {
1428 print_usage(stderr);
1429 ret = INVALID_OPTION;
1434 if (err_prob >= 0.0) {
1436 seed = (unsigned int) (time(NULL) + ws_getpid());
1439 fprintf(stderr, "Using seed %u\n", seed);
1444 if (check_startstop && !stoptime) {
1447 /* XXX: will work until 2035 */
1448 memset(&stoptm,0,sizeof(struct tm));
1449 stoptm.tm_year = 135;
1450 stoptm.tm_mday = 31;
1452 stoptm.tm_isdst = -1;
1454 stoptime = mktime(&stoptm);
1457 if (starttime > stoptime) {
1458 fprintf(stderr, "editcap: start time is after the stop time\n");
1459 ret = INVALID_OPTION;
1463 if (split_packet_count != 0 && !nstime_is_unset(&secs_per_block)) {
1464 fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
1465 fprintf(stderr, "editcap: at the same time\n");
1466 ret = INVALID_OPTION;
1470 wth = wtap_open_offline(argv[optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, FALSE);
1473 cfile_open_failure_message("editcap", argv[optind], read_err,
1480 fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
1481 wtap_file_type_subtype_string(wtap_file_type_subtype(wth)));
1484 if (ignored_bytes != 0 && skip_radiotap == TRUE) {
1485 fprintf(stderr, "editcap: can't skip radiotap headers and %d byte(s)\n", ignored_bytes);
1486 fprintf(stderr, "editcap: at the start of packet at the same time\n");
1487 ret = INVALID_OPTION;
1491 if (skip_radiotap == TRUE && wtap_file_encap(wth) != WTAP_ENCAP_IEEE_802_11_RADIOTAP) {
1492 fprintf(stderr, "editcap: can't skip radiotap header because input file is incorrect\n");
1493 fprintf(stderr, "editcap: expected '%s', input is '%s'\n",
1494 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP),
1495 wtap_encap_description(wtap_file_type_subtype(wth)));
1496 ret = INVALID_OPTION;
1500 wtap_dump_params_init(¶ms, wth);
1503 * Discard any secrets we read in while opening the file.
1505 if (discard_all_secrets) {
1506 wtap_dump_params_discard_decryption_secrets(¶ms);
1509 if (dsb_filenames) {
1510 for (guint k = 0; k < dsb_filenames->len; k++) {
1511 guint32 secrets_type_id = g_array_index(dsb_types, guint32, k);
1512 const char *secrets_filename = (const char *)g_ptr_array_index(dsb_filenames, k);
1516 wtapng_dsb_mandatory_t *dsb;
1519 if (!g_file_get_contents(secrets_filename, &data, &data_len, &err)) {
1520 fprintf(stderr, "editcap: \"%s\" could not be read: %s\n", secrets_filename, err->message);
1521 g_clear_error(&err);
1522 ret = INVALID_OPTION;
1525 if (data_len == 0) {
1526 fprintf(stderr, "editcap: \"%s\" is an empty file, ignoring\n", secrets_filename);
1530 if (data_len >= G_MAXINT) {
1531 fprintf(stderr, "editcap: \"%s\" is too large, ignoring\n", secrets_filename);
1536 /* Warn for badly formatted files, but proceed anyway. */
1537 validate_secrets_file(secrets_filename, secrets_type_id, data);
1539 block = wtap_block_create(WTAP_BLOCK_DSB);
1540 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(block);
1541 dsb->secrets_type = secrets_type_id;
1542 dsb->secrets_len = (guint)data_len;
1543 dsb->secrets_data = data;
1544 if (params.dsbs_initial == NULL) {
1545 params.dsbs_initial = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
1547 g_array_append_val(params.dsbs_initial, block);
1552 * If an encapsulation type was specified, override the encapsulation
1553 * type of the input file.
1555 if (out_frame_type != -2)
1556 params.encap = out_frame_type;
1559 * If a snapshot length was specified, and it's less than the snapshot
1560 * length of the input file, override the snapshot length of the input
1563 if (snaplen != 0 && snaplen < wtap_snapshot_length(wth))
1564 params.snaplen = snaplen;
1567 * Now process the arguments following the input and output file
1568 * names, if any; they specify packets to include/exclude.
1570 for (i = optind + 2; i < argc; i++)
1571 if (add_selection(argv[i], &max_packet_number) == FALSE)
1574 if (keep_em == FALSE)
1575 max_packet_number = G_MAXUINT;
1577 if (dup_detect || dup_detect_by_time) {
1578 for (i = 0; i < dup_window; i++) {
1579 memset(&fd_hash[i].digest, 0, 16);
1581 nstime_set_unset(&fd_hash[i].frame_time);
1585 /* Read all of the packets in turn */
1586 wtap_rec_init(&read_rec);
1587 ws_buffer_init(&read_buf, 1514);
1588 while (wtap_read(wth, &read_rec, &read_buf, &read_err, &read_err_info, &data_offset)) {
1589 if (max_packet_number <= read_count)
1596 /* Extra actions for the first packet */
1597 if (read_count == 1) {
1598 if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
1599 if (!fileset_extract_prefix_suffix(argv[optind+1], &fprefix, &fsuffix)) {
1600 ret = CANT_EXTRACT_PREFIX;
1604 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1606 filename = g_strdup(argv[optind+1]);
1610 /* If we don't have an application name add one */
1611 if (wtap_block_get_string_option_value(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
1612 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
1615 pdh = editcap_dump_open(filename, ¶ms, &write_err);
1618 cfile_dump_open_failure_message("editcap", filename,
1620 out_file_type_subtype);
1624 } /* first packet only handling */
1627 buf = ws_buffer_start_ptr(&read_buf);
1630 * Not all packets have time stamps. Only process the time
1631 * stamp if we have one.
1633 if (rec->presence_flags & WTAP_HAS_TS) {
1634 if (!nstime_is_unset(&secs_per_block)) {
1635 if (nstime_is_unset(&block_next)) {
1636 block_next = rec->ts;
1637 nstime_add(&block_next, &secs_per_block);
1639 while (nstime_cmp(&rec->ts, &block_next) > 0) { /* time for the next file */
1641 if (!wtap_dump_close(pdh, &write_err)) {
1642 cfile_close_failure_message(filename, write_err);
1646 nstime_add(&block_next, &secs_per_block); /* reset for next interval */
1648 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1652 fprintf(stderr, "Continuing writing in file %s\n", filename);
1654 pdh = editcap_dump_open(filename, ¶ms, &write_err);
1657 cfile_dump_open_failure_message("editcap", filename,
1659 out_file_type_subtype);
1665 } /* time stamp handling */
1667 if (split_packet_count != 0) {
1668 /* time for the next file? */
1669 if (written_count > 0 && (written_count % split_packet_count) == 0) {
1670 if (!wtap_dump_close(pdh, &write_err)) {
1671 cfile_close_failure_message(filename, write_err);
1677 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1681 fprintf(stderr, "Continuing writing in file %s\n", filename);
1683 pdh = editcap_dump_open(filename, ¶ms, &write_err);
1685 cfile_dump_open_failure_message("editcap", filename,
1687 out_file_type_subtype);
1692 } /* split packet handling */
1694 if (check_startstop) {
1696 * Is the packet in the selected timeframe?
1697 * If the packet has no time stamp, the answer is "no".
1699 if (rec->presence_flags & WTAP_HAS_TS)
1700 ts_okay = (rec->ts.secs >= starttime) && (rec->ts.secs < stoptime);
1705 * No selected timeframe, so all packets are "in the
1706 * selected timeframe".
1711 if (ts_okay && ((!selected(count) && !keep_em)
1712 || (selected(count) && keep_em))) {
1714 if (verbose && !dup_detect && !dup_detect_by_time)
1715 fprintf(stderr, "Packet: %u\n", count);
1717 /* We simply write it, perhaps after truncating it; we could
1718 * do other things, like modify it. */
1722 if (rec->presence_flags & WTAP_HAS_TS) {
1723 /* Do we adjust timestamps to ensure strict chronological
1725 if (do_strict_time_adjustment) {
1726 if (previous_time.secs || previous_time.nsecs) {
1727 if (!strict_time_adj.is_negative) {
1733 nstime_delta(&delta, ¤t, &previous_time);
1735 if (delta.secs < 0 || delta.nsecs < 0) {
1737 * A negative delta indicates that the current packet
1738 * has an absolute timestamp less than the previous packet
1739 * that it is being compared to. This is NOT a normal
1740 * situation since trace files usually have packets in
1741 * chronological order (oldest to newest).
1742 * Copy and change rather than modify
1745 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
1747 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1748 temp_rec.ts.nsecs = previous_time.nsecs;
1749 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1752 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1754 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1760 * A negative strict time adjustment is requested.
1761 * Unconditionally set each timestamp to previous
1762 * packet's timestamp plus delta.
1763 * Copy and change rather than modify returned
1767 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1768 temp_rec.ts.nsecs = previous_time.nsecs;
1769 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1772 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1774 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1779 previous_time = rec->ts;
1782 if (time_adj.tv.secs != 0) {
1783 /* Copy and change rather than modify returned rec */
1785 if (time_adj.is_negative)
1786 temp_rec.ts.secs -= time_adj.tv.secs;
1788 temp_rec.ts.secs += time_adj.tv.secs;
1792 if (time_adj.tv.nsecs != 0) {
1793 /* Copy and change rather than modify returned rec */
1795 if (time_adj.is_negative) { /* subtract */
1796 if (temp_rec.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
1798 temp_rec.ts.nsecs += ONE_BILLION;
1800 temp_rec.ts.nsecs -= time_adj.tv.nsecs;
1802 if (temp_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
1805 temp_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
1807 temp_rec.ts.nsecs += time_adj.tv.nsecs;
1812 } /* time stamp adjustment */
1814 if (rec->rec_type == REC_TYPE_PACKET) {
1816 /* Limit capture length to snaplen */
1817 if (rec->rec_header.packet_header.caplen > snaplen) {
1818 /* Copy and change rather than modify returned wtap_rec */
1820 temp_rec.rec_header.packet_header.caplen = snaplen;
1823 /* If -L, also set reported length to snaplen */
1824 if (adjlen && rec->rec_header.packet_header.len > snaplen) {
1825 /* Copy and change rather than modify returned phdr */
1827 temp_rec.rec_header.packet_header.len = snaplen;
1833 * If an encapsulation type was specified, override the
1834 * encapsulation type of the packet.
1835 * Copy and change rather than modify returned rec.
1837 if (out_frame_type != -2) {
1839 temp_rec.rec_header.packet_header.pkt_encap = out_frame_type;
1845 * Copy and change rather than modify returned rec.
1848 handle_chopping(chop, &temp_rec.rec_header.packet_header,
1849 &rec->rec_header.packet_header, &buf,
1853 /* remove vlan info */
1855 /* Copy and change rather than modify returned rec */
1857 remove_vlan_info(&rec->rec_header.packet_header, buf,
1858 &temp_rec.rec_header.packet_header.caplen);
1862 /* suppress duplicates by packet window */
1864 if (is_duplicate(buf, rec->rec_header.packet_header.caplen)) {
1866 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1868 rec->rec_header.packet_header.caplen);
1869 for (i = 0; i < 16; i++)
1870 fprintf(stderr, "%02x",
1871 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1872 fprintf(stderr, "\n");
1879 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1881 rec->rec_header.packet_header.caplen);
1882 for (i = 0; i < 16; i++)
1883 fprintf(stderr, "%02x",
1884 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1885 fprintf(stderr, "\n");
1888 } /* suppression of duplicates */
1890 if (rec->presence_flags & WTAP_HAS_TS) {
1891 /* suppress duplicates by time window */
1892 if (dup_detect_by_time) {
1895 current.secs = rec->ts.secs;
1896 current.nsecs = rec->ts.nsecs;
1898 if (is_duplicate_rel_time(buf,
1899 rec->rec_header.packet_header.caplen,
1902 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1904 rec->rec_header.packet_header.caplen);
1905 for (i = 0; i < 16; i++)
1906 fprintf(stderr, "%02x",
1907 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1908 fprintf(stderr, "\n");
1915 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1917 rec->rec_header.packet_header.caplen);
1918 for (i = 0; i < 16; i++)
1919 fprintf(stderr, "%02x",
1920 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1921 fprintf(stderr, "\n");
1925 } /* suppress duplicates by time window */
1928 /* Random error mutation */
1929 do_mutation = FALSE;
1931 if (err_prob > 0.0) {
1932 switch (rec->rec_type) {
1934 case REC_TYPE_PACKET:
1935 caplen = rec->rec_header.packet_header.caplen;
1939 case REC_TYPE_FT_SPECIFIC_EVENT:
1940 case REC_TYPE_FT_SPECIFIC_REPORT:
1941 caplen = rec->rec_header.ft_specific_header.record_len;
1945 case REC_TYPE_SYSCALL:
1946 caplen = rec->rec_header.syscall_header.event_filelen;
1951 if (change_offset > caplen) {
1952 fprintf(stderr, "change offset %u is longer than caplen %u in packet %u\n",
1953 change_offset, caplen, count);
1954 do_mutation = FALSE;
1959 int real_data_start = 0;
1961 /* Protect non-protocol data */
1962 switch (rec->rec_type) {
1964 case REC_TYPE_PACKET:
1965 if (wtap_file_type_subtype(wth) == WTAP_FILE_TYPE_SUBTYPE_CATAPULT_DCT2000)
1966 real_data_start = find_dct2000_real_data(buf);
1970 real_data_start += change_offset;
1972 for (i = real_data_start; i < (int) caplen; i++) {
1973 if (rand() <= err_prob * RAND_MAX) {
1974 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
1976 if (err_type < ERR_WT_BIT) {
1977 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
1978 err_type = ERR_WT_TOTAL;
1980 err_type -= ERR_WT_BYTE;
1983 if (err_type < ERR_WT_BYTE) {
1984 buf[i] = rand() / (RAND_MAX / 255 + 1);
1985 err_type = ERR_WT_TOTAL;
1987 err_type -= ERR_WT_BYTE;
1990 if (err_type < ERR_WT_ALNUM) {
1991 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
1992 err_type = ERR_WT_TOTAL;
1994 err_type -= ERR_WT_ALNUM;
1997 if (err_type < ERR_WT_FMT) {
1998 if ((unsigned int)i < caplen - 2)
1999 g_strlcpy((char*) &buf[i], "%s", 2);
2000 err_type = ERR_WT_TOTAL;
2002 err_type -= ERR_WT_FMT;
2005 if (err_type < ERR_WT_AA) {
2006 for (j = i; j < (int) caplen; j++)
2012 } /* random error mutation */
2014 /* Find a packet comment we may need to write */
2015 if (frames_user_comments) {
2016 const char *comment =
2017 (const char*)g_tree_lookup(frames_user_comments, GUINT_TO_POINTER(read_count));
2018 /* XXX: What about comment changed to no comment? */
2019 if (comment != NULL) {
2020 /* Copy and change rather than modify returned rec */
2022 /* The comment is not modified by dumper, cast away. */
2023 temp_rec.opt_comment = (char *)comment;
2024 temp_rec.has_comment_changed = TRUE;
2027 /* Copy and change rather than modify returned rec */
2029 temp_rec.has_comment_changed = FALSE;
2034 if (discard_all_secrets) {
2036 * Discard any secrets we've read since the last packet
2039 wtap_dump_discard_decryption_secrets(pdh);
2042 /* Attempt to dump out current frame to the output file */
2043 if (!wtap_dump(pdh, rec, buf, &write_err, &write_err_info)) {
2044 cfile_write_failure_message("editcap", argv[optind],
2046 write_err, write_err_info,
2048 out_file_type_subtype);
2056 wtap_rec_cleanup(&read_rec);
2057 ws_buffer_free(&read_buf);
2062 if (read_err != 0) {
2063 /* Print a message noting that the read failed somewhere along the
2065 cfile_read_failure_message("editcap", argv[optind], read_err,
2070 /* No valid packages found, open the outfile so we can write an
2073 filename = g_strdup(argv[optind+1]);
2075 pdh = editcap_dump_open(filename, ¶ms, &write_err);
2077 cfile_dump_open_failure_message("editcap", filename,
2079 out_file_type_subtype);
2085 if (!wtap_dump_close(pdh, &write_err)) {
2086 cfile_close_failure_message(filename, write_err);
2092 if (frames_user_comments) {
2093 g_tree_destroy(frames_user_comments);
2097 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate window of %i packets.\n",
2098 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2099 plurality(duplicate_count, "", "s"), dup_window);
2100 } else if (dup_detect_by_time) {
2101 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2102 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2103 plurality(duplicate_count, "", "s"),
2104 (long)relative_time_window.secs,
2105 (long int)relative_time_window.nsecs);
2109 if (dsb_filenames) {
2110 g_array_free(dsb_types, TRUE);
2111 g_ptr_array_free(dsb_filenames, TRUE);
2113 g_free(params.idb_inf);
2114 wtap_dump_params_cleanup(¶ms);
2122 /* Skip meta-information read from file to return offset of real
2125 find_dct2000_real_data(guint8 *buf)
2129 for (n = 0; buf[n] != '\0'; n++); /* Context name */
2131 n++; /* Context port number */
2132 for (; buf[n] != '\0'; n++); /* Timestamp */
2134 for (; buf[n] != '\0'; n++); /* Protocol name */
2136 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
2138 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
2140 n += 2; /* Direction & encap */
2146 * We support up to 2 chopping regions in a single pass: one specified by the
2147 * positive chop length, and one by the negative chop length.
2150 handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
2151 const wtap_packet_header *in_phdr, guint8 **buf,
2154 /* If we're not chopping anything from one side, then the offset for that
2155 * side is meaningless. */
2156 if (chop.len_begin == 0)
2157 chop.off_begin_pos = chop.off_begin_neg = 0;
2158 if (chop.len_end == 0)
2159 chop.off_end_pos = chop.off_end_neg = 0;
2161 if (chop.off_begin_neg < 0) {
2162 chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
2163 chop.off_begin_neg = 0;
2165 if (chop.off_end_pos > 0) {
2166 chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
2167 chop.off_end_pos = 0;
2170 /* If we've crossed chopping regions, swap them */
2171 if (chop.len_begin && chop.len_end) {
2172 if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
2173 int tmp_len, tmp_off;
2175 tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
2176 tmp_len = -chop.len_end;
2178 chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
2179 chop.len_end = -chop.len_begin;
2181 chop.len_begin = tmp_len;
2182 chop.off_begin_pos = tmp_off;
2186 /* Make sure we don't chop off more than we have available */
2187 if (in_phdr->caplen < (guint32)(chop.off_begin_pos - chop.off_end_neg)) {
2191 if ((guint32)(chop.len_begin - chop.len_end) >
2192 (in_phdr->caplen - (guint32)(chop.off_begin_pos - chop.off_end_neg))) {
2193 chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
2197 /* Handle chopping from the beginning. Note that if a beginning offset
2198 * was specified, we need to keep that piece */
2199 if (chop.len_begin > 0) {
2200 *out_phdr = *in_phdr;
2202 if (chop.off_begin_pos > 0) {
2203 memmove(*buf + chop.off_begin_pos,
2204 *buf + chop.off_begin_pos + chop.len_begin,
2205 out_phdr->caplen - chop.len_begin);
2207 *buf += chop.len_begin;
2209 out_phdr->caplen -= chop.len_begin;
2212 if (in_phdr->len > (guint32)chop.len_begin)
2213 out_phdr->len -= chop.len_begin;
2220 /* Handle chopping from the end. Note that if an ending offset was
2221 * specified, we need to keep that piece */
2222 if (chop.len_end < 0) {
2223 *out_phdr = *in_phdr;
2225 if (chop.off_end_neg < 0) {
2226 memmove(*buf + (gint)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2227 *buf + (gint)out_phdr->caplen + chop.off_end_neg,
2230 out_phdr->caplen += chop.len_end;
2233 if (((signed int) in_phdr->len + chop.len_end) > 0)
2234 out_phdr->len += chop.len_end;
2238 /*in_phdr = out_phdr;*/
2243 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2248 * indent-tabs-mode: nil
2251 * vi: set shiftwidth=4 tabstop=8 expandtab:
2252 * :indentSize=4:tabSize=8:noTabs=true: