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;
1020 #define LONGOPT_NO_VLAN 0x8100
1021 #define LONGOPT_SKIP_RADIOTAP_HEADER 0x8101
1022 #define LONGOPT_SEED 0x8102
1023 #define LONGOPT_INJECT_SECRETS 0x8103
1024 #define LONGOPT_DISCARD_ALL_SECRETS 0x8104
1025 static const struct option long_options[] = {
1026 {"novlan", no_argument, NULL, LONGOPT_NO_VLAN},
1027 {"skip-radiotap-header", no_argument, NULL, LONGOPT_SKIP_RADIOTAP_HEADER},
1028 {"seed", required_argument, NULL, LONGOPT_SEED},
1029 {"inject-secrets", required_argument, NULL, LONGOPT_INJECT_SECRETS},
1030 {"discard-all-secrets", no_argument, NULL, LONGOPT_DISCARD_ALL_SECRETS},
1031 {"help", no_argument, NULL, 'h'},
1032 {"version", no_argument, NULL, 'V'},
1037 guint32 snaplen = 0; /* No limit */
1038 chop_t chop = {0, 0, 0, 0, 0, 0}; /* No chop */
1039 gboolean adjlen = FALSE;
1040 wtap_dumper *pdh = NULL;
1041 unsigned int count = 1;
1042 unsigned int duplicate_count = 0;
1046 guint32 read_count = 0;
1047 guint32 split_packet_count = 0;
1048 int written_count = 0;
1049 char *filename = NULL;
1051 nstime_t secs_per_block = NSTIME_INIT_UNSET;
1053 nstime_t block_next = NSTIME_INIT_UNSET;
1054 gchar *fprefix = NULL;
1055 gchar *fsuffix = NULL;
1056 guint32 change_offset = 0;
1057 guint max_packet_number = 0;
1058 GArray *dsb_types = NULL;
1059 GPtrArray *dsb_filenames = NULL;
1062 const wtap_rec *rec;
1064 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
1065 char *shb_user_appl;
1066 gboolean do_mutation;
1068 int ret = EXIT_SUCCESS;
1069 gboolean valid_seed = FALSE;
1070 unsigned int seed = 0;
1072 cmdarg_err_init(failure_warning_message, failure_message_cont);
1075 create_app_running_mutex();
1078 /* Initialize the version information. */
1079 ws_init_version_info("Editcap (Wireshark)", NULL, NULL, NULL);
1082 * Get credential information for later use.
1084 init_process_policies();
1087 * Attempt to get the pathname of the directory containing the
1090 init_progfile_dir_error = init_progfile_dir(argv[0]);
1091 if (init_progfile_dir_error != NULL) {
1093 "editcap: Can't get pathname of directory containing the editcap program: %s.\n",
1094 init_progfile_dir_error);
1095 g_free(init_progfile_dir_error);
1098 init_report_message(failure_warning_message, failure_warning_message,
1103 /* Process the options */
1104 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) {
1106 case LONGOPT_NO_VLAN:
1112 case LONGOPT_SKIP_RADIOTAP_HEADER:
1114 skip_radiotap = TRUE;
1120 if (sscanf(optarg, "%u", &seed) != 1) {
1121 fprintf(stderr, "editcap: \"%s\" isn't a valid seed\n\n",
1123 ret = INVALID_OPTION;
1130 case LONGOPT_INJECT_SECRETS:
1132 guint32 secrets_type_id = 0;
1133 const char *secrets_filename = NULL;
1134 if (strcmp("help", optarg) == 0) {
1135 list_secrets_types(stdout);
1138 gchar **splitted = g_strsplit(optarg, ",", 2);
1139 if (splitted[0] && splitted[0][0] != '\0') {
1140 secrets_type_id = lookup_secrets_type(splitted[0]);
1141 if (secrets_type_id == 0) {
1142 fprintf(stderr, "editcap: \"%s\" isn't a valid secrets type\n", splitted[0]);
1143 g_strfreev(splitted);
1144 ret = INVALID_OPTION;
1147 secrets_filename = splitted[1];
1149 fprintf(stderr, "editcap: no secrets type was specified for --inject-secrets\n");
1150 g_strfreev(splitted);
1151 ret = INVALID_OPTION;
1154 if (!dsb_filenames) {
1155 dsb_types = g_array_new(FALSE, FALSE, sizeof(guint32));
1156 dsb_filenames = g_ptr_array_new_with_free_func(g_free);
1158 g_array_append_val(dsb_types, secrets_type_id);
1159 g_ptr_array_add(dsb_filenames, g_strdup(secrets_filename));
1160 g_strfreev(splitted);
1164 case LONGOPT_DISCARD_ALL_SECRETS:
1166 discard_all_secrets = TRUE;
1173 gint string_start_index = 0;
1175 if ((sscanf(optarg, "%u:%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1176 fprintf(stderr, "editcap: \"%s\" isn't a valid <frame>:<comment>\n\n",
1178 ret = INVALID_OPTION;
1182 /* Lazily create the table */
1183 if (!frames_user_comments) {
1184 frames_user_comments = g_tree_new_full(framenum_compare, NULL, NULL, g_free);
1187 /* Insert this entry (framenum -> comment) */
1188 g_tree_replace(frames_user_comments, GUINT_TO_POINTER(frame_number), g_strdup(optarg+string_start_index));
1196 memset(&starttm,0,sizeof(struct tm));
1198 if (!strptime(optarg,"%Y-%m-%d %T", &starttm)) {
1199 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1201 ret = INVALID_OPTION;
1205 check_startstop = TRUE;
1206 starttm.tm_isdst = -1;
1208 starttime = mktime(&starttm);
1216 memset(&stoptm,0,sizeof(struct tm));
1218 if (!strptime(optarg,"%Y-%m-%d %T", &stoptm)) {
1219 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1221 ret = INVALID_OPTION;
1224 check_startstop = TRUE;
1225 stoptm.tm_isdst = -1;
1226 stoptime = mktime(&stoptm);
1231 split_packet_count = get_nonzero_guint32(optarg, "packet count");
1236 int choplen = 0, chopoff = 0;
1238 switch (sscanf(optarg, "%d:%d", &chopoff, &choplen)) {
1239 case 1: /* only the chop length was specififed */
1244 case 2: /* both an offset and chop length was specified */
1248 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length or offset:length\n",
1250 ret = INVALID_OPTION;
1256 chop.len_begin += choplen;
1258 chop.off_begin_pos += chopoff;
1260 chop.off_begin_neg += chopoff;
1261 } else if (choplen < 0) {
1262 chop.len_end += choplen;
1264 chop.off_end_pos += chopoff;
1266 chop.off_end_neg += chopoff;
1273 dup_detect_by_time = FALSE;
1274 dup_window = DEFAULT_DUP_DEPTH;
1279 dup_detect_by_time = FALSE;
1280 dup_window = get_guint32(optarg, "duplicate window");
1281 if (dup_window > MAX_DUP_DEPTH) {
1282 fprintf(stderr, "editcap: \"%d\" duplicate window value must be between 0 and %d inclusive.\n",
1283 dup_window, MAX_DUP_DEPTH);
1284 ret = INVALID_OPTION;
1290 err_prob = g_ascii_strtod(optarg, &p);
1291 if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
1292 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
1294 ret = INVALID_OPTION;
1300 out_file_type_subtype = wtap_short_string_to_file_type_subtype(optarg);
1301 if (out_file_type_subtype < 0) {
1302 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
1304 list_capture_types(stderr);
1305 ret = INVALID_OPTION;
1311 show_help_header("Edit and/or translate the format of capture files.");
1312 print_usage(stdout);
1316 case 'i': /* break capture file based on time interval */
1318 double spb = get_positive_double(optarg, "time interval");
1320 cmdarg_err("The specified interval is zero");
1321 ret = INVALID_OPTION;
1325 double spb_int, spb_frac;
1326 spb_frac = modf(spb, &spb_int);
1327 secs_per_block.secs = (time_t) spb_int;
1328 secs_per_block.nsecs = (int) (NANOSECS_PER_SEC * spb_frac);
1332 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1333 ignored_bytes = get_guint32(optarg, "number of bytes to ignore");
1341 change_offset = get_guint32(optarg, "change offset");
1345 keep_em = !keep_em; /* Just invert */
1349 snaplen = get_nonzero_guint32(optarg, "snapshot length");
1353 if (!set_strict_time_adj(optarg)) {
1354 ret = INVALID_OPTION;
1357 do_strict_time_adjustment = TRUE;
1361 if (!set_time_adjustment(optarg)) {
1362 ret = INVALID_OPTION;
1368 out_frame_type = wtap_name_to_encap(optarg);
1369 if (out_frame_type < 0) {
1370 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
1372 list_encap_types(stderr);
1373 ret = INVALID_OPTION;
1379 verbose = !verbose; /* Just invert */
1389 dup_detect_by_time = TRUE;
1390 dup_window = MAX_DUP_DEPTH;
1391 if (!set_rel_time(optarg)) {
1392 ret = INVALID_OPTION;
1397 case '?': /* Bad options if GNU getopt */
1398 case ':': /* missing option argument */
1401 list_capture_types(stdout);
1404 list_encap_types(stdout);
1408 fprintf(stderr, "editcap: invalid option -- '%c'\n", optopt);
1410 fprintf(stderr, "editcap: option requires an argument -- '%c'\n", optopt);
1412 print_usage(stderr);
1413 ret = INVALID_OPTION;
1419 } /* processing commmand-line options */
1422 fprintf(stderr, "Optind = %i, argc = %i\n", optind, argc);
1425 if ((argc - optind) < 2) {
1426 print_usage(stderr);
1427 ret = INVALID_OPTION;
1432 if (err_prob >= 0.0) {
1434 seed = (unsigned int) (time(NULL) + ws_getpid());
1437 fprintf(stderr, "Using seed %u\n", seed);
1442 if (check_startstop && !stoptime) {
1445 /* XXX: will work until 2035 */
1446 memset(&stoptm,0,sizeof(struct tm));
1447 stoptm.tm_year = 135;
1448 stoptm.tm_mday = 31;
1450 stoptm.tm_isdst = -1;
1452 stoptime = mktime(&stoptm);
1455 if (starttime > stoptime) {
1456 fprintf(stderr, "editcap: start time is after the stop time\n");
1457 ret = INVALID_OPTION;
1461 if (split_packet_count != 0 && !nstime_is_unset(&secs_per_block)) {
1462 fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
1463 fprintf(stderr, "editcap: at the same time\n");
1464 ret = INVALID_OPTION;
1468 wth = wtap_open_offline(argv[optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, FALSE);
1471 cfile_open_failure_message("editcap", argv[optind], read_err,
1478 fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
1479 wtap_file_type_subtype_string(wtap_file_type_subtype(wth)));
1482 if (ignored_bytes != 0 && skip_radiotap == TRUE) {
1483 fprintf(stderr, "editcap: can't skip radiotap headers and %d byte(s)\n", ignored_bytes);
1484 fprintf(stderr, "editcap: at the start of packet at the same time\n");
1485 ret = INVALID_OPTION;
1489 if (skip_radiotap == TRUE && wtap_file_encap(wth) != WTAP_ENCAP_IEEE_802_11_RADIOTAP) {
1490 fprintf(stderr, "editcap: can't skip radiotap header because input file is incorrect\n");
1491 fprintf(stderr, "editcap: expected '%s', input is '%s'\n",
1492 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP),
1493 wtap_encap_description(wtap_file_type_subtype(wth)));
1494 ret = INVALID_OPTION;
1498 wtap_dump_params_init(¶ms, wth);
1501 * Discard any secrets we read in while opening the file.
1503 if (discard_all_secrets) {
1504 wtap_dump_params_discard_decryption_secrets(¶ms);
1507 if (dsb_filenames) {
1508 for (guint k = 0; k < dsb_filenames->len; k++) {
1509 guint32 secrets_type_id = g_array_index(dsb_types, guint32, k);
1510 const char *secrets_filename = (const char *)g_ptr_array_index(dsb_filenames, k);
1514 wtapng_dsb_mandatory_t *dsb;
1517 if (!g_file_get_contents(secrets_filename, &data, &data_len, &err)) {
1518 fprintf(stderr, "editcap: \"%s\" could not be read: %s\n", secrets_filename, err->message);
1519 g_clear_error(&err);
1520 ret = INVALID_OPTION;
1523 if (data_len == 0) {
1524 fprintf(stderr, "editcap: \"%s\" is an empty file, ignoring\n", secrets_filename);
1528 if (data_len >= G_MAXINT) {
1529 fprintf(stderr, "editcap: \"%s\" is too large, ignoring\n", secrets_filename);
1534 /* Warn for badly formatted files, but proceed anyway. */
1535 validate_secrets_file(secrets_filename, secrets_type_id, data);
1537 block = wtap_block_create(WTAP_BLOCK_DSB);
1538 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(block);
1539 dsb->secrets_type = secrets_type_id;
1540 dsb->secrets_len = (guint)data_len;
1541 dsb->secrets_data = data;
1542 if (params.dsbs_initial == NULL) {
1543 params.dsbs_initial = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
1545 g_array_append_val(params.dsbs_initial, block);
1550 * If an encapsulation type was specified, override the encapsulation
1551 * type of the input file.
1553 if (out_frame_type != -2)
1554 params.encap = out_frame_type;
1557 * If a snapshot length was specified, and it's less than the snapshot
1558 * length of the input file, override the snapshot length of the input
1561 if (snaplen != 0 && snaplen < wtap_snapshot_length(wth))
1562 params.snaplen = snaplen;
1565 * Now process the arguments following the input and output file
1566 * names, if any; they specify packets to include/exclude.
1568 for (i = optind + 2; i < argc; i++)
1569 if (add_selection(argv[i], &max_packet_number) == FALSE)
1572 if (keep_em == FALSE)
1573 max_packet_number = G_MAXUINT;
1575 if (dup_detect || dup_detect_by_time) {
1576 for (i = 0; i < dup_window; i++) {
1577 memset(&fd_hash[i].digest, 0, 16);
1579 nstime_set_unset(&fd_hash[i].frame_time);
1583 /* Read all of the packets in turn */
1584 wtap_rec_init(&read_rec);
1585 ws_buffer_init(&read_buf, 1514);
1586 while (wtap_read(wth, &read_rec, &read_buf, &read_err, &read_err_info, &data_offset)) {
1587 if (max_packet_number <= read_count)
1594 /* Extra actions for the first packet */
1595 if (read_count == 1) {
1596 if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
1597 if (!fileset_extract_prefix_suffix(argv[optind+1], &fprefix, &fsuffix)) {
1598 ret = CANT_EXTRACT_PREFIX;
1602 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1604 filename = g_strdup(argv[optind+1]);
1608 /* If we don't have an application name add one */
1609 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) {
1610 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
1613 pdh = editcap_dump_open(filename, ¶ms, &write_err);
1616 cfile_dump_open_failure_message("editcap", filename,
1618 out_file_type_subtype);
1622 } /* first packet only handling */
1625 buf = ws_buffer_start_ptr(&read_buf);
1628 * Not all packets have time stamps. Only process the time
1629 * stamp if we have one.
1631 if (rec->presence_flags & WTAP_HAS_TS) {
1632 if (!nstime_is_unset(&secs_per_block)) {
1633 if (nstime_is_unset(&block_next)) {
1634 block_next = rec->ts;
1635 nstime_add(&block_next, &secs_per_block);
1637 while (nstime_cmp(&rec->ts, &block_next) > 0) { /* time for the next file */
1639 if (!wtap_dump_close(pdh, &write_err)) {
1640 cfile_close_failure_message(filename, write_err);
1644 nstime_add(&block_next, &secs_per_block); /* reset for next interval */
1646 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1650 fprintf(stderr, "Continuing writing in file %s\n", filename);
1652 pdh = editcap_dump_open(filename, ¶ms, &write_err);
1655 cfile_dump_open_failure_message("editcap", filename,
1657 out_file_type_subtype);
1663 } /* time stamp handling */
1665 if (split_packet_count != 0) {
1666 /* time for the next file? */
1667 if (written_count > 0 && (written_count % split_packet_count) == 0) {
1668 if (!wtap_dump_close(pdh, &write_err)) {
1669 cfile_close_failure_message(filename, write_err);
1675 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1679 fprintf(stderr, "Continuing writing in file %s\n", filename);
1681 pdh = editcap_dump_open(filename, ¶ms, &write_err);
1683 cfile_dump_open_failure_message("editcap", filename,
1685 out_file_type_subtype);
1690 } /* split packet handling */
1692 if (check_startstop) {
1694 * Is the packet in the selected timeframe?
1695 * If the packet has no time stamp, the answer is "no".
1697 if (rec->presence_flags & WTAP_HAS_TS)
1698 ts_okay = (rec->ts.secs >= starttime) && (rec->ts.secs < stoptime);
1703 * No selected timeframe, so all packets are "in the
1704 * selected timeframe".
1709 if (ts_okay && ((!selected(count) && !keep_em)
1710 || (selected(count) && keep_em))) {
1712 if (verbose && !dup_detect && !dup_detect_by_time)
1713 fprintf(stderr, "Packet: %u\n", count);
1715 /* We simply write it, perhaps after truncating it; we could
1716 * do other things, like modify it. */
1720 if (rec->presence_flags & WTAP_HAS_TS) {
1721 /* Do we adjust timestamps to ensure strict chronological
1723 if (do_strict_time_adjustment) {
1724 if (previous_time.secs || previous_time.nsecs) {
1725 if (!strict_time_adj.is_negative) {
1731 nstime_delta(&delta, ¤t, &previous_time);
1733 if (delta.secs < 0 || delta.nsecs < 0) {
1735 * A negative delta indicates that the current packet
1736 * has an absolute timestamp less than the previous packet
1737 * that it is being compared to. This is NOT a normal
1738 * situation since trace files usually have packets in
1739 * chronological order (oldest to newest).
1740 * Copy and change rather than modify
1743 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
1745 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1746 temp_rec.ts.nsecs = previous_time.nsecs;
1747 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1750 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1752 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1758 * A negative strict time adjustment is requested.
1759 * Unconditionally set each timestamp to previous
1760 * packet's timestamp plus delta.
1761 * Copy and change rather than modify returned
1765 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1766 temp_rec.ts.nsecs = previous_time.nsecs;
1767 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
1770 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1772 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
1777 previous_time = rec->ts;
1780 if (time_adj.tv.secs != 0) {
1781 /* Copy and change rather than modify returned rec */
1783 if (time_adj.is_negative)
1784 temp_rec.ts.secs -= time_adj.tv.secs;
1786 temp_rec.ts.secs += time_adj.tv.secs;
1790 if (time_adj.tv.nsecs != 0) {
1791 /* Copy and change rather than modify returned rec */
1793 if (time_adj.is_negative) { /* subtract */
1794 if (temp_rec.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
1796 temp_rec.ts.nsecs += ONE_BILLION;
1798 temp_rec.ts.nsecs -= time_adj.tv.nsecs;
1800 if (temp_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
1803 temp_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
1805 temp_rec.ts.nsecs += time_adj.tv.nsecs;
1810 } /* time stamp adjustment */
1812 if (rec->rec_type == REC_TYPE_PACKET) {
1814 /* Limit capture length to snaplen */
1815 if (rec->rec_header.packet_header.caplen > snaplen) {
1816 /* Copy and change rather than modify returned wtap_rec */
1818 temp_rec.rec_header.packet_header.caplen = snaplen;
1821 /* If -L, also set reported length to snaplen */
1822 if (adjlen && rec->rec_header.packet_header.len > snaplen) {
1823 /* Copy and change rather than modify returned phdr */
1825 temp_rec.rec_header.packet_header.len = snaplen;
1831 * If an encapsulation type was specified, override the
1832 * encapsulation type of the packet.
1833 * Copy and change rather than modify returned rec.
1835 if (out_frame_type != -2) {
1837 temp_rec.rec_header.packet_header.pkt_encap = out_frame_type;
1843 * Copy and change rather than modify returned rec.
1846 handle_chopping(chop, &temp_rec.rec_header.packet_header,
1847 &rec->rec_header.packet_header, &buf,
1851 /* remove vlan info */
1853 /* Copy and change rather than modify returned rec */
1855 remove_vlan_info(&rec->rec_header.packet_header, buf,
1856 &temp_rec.rec_header.packet_header.caplen);
1860 /* suppress duplicates by packet window */
1862 if (is_duplicate(buf, rec->rec_header.packet_header.caplen)) {
1864 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1866 rec->rec_header.packet_header.caplen);
1867 for (i = 0; i < 16; i++)
1868 fprintf(stderr, "%02x",
1869 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1870 fprintf(stderr, "\n");
1877 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1879 rec->rec_header.packet_header.caplen);
1880 for (i = 0; i < 16; i++)
1881 fprintf(stderr, "%02x",
1882 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1883 fprintf(stderr, "\n");
1886 } /* suppression of duplicates */
1888 if (rec->presence_flags & WTAP_HAS_TS) {
1889 /* suppress duplicates by time window */
1890 if (dup_detect_by_time) {
1893 current.secs = rec->ts.secs;
1894 current.nsecs = rec->ts.nsecs;
1896 if (is_duplicate_rel_time(buf,
1897 rec->rec_header.packet_header.caplen,
1900 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1902 rec->rec_header.packet_header.caplen);
1903 for (i = 0; i < 16; i++)
1904 fprintf(stderr, "%02x",
1905 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1906 fprintf(stderr, "\n");
1913 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1915 rec->rec_header.packet_header.caplen);
1916 for (i = 0; i < 16; i++)
1917 fprintf(stderr, "%02x",
1918 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1919 fprintf(stderr, "\n");
1923 } /* suppress duplicates by time window */
1926 /* Random error mutation */
1927 do_mutation = FALSE;
1929 if (err_prob > 0.0) {
1930 switch (rec->rec_type) {
1932 case REC_TYPE_PACKET:
1933 caplen = rec->rec_header.packet_header.caplen;
1937 case REC_TYPE_FT_SPECIFIC_EVENT:
1938 case REC_TYPE_FT_SPECIFIC_REPORT:
1939 caplen = rec->rec_header.ft_specific_header.record_len;
1943 case REC_TYPE_SYSCALL:
1944 caplen = rec->rec_header.syscall_header.event_filelen;
1949 if (change_offset > caplen) {
1950 fprintf(stderr, "change offset %u is longer than caplen %u in packet %u\n",
1951 change_offset, caplen, count);
1952 do_mutation = FALSE;
1957 int real_data_start = 0;
1959 /* Protect non-protocol data */
1960 switch (rec->rec_type) {
1962 case REC_TYPE_PACKET:
1963 if (wtap_file_type_subtype(wth) == WTAP_FILE_TYPE_SUBTYPE_CATAPULT_DCT2000)
1964 real_data_start = find_dct2000_real_data(buf);
1968 real_data_start += change_offset;
1970 for (i = real_data_start; i < (int) caplen; i++) {
1971 if (rand() <= err_prob * RAND_MAX) {
1972 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
1974 if (err_type < ERR_WT_BIT) {
1975 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
1976 err_type = ERR_WT_TOTAL;
1978 err_type -= ERR_WT_BYTE;
1981 if (err_type < ERR_WT_BYTE) {
1982 buf[i] = rand() / (RAND_MAX / 255 + 1);
1983 err_type = ERR_WT_TOTAL;
1985 err_type -= ERR_WT_BYTE;
1988 if (err_type < ERR_WT_ALNUM) {
1989 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
1990 err_type = ERR_WT_TOTAL;
1992 err_type -= ERR_WT_ALNUM;
1995 if (err_type < ERR_WT_FMT) {
1996 if ((unsigned int)i < caplen - 2)
1997 g_strlcpy((char*) &buf[i], "%s", 2);
1998 err_type = ERR_WT_TOTAL;
2000 err_type -= ERR_WT_FMT;
2003 if (err_type < ERR_WT_AA) {
2004 for (j = i; j < (int) caplen; j++)
2010 } /* random error mutation */
2012 /* Find a packet comment we may need to write */
2013 if (frames_user_comments) {
2014 const char *comment =
2015 (const char*)g_tree_lookup(frames_user_comments, GUINT_TO_POINTER(read_count));
2016 /* XXX: What about comment changed to no comment? */
2017 if (comment != NULL) {
2018 /* Copy and change rather than modify returned rec */
2020 /* The comment is not modified by dumper, cast away. */
2021 temp_rec.opt_comment = (char *)comment;
2022 temp_rec.has_comment_changed = TRUE;
2025 /* Copy and change rather than modify returned rec */
2027 temp_rec.has_comment_changed = FALSE;
2032 if (discard_all_secrets) {
2034 * Discard any secrets we've read since the last packet
2037 wtap_dump_discard_decryption_secrets(pdh);
2040 /* Attempt to dump out current frame to the output file */
2041 if (!wtap_dump(pdh, rec, buf, &write_err, &write_err_info)) {
2042 cfile_write_failure_message("editcap", argv[optind],
2044 write_err, write_err_info,
2046 out_file_type_subtype);
2054 wtap_rec_cleanup(&read_rec);
2055 ws_buffer_free(&read_buf);
2060 if (read_err != 0) {
2061 /* Print a message noting that the read failed somewhere along the
2063 cfile_read_failure_message("editcap", argv[optind], read_err,
2068 /* No valid packages found, open the outfile so we can write an
2071 filename = g_strdup(argv[optind+1]);
2073 pdh = editcap_dump_open(filename, ¶ms, &write_err);
2075 cfile_dump_open_failure_message("editcap", filename,
2077 out_file_type_subtype);
2083 if (!wtap_dump_close(pdh, &write_err)) {
2084 cfile_close_failure_message(filename, write_err);
2090 if (frames_user_comments) {
2091 g_tree_destroy(frames_user_comments);
2095 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate window of %i packets.\n",
2096 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2097 plurality(duplicate_count, "", "s"), dup_window);
2098 } else if (dup_detect_by_time) {
2099 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2100 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2101 plurality(duplicate_count, "", "s"),
2102 (long)relative_time_window.secs,
2103 (long int)relative_time_window.nsecs);
2107 if (dsb_filenames) {
2108 g_array_free(dsb_types, TRUE);
2109 g_ptr_array_free(dsb_filenames, TRUE);
2111 g_free(params.idb_inf);
2112 wtap_dump_params_cleanup(¶ms);
2120 /* Skip meta-information read from file to return offset of real
2123 find_dct2000_real_data(guint8 *buf)
2127 for (n = 0; buf[n] != '\0'; n++); /* Context name */
2129 n++; /* Context port number */
2130 for (; buf[n] != '\0'; n++); /* Timestamp */
2132 for (; buf[n] != '\0'; n++); /* Protocol name */
2134 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
2136 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
2138 n += 2; /* Direction & encap */
2144 * We support up to 2 chopping regions in a single pass: one specified by the
2145 * positive chop length, and one by the negative chop length.
2148 handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
2149 const wtap_packet_header *in_phdr, guint8 **buf,
2152 /* If we're not chopping anything from one side, then the offset for that
2153 * side is meaningless. */
2154 if (chop.len_begin == 0)
2155 chop.off_begin_pos = chop.off_begin_neg = 0;
2156 if (chop.len_end == 0)
2157 chop.off_end_pos = chop.off_end_neg = 0;
2159 if (chop.off_begin_neg < 0) {
2160 chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
2161 chop.off_begin_neg = 0;
2163 if (chop.off_end_pos > 0) {
2164 chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
2165 chop.off_end_pos = 0;
2168 /* If we've crossed chopping regions, swap them */
2169 if (chop.len_begin && chop.len_end) {
2170 if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
2171 int tmp_len, tmp_off;
2173 tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
2174 tmp_len = -chop.len_end;
2176 chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
2177 chop.len_end = -chop.len_begin;
2179 chop.len_begin = tmp_len;
2180 chop.off_begin_pos = tmp_off;
2184 /* Make sure we don't chop off more than we have available */
2185 if (in_phdr->caplen < (guint32)(chop.off_begin_pos - chop.off_end_neg)) {
2189 if ((guint32)(chop.len_begin - chop.len_end) >
2190 (in_phdr->caplen - (guint32)(chop.off_begin_pos - chop.off_end_neg))) {
2191 chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
2195 /* Handle chopping from the beginning. Note that if a beginning offset
2196 * was specified, we need to keep that piece */
2197 if (chop.len_begin > 0) {
2198 *out_phdr = *in_phdr;
2200 if (chop.off_begin_pos > 0) {
2201 memmove(*buf + chop.off_begin_pos,
2202 *buf + chop.off_begin_pos + chop.len_begin,
2203 out_phdr->caplen - chop.len_begin);
2205 *buf += chop.len_begin;
2207 out_phdr->caplen -= chop.len_begin;
2210 if (in_phdr->len > (guint32)chop.len_begin)
2211 out_phdr->len -= chop.len_begin;
2218 /* Handle chopping from the end. Note that if an ending offset was
2219 * specified, we need to keep that piece */
2220 if (chop.len_end < 0) {
2221 *out_phdr = *in_phdr;
2223 if (chop.off_end_neg < 0) {
2224 memmove(*buf + (gint)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2225 *buf + (gint)out_phdr->caplen + chop.off_end_neg,
2228 out_phdr->caplen += chop.len_end;
2231 if (((signed int) in_phdr->len + chop.len_end) > 0)
2232 out_phdr->len += chop.len_end;
2236 /*in_phdr = out_phdr;*/
2241 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2246 * indent-tabs-mode: nil
2249 * vi: set shiftwidth=4 tabstop=8 expandtab:
2250 * :indentSize=4:tabSize=8:noTabs=true: