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
19 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
36 #include <ws_exit_codes.h>
37 #include <wsutil/ws_getopt.h>
39 #include <wiretap/secrets-types.h>
40 #include <wiretap/wtap.h>
42 #include "epan/etypes.h"
43 #include "epan/dissectors/packet-ieee80211-radiotap-defs.h"
46 #include <process.h> /* getpid */
50 #include <wsutil/clopts_common.h>
51 #include <wsutil/cmdarg_err.h>
52 #include <wsutil/filesystem.h>
53 #include <wsutil/file_util.h>
54 #include <wsutil/plugins.h>
55 #include <wsutil/privileges.h>
56 #include <wsutil/report_message.h>
57 #include <wsutil/strnatcmp.h>
58 #include <wsutil/str_util.h>
60 #include <wsutil/version_info.h>
61 #include <wsutil/pint.h>
62 #include <wsutil/strtoi.h>
63 #include <wsutil/ws_assert.h>
64 #include <wsutil/wslog.h>
65 #include <wiretap/wtap_opttypes.h>
67 #include "ui/failure_message.h"
69 #include "ringbuffer.h" /* For RINGBUFFER_MAX_NUM_FILES */
71 /* Additional exit codes */
72 #define CANT_EXTRACT_PREFIX 2
76 #define NANOSECS_PER_SEC 1000000000
79 * Some globals so we can pass things to various routines
84 uint64_t first
, second
;
88 * Duplicate frame detection
90 typedef struct _fd_hash_t
{
96 #define DEFAULT_DUP_DEPTH 5 /* Used with -d */
97 #define MAX_DUP_DEPTH 1000000 /* the maximum window (and actual size of fd_hash[]) for de-duplication */
99 static fd_hash_t fd_hash
[MAX_DUP_DEPTH
];
100 static int dup_window
= DEFAULT_DUP_DEPTH
;
101 static int cur_dup_entry
;
103 static uint32_t ignored_bytes
; /* Used with -I */
105 #define ONE_BILLION 1000000000
107 /* Weights of different errors we can introduce */
108 /* We should probably make these command-line arguments */
109 /* XXX - Should we add a bit-level error? */
110 #define ERR_WT_BIT 5 /* Flip a random bit */
111 #define ERR_WT_BYTE 5 /* Substitute a random byte */
112 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
113 #define ERR_WT_FMT 2 /* Substitute "%s" */
114 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
115 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
117 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
118 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
120 struct time_adjustment
{
125 typedef struct _chop_t
{
135 /* Table of user comments */
136 GTree
*frames_user_comments
;
137 GPtrArray
*capture_comments
;
139 #define MAX_SELECTIONS 512
140 static struct select_item selectfrm
[MAX_SELECTIONS
];
141 static unsigned max_selected
;
143 static int out_file_type_subtype
= WTAP_FILE_TYPE_SUBTYPE_UNKNOWN
;
144 static int out_frame_type
= -2; /* Leave frame type alone */
145 static bool verbose
; /* Not so verbose */
146 static struct time_adjustment time_adj
; /* no adjustment */
147 static nstime_t relative_time_window
; /* de-dup time window */
148 static double err_prob
= -1.0;
149 static nstime_t starttime
;
150 static bool have_starttime
;
151 static nstime_t stoptime
;
152 static bool have_stoptime
;
153 static bool check_startstop
;
154 static bool rem_vlan
;
155 static bool dup_detect
;
156 static bool dup_detect_by_time
;
157 static bool skip_radiotap
;
158 static bool discard_all_secrets
;
159 static bool discard_cap_comments
;
160 static bool set_unused
;
161 static bool discard_pkt_comments
;
162 static bool do_extract_secrets
;
164 static int do_strict_time_adjustment
;
165 static struct time_adjustment strict_time_adj
; /* strict time adjustment */
166 static nstime_t previous_time
; /* previous time */
168 static const struct {
171 } secrets_types
[] = {
172 { "tls", SECRETS_TYPE_TLS
},
173 { "ssh", SECRETS_TYPE_SSH
},
174 { "wg", SECRETS_TYPE_WIREGUARD
},
175 { "opcua", SECRETS_TYPE_OPCUA
},
178 static int find_dct2000_real_data(uint8_t *buf
);
179 static void handle_chopping(chop_t chop
, wtap_packet_header
*out_phdr
,
180 const wtap_packet_header
*in_phdr
, uint8_t **buf
,
184 abs_time_to_str_with_sec_resolution(const nstime_t
*abs_time
)
187 char *buf
= (char *)g_malloc(16);
189 tmp
= localtime(&abs_time
->secs
);
192 snprintf(buf
, 16, "%d%02d%02d%02d%02d%02d",
207 fileset_get_filename_by_pattern(unsigned idx
, const wtap_rec
*rec
,
208 char *fprefix
, char *fsuffix
)
214 snprintf(filenum
, sizeof(filenum
), "%05u", idx
% RINGBUFFER_MAX_NUM_FILES
);
215 if (rec
&& rec
->presence_flags
& WTAP_HAS_TS
) {
216 timestr
= abs_time_to_str_with_sec_resolution(&rec
->ts
);
217 abs_str
= g_strconcat(fprefix
, "_", filenum
, "_", timestr
, fsuffix
, NULL
);
220 abs_str
= g_strconcat(fprefix
, "_", filenum
, fsuffix
, NULL
);
226 fileset_extract_prefix_suffix(const char *fname
, char **fprefix
, char **fsuffix
, wtap_compression_type
*compression_typep
)
228 char *pfx
, *last_pathsep
;
230 wtap_compression_type compression_type
;
232 save_file
= g_strdup(fname
);
233 if (save_file
== NULL
) {
234 fprintf(stderr
, "editcap: Out of memory\n");
238 last_pathsep
= strrchr(save_file
, G_DIR_SEPARATOR
);
239 if (last_pathsep
== NULL
) {
240 last_pathsep
= save_file
;
242 pfx
= strrchr(last_pathsep
, '.');
244 /* The pathname has a "." in it, and it's in the last component
245 * of the pathname (because there is either only one component,
246 * i.e. last_pathsep is null as there are no path separators,
247 * or the "." is after the path separator before the last
250 * Treat it as a separator between the rest of the file name and
251 * the file name suffix, and arrange that the names given to the
252 * ring buffer files have the specified suffix, i.e. put the
253 * changing part of the name *before* the suffix. */
255 compression_type
= wtap_extension_to_compression_type(pfx
+ 1);
256 if (compression_type
!= WTAP_UNKNOWN_COMPRESSION
) {
257 char *pfx2
= strrchr(last_pathsep
, '.');
263 if (compression_typep
&& *compression_typep
== WTAP_UNKNOWN_COMPRESSION
) {
264 *compression_typep
= compression_type
;
266 /* XXX - What if there's an extension matching a compression type
267 * and the passed in compression type is known but something else?
270 *fprefix
= g_strdup(save_file
);
271 pfx
[0] = '.'; /* restore capfile_name */
272 *fsuffix
= g_strdup(pfx
);
274 /* Either there's no "." in the pathname, or it's in a directory
275 * component, so the last component has no suffix. */
276 *fprefix
= g_strdup(save_file
);
283 /* Add a selection item, a simple parser for now */
285 add_selection(char *sel
, uint64_t* max_selection
)
290 if (max_selected
>= MAX_SELECTIONS
) {
291 /* Let the user know we stopped selecting */
292 fprintf(stderr
, "Out of room for packet selections.\n");
297 fprintf(stderr
, "Add_Selected: %s\n", sel
);
299 if ((locn
= strchr(sel
, '-')) == NULL
) { /* No dash, so a single number? */
301 fprintf(stderr
, "Not inclusive ...");
303 selectfrm
[max_selected
].inclusive
= false;
304 selectfrm
[max_selected
].first
= get_uint64(sel
, "packet number");
305 if (selectfrm
[max_selected
].first
> *max_selection
)
306 *max_selection
= selectfrm
[max_selected
].first
;
309 fprintf(stderr
, " %" PRIu64
"\n", selectfrm
[max_selected
].first
);
312 fprintf(stderr
, "Inclusive ...");
314 *locn
= '\0'; /* split the range */
316 selectfrm
[max_selected
].inclusive
= true;
317 selectfrm
[max_selected
].first
= get_uint64(sel
, "beginning of packet range");
318 selectfrm
[max_selected
].second
= get_uint64(next
, "end of packet range");
320 if (selectfrm
[max_selected
].second
== 0)
322 /* Not a valid number, presume all */
323 selectfrm
[max_selected
].second
= *max_selection
= UINT64_MAX
;
325 else if (selectfrm
[max_selected
].second
> *max_selection
)
326 *max_selection
= selectfrm
[max_selected
].second
;
329 fprintf(stderr
, " %" PRIu64
", %" PRIu64
"\n", selectfrm
[max_selected
].first
,
330 selectfrm
[max_selected
].second
);
337 /* Was the packet selected? */
340 selected(uint64_t recno
)
344 for (i
= 0; i
< max_selected
; i
++) {
345 if (selectfrm
[i
].inclusive
) {
346 if (selectfrm
[i
].first
<= recno
&& selectfrm
[i
].second
>= recno
)
349 if (recno
== selectfrm
[i
].first
)
358 set_time_adjustment(char *optarg_str_p
)
367 /* skip leading whitespace */
368 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
371 /* check for a negative adjustment */
372 if (*optarg_str_p
== '-') {
373 time_adj
.is_negative
= 1;
377 /* collect whole number of seconds, if any */
378 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
382 val
= strtol(optarg_str_p
, &frac
, 10);
383 if (frac
== NULL
|| frac
== optarg_str_p
384 || val
== LONG_MIN
|| val
== LONG_MAX
) {
385 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
389 if (val
< 0) { /* implies '--' since we caught '-' above */
390 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
395 time_adj
.tv
.secs
= val
;
397 /* now collect the partial seconds, if any */
398 if (*frac
!= '\0') { /* chars left, so get fractional part */
399 val
= strtol(&(frac
[1]), &end
, 10);
400 /* if more than 9 fractional digits truncate to 9 */
401 if ((end
- &(frac
[1])) > 9) {
402 frac
[10] = 't'; /* 't' for truncate */
403 val
= strtol(&(frac
[1]), &end
, 10);
405 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
406 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
407 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
412 return true; /* no fractional digits */
415 /* adjust fractional portion from fractional to numerator
416 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
417 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
418 while(frac_digits
< 9) { /* this is frac of 10^9 */
423 time_adj
.tv
.nsecs
= (int)val
;
428 set_strict_time_adj(char *optarg_str_p
)
437 /* skip leading whitespace */
438 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
442 * check for a negative adjustment
443 * A negative strict adjustment value is a flag
444 * to adjust all frames by the specified delta time.
446 if (*optarg_str_p
== '-') {
447 strict_time_adj
.is_negative
= 1;
451 /* collect whole number of seconds, if any */
452 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
456 val
= strtol(optarg_str_p
, &frac
, 10);
457 if (frac
== NULL
|| frac
== optarg_str_p
458 || val
== LONG_MIN
|| val
== LONG_MAX
) {
459 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
463 if (val
< 0) { /* implies '--' since we caught '-' above */
464 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
469 strict_time_adj
.tv
.secs
= val
;
471 /* now collect the partial seconds, if any */
472 if (*frac
!= '\0') { /* chars left, so get fractional part */
473 val
= strtol(&(frac
[1]), &end
, 10);
474 /* if more than 9 fractional digits truncate to 9 */
475 if ((end
- &(frac
[1])) > 9) {
476 frac
[10] = 't'; /* 't' for truncate */
477 val
= strtol(&(frac
[1]), &end
, 10);
479 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
480 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
481 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
486 return true; /* no fractional digits */
489 /* adjust fractional portion from fractional to numerator
490 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
491 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
492 while(frac_digits
< 9) { /* this is frac of 10^9 */
497 strict_time_adj
.tv
.nsecs
= (int)val
;
502 set_rel_time(char *optarg_str_p
)
511 /* skip leading whitespace */
512 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
515 /* ignore negative adjustment */
516 if (*optarg_str_p
== '-')
519 /* collect whole number of seconds, if any */
520 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
524 val
= strtol(optarg_str_p
, &frac
, 10);
525 if (frac
== NULL
|| frac
== optarg_str_p
526 || val
== LONG_MIN
|| val
== LONG_MAX
) {
527 fprintf(stderr
, "1: editcap: \"%s\" isn't a valid rel time value\n",
531 if (val
< 0) { /* implies '--' since we caught '-' above */
532 fprintf(stderr
, "2: editcap: \"%s\" isn't a valid rel time value\n",
537 relative_time_window
.secs
= val
;
539 /* now collect the partial seconds, if any */
540 if (*frac
!= '\0') { /* chars left, so get fractional part */
541 val
= strtol(&(frac
[1]), &end
, 10);
542 /* if more than 9 fractional digits truncate to 9 */
543 if ((end
- &(frac
[1])) > 9) {
544 frac
[10] = 't'; /* 't' for truncate */
545 val
= strtol(&(frac
[1]), &end
, 10);
547 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
548 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
549 fprintf(stderr
, "3: editcap: \"%s\" isn't a valid rel time value\n",
554 return true; /* no fractional digits */
557 /* adjust fractional portion from fractional to numerator
558 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
559 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
560 while(frac_digits
< 9) { /* this is frac of 10^9 */
565 relative_time_window
.nsecs
= (int)val
;
569 #define SLL_ADDRLEN 8 /* length of address field */
571 uint16_t sll_pkttype
; /* packet type */
572 uint16_t sll_hatype
; /* link-layer address type */
573 uint16_t sll_halen
; /* link-layer address length */
574 uint8_t sll_addr
[SLL_ADDRLEN
]; /* link-layer address */
575 uint16_t sll_protocol
; /* protocol */
579 uint16_t sll2_protocol
; /* protocol */
580 uint16_t sll2_reserved_mbz
; /* reserved - must be zero */
581 uint32_t sll2_if_index
; /* 1-based interface index */
582 uint16_t sll2_hatype
; /* link-layer address type */
583 uint8_t sll2_pkttype
; /* packet type */
584 uint8_t sll2_halen
; /* link-layer address length */
585 uint8_t sll2_addr
[SLL_ADDRLEN
]; /* link-layer address */
590 sll_remove_vlan_info(uint8_t* fd
, uint32_t* len
) {
591 if (pntoh16(fd
+ offsetof(struct sll_header
, sll_protocol
)) == ETHERTYPE_VLAN
) {
593 /* point to start of vlan */
594 fd
= fd
+ offsetof(struct sll_header
, sll_protocol
);
595 /* bytes to read after vlan info */
596 rest_len
= *len
- (offsetof(struct sll_header
, sll_protocol
) + VLAN_SIZE
);
597 /* remove vlan info from packet */
598 memmove(fd
, fd
+ VLAN_SIZE
, rest_len
);
606 sll_set_unused_info(uint8_t* fd
) {
608 ha_len
= pntoh16(fd
+ offsetof(struct sll_header
, sll_halen
));
610 if (ha_len
< SLL_ADDRLEN
) {
612 unused
= SLL_ADDRLEN
- ha_len
;
613 /* point to end of sll_ddr */
614 fd
= fd
+ offsetof(struct sll_header
, sll_addr
) + ha_len
;
615 /* set zeros in the unused data */
616 memset(fd
, 0, unused
);
621 sll2_set_unused_info(uint8_t* fd
) {
623 ha_len
= *(fd
+ offsetof(struct sll2_header
, sll2_halen
));
625 if (ha_len
< SLL_ADDRLEN
) {
627 unused
= SLL_ADDRLEN
- ha_len
;
628 /* point to end of sll2_addr */
629 fd
= fd
+ offsetof(struct sll2_header
, sll2_addr
) + ha_len
;
630 /* set zeros in the unused data */
631 memset(fd
, 0, unused
);
636 remove_vlan_info(const wtap_packet_header
*phdr
, uint8_t* fd
, uint32_t* len
) {
637 switch (phdr
->pkt_encap
) {
639 sll_remove_vlan_info(fd
, len
);
642 /* no support for current pkt_encap */
648 set_unused_info(const wtap_packet_header
*phdr
, uint8_t* fd
) {
649 switch (phdr
->pkt_encap
) {
651 sll_set_unused_info(fd
);
653 case WTAP_ENCAP_SLL2
:
654 sll2_set_unused_info(fd
);
657 /* no support for current pkt_encap */
663 is_duplicate(uint8_t* fd
, uint32_t len
) {
665 const struct ieee80211_radiotap_header
* tap_header
;
667 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
668 uint32_t offset
= ignored_bytes
;
672 if (len
<= ignored_bytes
) {
676 /* Get the size of radiotap header and use that as offset (-p option) */
677 if (skip_radiotap
== true) {
678 tap_header
= (const struct ieee80211_radiotap_header
*)fd
;
679 offset
= pletoh16(&tap_header
->it_len
);
684 new_fd
= &fd
[offset
];
685 new_len
= len
- (offset
);
688 if (cur_dup_entry
>= dup_window
)
691 /* Calculate our digest */
692 gcry_md_hash_buffer(GCRY_MD_MD5
, fd_hash
[cur_dup_entry
].digest
, new_fd
, new_len
);
694 fd_hash
[cur_dup_entry
].len
= len
;
696 /* Look for duplicates */
697 for (i
= 0; i
< dup_window
; i
++) {
698 if (i
== cur_dup_entry
)
701 if (fd_hash
[i
].len
== fd_hash
[cur_dup_entry
].len
702 && memcmp(fd_hash
[i
].digest
, fd_hash
[cur_dup_entry
].digest
, 16) == 0) {
711 is_duplicate_rel_time(uint8_t* fd
, uint32_t len
, const nstime_t
*current
) {
714 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
715 uint32_t offset
= ignored_bytes
;
719 if (len
<= ignored_bytes
) {
723 new_fd
= &fd
[offset
];
724 new_len
= len
- (offset
);
727 if (cur_dup_entry
>= dup_window
)
730 /* Calculate our digest */
731 gcry_md_hash_buffer(GCRY_MD_MD5
, fd_hash
[cur_dup_entry
].digest
, new_fd
, new_len
);
733 fd_hash
[cur_dup_entry
].len
= len
;
734 fd_hash
[cur_dup_entry
].frame_time
.secs
= current
->secs
;
735 fd_hash
[cur_dup_entry
].frame_time
.nsecs
= current
->nsecs
;
738 * Look for relative time related duplicates.
739 * This is hopefully a reasonably efficient mechanism for
740 * finding duplicates by rel time in the fd_hash[] cache.
741 * We check starting from the most recently added hash
742 * entries and work backwards towards older packets.
743 * This approach allows the dup test to be terminated
744 * when the relative time of a cached entry is found to
745 * be beyond the dup time window.
747 * Of course this assumes that the input trace file is
748 * "well-formed" in the sense that the packet timestamps are
749 * in strict chronologically increasing order (which is NOT
750 * always the case!!).
752 * The fd_hash[] table was deliberately created large (1,000,000).
753 * Looking for time related duplicates in large trace files with
754 * non-fractional dup time window values can potentially take
755 * a long time to complete.
758 for (i
= cur_dup_entry
- 1;; i
--) {
765 if (i
== cur_dup_entry
) {
767 * We've decremented back to where we started.
773 if (nstime_is_unset(&(fd_hash
[i
].frame_time
))) {
775 * We've decremented to an unused fd_hash[] entry.
781 nstime_delta(&delta
, current
, &fd_hash
[i
].frame_time
);
783 if (delta
.secs
< 0 || delta
.nsecs
< 0) {
785 * A negative delta implies that the current packet
786 * has an absolute timestamp less than the cached packet
787 * that it is being compared to. This is NOT a normal
788 * situation since trace files usually have packets in
789 * chronological order (oldest to newest).
791 * There are several possible ways to deal with this:
792 * 1. 'continue' dup checking with the next cached frame.
793 * 2. 'break' from looking for a duplicate of the current frame.
794 * 3. Take the absolute value of the delta and see if that
795 * falls within the specified dup time window.
797 * Currently this code does option 1. But it would pretty
798 * easy to add yet-another-editcap-option to select one of
799 * the other behaviors for dealing with out-of-sequence
805 cmp
= nstime_cmp(&delta
, &relative_time_window
);
809 * The delta time indicates that we are now looking at
810 * cached packets beyond the specified dup time window.
814 } else if (fd_hash
[i
].len
== fd_hash
[cur_dup_entry
].len
815 && memcmp(fd_hash
[i
].digest
, fd_hash
[cur_dup_entry
].digest
, 16) == 0) {
824 print_usage(FILE *output
)
826 fprintf(output
, "\n");
827 fprintf(output
, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
828 fprintf(output
, "\n");
829 fprintf(output
, "<infile> and <outfile> must both be present; use '-' for stdin or stdout.\n");
830 fprintf(output
, "A single packet or a range of packets can be selected.\n");
831 fprintf(output
, "\n");
832 fprintf(output
, "Packet selection:\n");
833 fprintf(output
, " -r keep the selected packets; default is to delete them.\n");
834 fprintf(output
, " -A <start time> only read packets whose timestamp is after (or equal\n");
835 fprintf(output
, " to) the given time.\n");
836 fprintf(output
, " -B <stop time> only read packets whose timestamp is before the\n");
837 fprintf(output
, " given time.\n");
838 fprintf(output
, " Time format for -A/-B options is\n");
839 fprintf(output
, " YYYY-MM-DDThh:mm:ss[.nnnnnnnnn][Z|+-hh:mm]\n");
840 fprintf(output
, " Unix epoch timestamps are also supported.\n");
841 fprintf(output
, "\n");
842 fprintf(output
, "Duplicate packet removal:\n");
843 fprintf(output
, " --novlan remove vlan info from packets before checking for duplicates.\n");
844 fprintf(output
, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH
);
845 fprintf(output
, " -D <dup window> remove packet if duplicate; configurable <dup window>.\n");
846 fprintf(output
, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH
);
847 fprintf(output
, " NOTE: A <dup window> of 0 with -V (verbose option) is\n");
848 fprintf(output
, " useful to print MD5 hashes.\n");
849 fprintf(output
, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
850 fprintf(output
, " LESS THAN <dup time window> prior to current packet.\n");
851 fprintf(output
, " A <dup time window> is specified in relative seconds\n");
852 fprintf(output
, " (e.g. 0.000001).\n");
853 fprintf(output
, " NOTE: The use of the 'Duplicate packet removal' options with\n");
854 fprintf(output
, " other editcap options except -V may not always work as expected.\n");
855 fprintf(output
, " Specifically the -r, -t or -S options will very likely NOT have the\n");
856 fprintf(output
, " desired effect if combined with the -d, -D or -w.\n");
857 fprintf(output
, " --skip-radiotap-header skip radiotap header when checking for packet duplicates.\n");
858 fprintf(output
, " Useful when processing packets captured by multiple radios\n");
859 fprintf(output
, " on the same channel in the vicinity of each other.\n");
860 fprintf(output
, " --set-unused set unused byts to zero in sll link addr.\n");
861 fprintf(output
, "\n");
862 fprintf(output
, "Packet manipulation:\n");
863 fprintf(output
, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
864 fprintf(output
, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
865 fprintf(output
, " chop at the packet beginning, negative values at the\n");
866 fprintf(output
, " packet end. If an optional offset precedes the length,\n");
867 fprintf(output
, " then the bytes chopped will be offset from that value.\n");
868 fprintf(output
, " Positive offsets are from the packet beginning,\n");
869 fprintf(output
, " negative offsets are from the packet end. You can use\n");
870 fprintf(output
, " this option more than once, allowing up to 2 chopping\n");
871 fprintf(output
, " regions within a packet provided that at least 1\n");
872 fprintf(output
, " choplen is positive and at least 1 is negative.\n");
873 fprintf(output
, " -L adjust the frame (i.e. reported) length when chopping\n");
874 fprintf(output
, " and/or snapping.\n");
875 fprintf(output
, " -t <time adjustment> adjust the timestamp of each packet.\n");
876 fprintf(output
, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
877 fprintf(output
, " -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
878 fprintf(output
, " strict chronological increasing order. The <strict\n");
879 fprintf(output
, " adjustment> is specified in relative seconds with\n");
880 fprintf(output
, " values of 0 or 0.000001 being the most reasonable.\n");
881 fprintf(output
, " A negative adjustment value will modify timestamps so\n");
882 fprintf(output
, " that each packet's delta time is the absolute value\n");
883 fprintf(output
, " of the adjustment specified. A value of -0 will set\n");
884 fprintf(output
, " all packets to the timestamp of the first packet.\n");
885 fprintf(output
, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
886 fprintf(output
, " a particular packet byte will be randomly changed.\n");
887 fprintf(output
, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
888 fprintf(output
, " beginning of the packet. This allows one to preserve some\n");
889 fprintf(output
, " bytes, in order to have some headers untouched.\n");
890 fprintf(output
, " --seed <seed> When used in conjunction with -E, set the seed to use for\n");
891 fprintf(output
, " the pseudo-random number generator. This allows one to\n");
892 fprintf(output
, " repeat a particular sequence of errors.\n");
893 fprintf(output
, " -I <bytes to ignore> ignore the specified number of bytes at the beginning\n");
894 fprintf(output
, " of the frame during MD5 hash calculation, unless the\n");
895 fprintf(output
, " frame is too short, then the full frame is used.\n");
896 fprintf(output
, " Useful to remove duplicated packets taken on\n");
897 fprintf(output
, " several routers (different mac addresses for\n");
898 fprintf(output
, " example).\n");
899 fprintf(output
, " e.g. -I 26 in case of Ether/IP will ignore\n");
900 fprintf(output
, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
901 fprintf(output
, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
902 fprintf(output
, "\n");
903 fprintf(output
, "Output File(s):\n");
904 fprintf(output
, " if the output file(s) have the .gz extension, then\n");
905 fprintf(output
, " gzip compression will be used\n");
906 fprintf(output
, " -c <packets per file> split the packet output to different files based on\n");
907 fprintf(output
, " uniform packet counts with a maximum of\n");
908 fprintf(output
, " <packets per file> each.\n");
909 fprintf(output
, " -i <seconds per file> split the packet output to different files based on\n");
910 fprintf(output
, " uniform time intervals with a maximum of\n");
911 fprintf(output
, " <seconds per file> each.\n");
912 fprintf(output
, " -F <capture type> set the output file type; default is pcapng.\n");
913 fprintf(output
, " An empty \"-F\" option will list the file types.\n");
914 fprintf(output
, " -T <encap type> set the output file encapsulation type; default is the\n");
915 fprintf(output
, " same as the input file. An empty \"-T\" option will\n");
916 fprintf(output
, " list the encapsulation types.\n");
917 fprintf(output
, " --inject-secrets <type>,<file> Insert decryption secrets from <file>. List\n");
918 fprintf(output
, " supported secret types with \"--inject-secrets help\".\n");
919 fprintf(output
, " --extract-secrets Extract decryption secrets into the output file instead.\n");
920 fprintf(output
, " Incompatible with other options besides -V.\n");
921 fprintf(output
, " --discard-all-secrets Discard all decryption secrets from the input file\n");
922 fprintf(output
, " when writing the output file. Does not discard\n");
923 fprintf(output
, " secrets added by \"--inject-secrets\" in the same\n");
924 fprintf(output
, " command line.\n");
925 fprintf(output
, " --capture-comment <comment>\n");
926 fprintf(output
, " Add a capture file comment, if supported.\n");
927 fprintf(output
, " --discard-capture-comment\n");
928 fprintf(output
, " Discard capture file comments from the input file\n");
929 fprintf(output
, " when writing the output file. Does not discard\n");
930 fprintf(output
, " comments added by \"--capture-comment\" in the same\n");
931 fprintf(output
, " command line.\n");
932 fprintf(output
, " --discard-packet-comments\n");
933 fprintf(output
, " Discard all packet comments from the input file\n");
934 fprintf(output
, " when writing the output file. Does not discard\n");
935 fprintf(output
, " comments added by \"-a\" in the same command line.\n");
936 fprintf(output
, " --compress <type> Compress the output file using the type compression format.\n");
937 fprintf(output
, "\n");
938 fprintf(output
, "Miscellaneous:\n");
939 fprintf(output
, " -h, --help display this help and exit.\n");
940 fprintf(output
, " -V verbose output.\n");
941 fprintf(output
, " If -V is used with any of the 'Duplicate Packet\n");
942 fprintf(output
, " Removal' options (-d, -D or -w) then Packet lengths\n");
943 fprintf(output
, " and MD5 hashes are printed to standard-error.\n");
944 fprintf(output
, " -v, --version print version information and exit.\n");
948 const char *sstr
; /* The short string */
949 const char *lstr
; /* The long string */
953 string_nat_compare(const void *a
, const void *b
)
955 return ws_ascii_strnatcmp(((const struct string_elem
*)a
)->sstr
,
956 ((const struct string_elem
*)b
)->sstr
);
960 string_elem_print(void *data
, void *stream_ptr
)
962 fprintf((FILE *) stream_ptr
, " %s - %s\n",
963 ((struct string_elem
*)data
)->sstr
,
964 ((struct string_elem
*)data
)->lstr
);
968 list_capture_types(FILE *stream
) {
969 GArray
*writable_type_subtypes
;
971 fprintf(stream
, "editcap: The available capture file types for the \"-F\" flag are:\n");
972 writable_type_subtypes
= wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME
);
973 for (unsigned i
= 0; i
< writable_type_subtypes
->len
; i
++) {
974 int ft
= g_array_index(writable_type_subtypes
, int, i
);
975 fprintf(stream
, " %s - %s\n", wtap_file_type_subtype_name(ft
),
976 wtap_file_type_subtype_description(ft
));
978 g_array_free(writable_type_subtypes
, TRUE
);
982 list_encap_types(FILE *stream
) {
984 struct string_elem
*encaps
;
987 encaps
= g_new(struct string_elem
, WTAP_NUM_ENCAP_TYPES
);
988 fprintf(stream
, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
989 for (i
= 0; i
< WTAP_NUM_ENCAP_TYPES
; i
++) {
990 encaps
[i
].sstr
= wtap_encap_name(i
);
991 if (encaps
[i
].sstr
!= NULL
) {
992 encaps
[i
].lstr
= wtap_encap_description(i
);
993 list
= g_slist_insert_sorted(list
, &encaps
[i
], string_nat_compare
);
996 g_slist_foreach(list
, string_elem_print
, stream
);
1002 list_output_compression_types(void) {
1003 GSList
*output_compression_types
;
1005 fprintf(stderr
, "editcap: The available output compress type(s) for the \"--compress\" flag are:\n");
1006 output_compression_types
= wtap_get_all_output_compression_type_names_list();
1007 for (GSList
*compression_type
= output_compression_types
;
1008 compression_type
!= NULL
;
1009 compression_type
= g_slist_next(compression_type
)) {
1010 fprintf(stderr
, " %s\n", (const char *)compression_type
->data
);
1013 g_slist_free(output_compression_types
);
1017 list_secrets_types(FILE *stream
)
1019 for (unsigned i
= 0; i
< G_N_ELEMENTS(secrets_types
); i
++) {
1020 fprintf(stream
, " %s\n", secrets_types
[i
].str
);
1025 lookup_secrets_type(const char *type
)
1027 for (unsigned i
= 0; i
< G_N_ELEMENTS(secrets_types
); i
++) {
1028 if (!strcmp(secrets_types
[i
].str
, type
)) {
1029 return secrets_types
[i
].id
;
1036 validate_secrets_file(const char *filename
, uint32_t secrets_type
, const char *data
)
1038 if (secrets_type
== SECRETS_TYPE_TLS
) {
1040 * A key log file is unlikely going to look like either:
1041 * - a PEM-encoded private key file.
1042 * - a BER-encoded PKCS #12 file ("PFX file"). (Look for a Constructed
1043 * SEQUENCE tag, e.g. bytes 0x30 which happens to be ASCII '0'.)
1045 if (g_str_has_prefix(data
, "-----BEGIN ") || data
[0] == 0x30) {
1047 "editcap: Warning: \"%s\" is not a key log file, but an unsupported private key file. Decryption will not work.\n",
1054 framenum_compare(const void *a
, const void *b
, void *user_data _U_
)
1056 uint64_t *frame_a
= (uint64_t*)a
;
1057 uint64_t *frame_b
= (uint64_t*)b
;
1058 if (*frame_a
< *frame_b
)
1061 if (*frame_a
> *frame_b
)
1068 * Report an error in command-line arguments.
1071 editcap_cmdarg_err(const char *msg_format
, va_list ap
)
1073 fprintf(stderr
, "editcap: ");
1074 vfprintf(stderr
, msg_format
, ap
);
1075 fprintf(stderr
, "\n");
1079 * Report additional information for an error in command-line arguments.
1082 editcap_cmdarg_err_cont(const char *msg_format
, va_list ap
)
1084 vfprintf(stderr
, msg_format
, ap
);
1085 fprintf(stderr
, "\n");
1088 static wtap_dumper
*
1089 editcap_dump_open(const char *filename
, const wtap_dump_params
*params
,
1090 GArray
*idbs_seen
, int *err
, char **err_info
,
1091 wtap_compression_type compression_type
)
1095 if (strcmp(filename
, "-") == 0) {
1096 /* Write to the standard output. */
1097 pdh
= wtap_dump_open_stdout(out_file_type_subtype
, compression_type
,
1098 params
, err
, err_info
);
1100 pdh
= wtap_dump_open(filename
, out_file_type_subtype
, compression_type
,
1101 params
, err
, err_info
);
1107 * If the output file supports identifying the interfaces on which
1108 * packets arrive, add all the IDBs we've seen so far.
1110 * That mean that the abstract interface provided by libwiretap
1111 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1113 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh
),
1114 WTAP_BLOCK_IF_ID_AND_INFO
) != BLOCK_NOT_SUPPORTED
) {
1115 for (unsigned i
= 0; i
< idbs_seen
->len
; i
++) {
1116 wtap_block_t if_data
= g_array_index(idbs_seen
, wtap_block_t
, i
);
1117 wtap_block_t if_data_copy
;
1120 * Make a copy of this IDB, so that we can change the
1121 * encapsulation type without trashing the original.
1123 if_data_copy
= wtap_block_make_copy(if_data
);
1126 * If an encapsulation type was specified, override the
1127 * encapsulation type of the interface.
1129 if (out_frame_type
!= -2) {
1130 wtapng_if_descr_mandatory_t
*if_mand
;
1132 if_mand
= (wtapng_if_descr_mandatory_t
*)wtap_block_get_mandatory_data(if_data_copy
);
1133 if_mand
->wtap_encap
= out_frame_type
;
1137 * Add this possibly-modified IDB to the file to which
1138 * we're currently writing.
1140 if (!wtap_dump_add_idb(pdh
, if_data_copy
, err
, err_info
)) {
1142 char *close_err_info
;
1144 wtap_dump_close(pdh
, NULL
, &close_err
, &close_err_info
);
1145 g_free(close_err_info
);
1146 wtap_block_unref(if_data_copy
);
1151 * Release the copy - wtap_dump_add_idb() makes its own copy.
1153 wtap_block_unref(if_data_copy
);
1161 process_new_idbs(wtap
*wth
, wtap_dumper
*pdh
, GArray
*idbs_seen
,
1162 int *err
, char **err_info
)
1164 wtap_block_t if_data
;
1166 while ((if_data
= wtap_get_next_interface_description(wth
)) != NULL
) {
1168 * Only add interface blocks if the output file supports (meaning
1171 * That mean that the abstract interface provided by libwiretap
1172 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1174 if (pdh
!= NULL
&& wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh
),
1175 WTAP_BLOCK_IF_ID_AND_INFO
) != BLOCK_NOT_SUPPORTED
) {
1176 wtap_block_t if_data_copy
;
1179 * Make a copy of this IDB, so that we can change the
1180 * encapsulation type without trashing the original.
1182 if_data_copy
= wtap_block_make_copy(if_data
);
1185 * If an encapsulation type was specified, override the
1186 * encapsulation type of the interface.
1188 if (out_frame_type
!= -2) {
1189 wtapng_if_descr_mandatory_t
*if_mand
;
1191 if_mand
= (wtapng_if_descr_mandatory_t
*)wtap_block_get_mandatory_data(if_data_copy
);
1192 if_mand
->wtap_encap
= out_frame_type
;
1196 * Add this possibly-modified IDB to the file to which
1197 * we're currently writing.
1199 if (!wtap_dump_add_idb(pdh
, if_data_copy
, err
, err_info
))
1203 * Release the copy - wtap_dump_add_idb() makes its own copy.
1205 wtap_block_unref(if_data_copy
);
1208 * Also add an unmodified copy to the set of IDBs we've seen,
1209 * in case we start writing to another file (which would be
1210 * of the same type as the current file, and thus will also
1211 * require interface IDs).
1213 if_data_copy
= wtap_block_make_copy(if_data
);
1214 g_array_append_val(idbs_seen
, if_data_copy
);
1221 extract_secrets(wtap
*wth
, char* filename
, int *err
, char **err_info
)
1226 char *fprefix
= NULL
;
1227 char *fsuffix
= NULL
;
1229 /* Read all of the packets in turn */
1230 wtap_rec_init(&read_rec
);
1231 ws_buffer_init(&read_buf
, 1514);
1232 while (wtap_read(wth
, &read_rec
, &read_buf
, err
, err_info
, &offset
)) {
1233 /* Do we want to respect the max packet number on the command line?
1234 * Probably more confusing than it's worth, because a user might
1235 * not know if a DSB is at the end of the file.
1237 wtap_rec_reset(&read_rec
);
1239 wtap_rec_cleanup(&read_rec
);
1240 ws_buffer_free(&read_buf
);
1242 wtapng_dsb_mandatory_t
*dsb
;
1243 if (strcmp(filename
, "-") == 0) {
1244 /* Sure. Why not. */
1245 for (unsigned dsb_num
= 0; dsb_num
< wtap_file_get_num_dsbs(wth
); ++dsb_num
) {
1246 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, dsb_num
));
1248 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to standard out.\n",
1249 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
);
1251 if (fwrite(dsb
->secrets_data
, 1, dsb
->secrets_len
, stdout
) != dsb
->secrets_len
) {
1255 } else if (wtap_file_get_num_dsbs(wth
) == 1) {
1256 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, 0));
1258 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1259 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
,
1262 if (!write_file_binary_mode(filename
, dsb
->secrets_data
, dsb
->secrets_len
)) {
1266 /* We have more than one DSB, so write multiple files. While for some
1267 * types, we could combine the information from different DSBs togther
1268 * (and most of those are text-based, so we'd want to write in text
1269 * mode so that the line endings are uniform (which makes testing
1270 * harder), we don't know that for every type.
1272 if (!fileset_extract_prefix_suffix(filename
, &fprefix
, &fsuffix
, NULL
)) {
1273 return CANT_EXTRACT_PREFIX
;
1275 char *extract_filename
;
1276 for (unsigned dsb_num
= 0; dsb_num
< wtap_file_get_num_dsbs(wth
); ++dsb_num
) {
1277 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, dsb_num
));
1278 extract_filename
= fileset_get_filename_by_pattern(dsb_num
, NULL
, fprefix
, fsuffix
);
1280 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1281 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
,
1284 if (!write_file_binary_mode(extract_filename
, dsb
->secrets_data
, dsb
->secrets_len
)) {
1285 /* write_file_binary_mode already reports failures */
1286 g_free(extract_filename
);
1292 g_free(extract_filename
);
1297 return EXIT_SUCCESS
;
1301 main(int argc
, char *argv
[])
1303 char *configuration_init_error
;
1304 static const struct report_message_routines editcap_report_routines
= {
1307 open_failure_message
,
1308 read_failure_message
,
1309 write_failure_message
,
1310 cfile_open_failure_message
,
1311 cfile_dump_open_failure_message
,
1312 cfile_read_failure_message
,
1313 cfile_write_failure_message
,
1314 cfile_close_failure_message
1317 int i
, j
, read_err
, write_err
;
1318 char *read_err_info
, *write_err_info
;
1321 #define LONGOPT_NO_VLAN LONGOPT_BASE_APPLICATION+1
1322 #define LONGOPT_SKIP_RADIOTAP_HEADER LONGOPT_BASE_APPLICATION+2
1323 #define LONGOPT_SEED LONGOPT_BASE_APPLICATION+3
1324 #define LONGOPT_INJECT_SECRETS LONGOPT_BASE_APPLICATION+4
1325 #define LONGOPT_DISCARD_ALL_SECRETS LONGOPT_BASE_APPLICATION+5
1326 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
1327 #define LONGOPT_DISCARD_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+7
1328 #define LONGOPT_SET_UNUSED LONGOPT_BASE_APPLICATION+8
1329 #define LONGOPT_DISCARD_PACKET_COMMENTS LONGOPT_BASE_APPLICATION+9
1330 #define LONGOPT_EXTRACT_SECRETS LONGOPT_BASE_APPLICATION+10
1331 #define LONGOPT_COMPRESS LONGOPT_BASE_APPLICATION+11
1333 static const struct ws_option long_options
[] = {
1334 {"novlan", ws_no_argument
, NULL
, LONGOPT_NO_VLAN
},
1335 {"skip-radiotap-header", ws_no_argument
, NULL
, LONGOPT_SKIP_RADIOTAP_HEADER
},
1336 {"seed", ws_required_argument
, NULL
, LONGOPT_SEED
},
1337 {"inject-secrets", ws_required_argument
, NULL
, LONGOPT_INJECT_SECRETS
},
1338 {"discard-all-secrets", ws_no_argument
, NULL
, LONGOPT_DISCARD_ALL_SECRETS
},
1339 {"help", ws_no_argument
, NULL
, 'h'},
1340 {"version", ws_no_argument
, NULL
, 'v'},
1341 {"capture-comment", ws_required_argument
, NULL
, LONGOPT_CAPTURE_COMMENT
},
1342 {"discard-capture-comment", ws_no_argument
, NULL
, LONGOPT_DISCARD_CAPTURE_COMMENT
},
1343 {"set-unused", ws_no_argument
, NULL
, LONGOPT_SET_UNUSED
},
1344 {"discard-packet-comments", ws_no_argument
, NULL
, LONGOPT_DISCARD_PACKET_COMMENTS
},
1345 {"extract-secrets", ws_no_argument
, NULL
, LONGOPT_EXTRACT_SECRETS
},
1346 {"compress", ws_required_argument
, NULL
, LONGOPT_COMPRESS
},
1351 uint32_t snaplen
= 0; /* No limit */
1352 chop_t chop
= {0, 0, 0, 0, 0, 0}; /* No chop */
1353 bool adjlen
= false;
1354 wtap_dumper
*pdh
= NULL
;
1355 GArray
*idbs_seen
= NULL
;
1357 uint64_t duplicate_count
= 0;
1358 int64_t data_offset
;
1361 uint64_t read_count
= 0;
1362 uint64_t split_packet_count
= 0;
1363 uint64_t written_count
= 0;
1364 char *filename
= NULL
;
1366 nstime_t secs_per_block
= NSTIME_INIT_UNSET
;
1368 nstime_t block_next
= NSTIME_INIT_UNSET
;
1369 char *fprefix
= NULL
;
1370 char *fsuffix
= NULL
;
1371 uint32_t change_offset
= 0;
1372 uint64_t max_packet_number
= 0;
1373 GArray
*dsb_types
= NULL
;
1374 GPtrArray
*dsb_filenames
= NULL
;
1377 const wtap_rec
*rec
;
1379 wtap_dump_params params
= WTAP_DUMP_PARAMS_INIT
;
1380 char *shb_user_appl
;
1383 int ret
= EXIT_SUCCESS
;
1384 bool valid_seed
= false;
1385 unsigned int seed
= 0;
1386 bool edit_option_specified
= false;
1387 wtap_compression_type compression_type
= WTAP_UNKNOWN_COMPRESSION
;
1389 cmdarg_err_init(editcap_cmdarg_err
, editcap_cmdarg_err_cont
);
1390 memset(&read_rec
, 0, sizeof *rec
);
1392 /* Initialize log handler early so we can have proper logging during startup. */
1393 ws_log_init("editcap", vcmdarg_err
);
1395 /* Early logging command-line initialization. */
1396 ws_log_parse_args(&argc
, argv
, vcmdarg_err
, WS_EXIT_INVALID_OPTION
);
1398 ws_noisy("Finished log init and parsing command line log arguments");
1401 create_app_running_mutex();
1404 /* Initialize the version information. */
1405 ws_init_version_info("Editcap", NULL
, NULL
);
1408 * Get credential information for later use.
1410 init_process_policies();
1413 * Attempt to get the pathname of the directory containing the
1416 configuration_init_error
= configuration_init(argv
[0], NULL
);
1417 if (configuration_init_error
!= NULL
) {
1418 cmdarg_err("Can't get pathname of directory containing the editcap program: %s.",
1419 configuration_init_error
);
1420 g_free(configuration_init_error
);
1423 init_report_message("editcap", &editcap_report_routines
);
1427 /* Process the options */
1428 while ((opt
= ws_getopt_long(argc
, argv
, "a:A:B:c:C:dD:E:F:hi:I:Lo:rs:S:t:T:vVw:", long_options
, NULL
)) != -1) {
1429 if (opt
!= LONGOPT_EXTRACT_SECRETS
&& opt
!= 'V') {
1430 edit_option_specified
= true;
1433 case LONGOPT_NO_VLAN
:
1439 case LONGOPT_SKIP_RADIOTAP_HEADER
:
1441 skip_radiotap
= true;
1447 if (sscanf(ws_optarg
, "%u", &seed
) != 1) {
1448 cmdarg_err("\"%s\" isn't a valid seed", ws_optarg
);
1449 ret
= WS_EXIT_INVALID_OPTION
;
1456 case LONGOPT_INJECT_SECRETS
:
1458 uint32_t secrets_type_id
= 0;
1459 const char *secrets_filename
= NULL
;
1460 if (strcmp("help", ws_optarg
) == 0) {
1461 list_secrets_types(stdout
);
1464 char **splitted
= g_strsplit(ws_optarg
, ",", 2);
1465 if (splitted
[0] && splitted
[0][0] != '\0') {
1466 secrets_type_id
= lookup_secrets_type(splitted
[0]);
1467 if (secrets_type_id
== 0) {
1468 cmdarg_err("\"%s\" isn't a valid secrets type", splitted
[0]);
1469 g_strfreev(splitted
);
1470 ret
= WS_EXIT_INVALID_OPTION
;
1473 secrets_filename
= splitted
[1];
1475 cmdarg_err("no secrets type was specified for --inject-secrets");
1476 g_strfreev(splitted
);
1477 ret
= WS_EXIT_INVALID_OPTION
;
1480 if (!dsb_filenames
) {
1481 dsb_types
= g_array_new(FALSE
, FALSE
, sizeof(uint32_t));
1482 dsb_filenames
= g_ptr_array_new_with_free_func(g_free
);
1484 g_array_append_val(dsb_types
, secrets_type_id
);
1485 g_ptr_array_add(dsb_filenames
, g_strdup(secrets_filename
));
1486 g_strfreev(splitted
);
1490 case LONGOPT_DISCARD_ALL_SECRETS
:
1492 discard_all_secrets
= true;
1496 case LONGOPT_CAPTURE_COMMENT
:
1499 * Make sure this would fit in a pcapng option.
1501 * XXX - 65535 is the maximum size for an option in pcapng;
1502 * what if another capture file format supports larger
1505 if (strlen(ws_optarg
) > 65535) {
1506 /* It doesn't fit. Tell the user and give up. */
1507 cmdarg_err("Capture comment %u is too large to save in a capture file.",
1508 capture_comments
->len
+ 1);
1509 ret
= WS_EXIT_INVALID_OPTION
;
1513 /* pcapng supports multiple comments, so support them here too.
1515 if (!capture_comments
) {
1516 capture_comments
= g_ptr_array_new_with_free_func(g_free
);
1518 g_ptr_array_add(capture_comments
, g_strdup(ws_optarg
));
1522 case LONGOPT_DISCARD_CAPTURE_COMMENT
:
1524 discard_cap_comments
= true;
1528 case LONGOPT_SET_UNUSED
:
1534 case LONGOPT_DISCARD_PACKET_COMMENTS
:
1536 discard_pkt_comments
= true;
1540 case LONGOPT_EXTRACT_SECRETS
:
1542 do_extract_secrets
= true;
1543 /* XXX - Would it make sense to specify what types of secrets
1544 * to extract (or any)?
1549 case LONGOPT_COMPRESS
:
1551 compression_type
= wtap_name_to_compression_type(ws_optarg
);
1552 if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1553 cmdarg_err("\"%s\" isn't a valid output compression mode",
1555 list_output_compression_types();
1563 uint64_t frame_number
;
1564 int string_start_index
= 0;
1566 if ((sscanf(ws_optarg
, "%" SCNu64
":%n", &frame_number
, &string_start_index
) < 1) || (string_start_index
== 0)) {
1567 cmdarg_err("\"%s\" isn't a valid <frame>:<comment>", ws_optarg
);
1568 ret
= WS_EXIT_INVALID_OPTION
;
1573 * Make sure this would fit in a pcapng option.
1575 * XXX - 65535 is the maximum size for an option in pcapng;
1576 * what if another capture file format supports larger
1579 if (strlen(ws_optarg
+string_start_index
) > 65535) {
1580 /* It doesn't fit. Tell the user and give up. */
1581 cmdarg_err("A comment for frame %" PRIu64
" is too large to save in a capture file.",
1583 ret
= WS_EXIT_INVALID_OPTION
;
1587 /* Lazily create the table */
1588 if (!frames_user_comments
) {
1589 frames_user_comments
= g_tree_new_full(framenum_compare
, NULL
, g_free
, g_free
);
1592 /* Insert this entry (framenum -> comment) */
1593 uint64_t *frame_p
= g_new(uint64_t, 1);
1594 *frame_p
= frame_number
;
1595 g_tree_replace(frames_user_comments
, frame_p
, g_strdup(ws_optarg
+string_start_index
));
1604 check_startstop
= true;
1605 if ((NULL
!= iso8601_to_nstime(&in_time
, ws_optarg
, ISO8601_DATETIME
)) || (NULL
!= unix_epoch_to_nstime(&in_time
, ws_optarg
))) {
1607 nstime_copy(&starttime
, &in_time
);
1608 have_starttime
= true;
1610 nstime_copy(&stoptime
, &in_time
);
1611 have_stoptime
= true;
1616 cmdarg_err("\"%s\" isn't a valid date and time", ws_optarg
);
1617 ret
= WS_EXIT_INVALID_OPTION
;
1623 split_packet_count
= get_nonzero_uint64(ws_optarg
, "packet count");
1628 int choplen
= 0, chopoff
= 0;
1630 switch (sscanf(ws_optarg
, "%d:%d", &chopoff
, &choplen
)) {
1631 case 1: /* only the chop length was specified */
1636 case 2: /* both an offset and chop length was specified */
1640 cmdarg_err("\"%s\" isn't a valid chop length or offset:length", ws_optarg
);
1641 ret
= WS_EXIT_INVALID_OPTION
;
1647 chop
.len_begin
+= choplen
;
1649 chop
.off_begin_pos
+= chopoff
;
1651 chop
.off_begin_neg
+= chopoff
;
1652 } else if (choplen
< 0) {
1653 chop
.len_end
+= choplen
;
1655 chop
.off_end_pos
+= chopoff
;
1657 chop
.off_end_neg
+= chopoff
;
1664 dup_detect_by_time
= false;
1665 dup_window
= DEFAULT_DUP_DEPTH
;
1670 dup_detect_by_time
= false;
1671 dup_window
= get_uint32(ws_optarg
, "duplicate window");
1672 if (dup_window
> MAX_DUP_DEPTH
) {
1673 cmdarg_err("\"%d\" duplicate window value must be between 0 and %d inclusive.",
1674 dup_window
, MAX_DUP_DEPTH
);
1675 ret
= WS_EXIT_INVALID_OPTION
;
1681 err_prob
= g_ascii_strtod(ws_optarg
, &p
);
1682 if (p
== ws_optarg
|| err_prob
< 0.0 || err_prob
> 1.0) {
1683 cmdarg_err("probability \"%s\" must be between 0.0 and 1.0", ws_optarg
);
1684 ret
= WS_EXIT_INVALID_OPTION
;
1690 out_file_type_subtype
= wtap_name_to_file_type_subtype(ws_optarg
);
1691 if (out_file_type_subtype
< 0) {
1692 cmdarg_err("\"%s\" isn't a valid capture file type\n", ws_optarg
);
1693 list_capture_types(stderr
);
1694 ret
= WS_EXIT_INVALID_OPTION
;
1700 show_help_header("Edit and/or translate the format of capture files.");
1701 print_usage(stdout
);
1705 case 'i': /* break capture file based on time interval */
1707 double spb
= get_positive_double(ws_optarg
, "time interval");
1709 cmdarg_err("The specified interval is zero");
1710 ret
= WS_EXIT_INVALID_OPTION
;
1714 double spb_int
, spb_frac
;
1715 spb_frac
= modf(spb
, &spb_int
);
1716 secs_per_block
.secs
= (time_t) spb_int
;
1717 secs_per_block
.nsecs
= (int) (NANOSECS_PER_SEC
* spb_frac
);
1721 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1722 ignored_bytes
= get_uint32(ws_optarg
, "number of bytes to ignore");
1730 change_offset
= get_uint32(ws_optarg
, "change offset");
1735 cmdarg_err("-r was specified twice");
1736 ret
= WS_EXIT_INVALID_OPTION
;
1743 snaplen
= get_nonzero_uint32(ws_optarg
, "snapshot length");
1747 if (!set_strict_time_adj(ws_optarg
)) {
1748 ret
= WS_EXIT_INVALID_OPTION
;
1751 do_strict_time_adjustment
= true;
1755 if (!set_time_adjustment(ws_optarg
)) {
1756 ret
= WS_EXIT_INVALID_OPTION
;
1762 out_frame_type
= wtap_name_to_encap(ws_optarg
);
1763 if (out_frame_type
< 0) {
1764 cmdarg_err("\"%s\" isn't a valid encapsulation type\n", ws_optarg
);
1765 list_encap_types(stderr
);
1766 ret
= WS_EXIT_INVALID_OPTION
;
1773 cmdarg_err("-V was specified twice");
1774 ret
= WS_EXIT_INVALID_OPTION
;
1787 dup_detect_by_time
= true;
1788 dup_window
= MAX_DUP_DEPTH
;
1789 if (!set_rel_time(ws_optarg
)) {
1790 ret
= WS_EXIT_INVALID_OPTION
;
1795 case '?': /* Bad options - print usage */
1799 list_capture_types(stdout
);
1802 list_encap_types(stdout
);
1804 case LONGOPT_COMPRESS
:
1805 list_output_compression_types();
1808 print_usage(stderr
);
1809 ret
= WS_EXIT_INVALID_OPTION
;
1815 } /* processing command-line options */
1818 fprintf(stderr
, "Optind = %i, argc = %i\n", ws_optind
, argc
);
1821 if ((argc
- ws_optind
) < 2) {
1822 print_usage(stderr
);
1823 ret
= WS_EXIT_INVALID_OPTION
;
1827 if (out_file_type_subtype
== WTAP_FILE_TYPE_SUBTYPE_UNKNOWN
) {
1828 /* default to pcapng */
1829 out_file_type_subtype
= wtap_pcapng_file_type_subtype();
1832 if (split_packet_count
!= 0 || !nstime_is_unset(&secs_per_block
)) {
1833 if (!fileset_extract_prefix_suffix(argv
[ws_optind
+1], &fprefix
, &fsuffix
, &compression_type
)) {
1834 ret
= CANT_EXTRACT_PREFIX
;
1837 } else if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1838 /* An explicitly specified compression type overrides filename
1839 * magic. (Should we allow specifying "no" compression with, e.g.
1840 * a ".gz" extension?) */
1841 const char *sfx
= strrchr(argv
[ws_optind
+1], '.');
1843 compression_type
= wtap_extension_to_compression_type(sfx
+ 1);
1847 if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1848 compression_type
= WTAP_UNCOMPRESSED
;
1851 if (!wtap_can_write_compression_type(compression_type
)) {
1852 cmdarg_err("Output files can't be written as %s",
1853 wtap_compression_type_description(compression_type
));
1854 ret
= WS_EXIT_INVALID_OPTION
;
1858 if (compression_type
!= WTAP_UNCOMPRESSED
&& !wtap_dump_can_compress(out_file_type_subtype
)) {
1859 cmdarg_err("The file format %s can't be written to output compressed format",
1860 wtap_file_type_subtype_name(out_file_type_subtype
));
1861 ret
= WS_EXIT_INVALID_OPTION
;
1865 if (err_prob
>= 0.0) {
1867 seed
= (unsigned int) (time(NULL
) + ws_getpid());
1870 fprintf(stderr
, "Using seed %u\n", seed
);
1875 if (have_starttime
&& have_stoptime
&&
1876 nstime_cmp(&starttime
, &stoptime
) > 0) {
1877 cmdarg_err("start time is after the stop time");
1878 ret
= WS_EXIT_INVALID_OPTION
;
1882 if (split_packet_count
!= 0 && !nstime_is_unset(&secs_per_block
)) {
1883 cmdarg_err("can't split on both packet count and time interval");
1884 cmdarg_err_cont("at the same time");
1885 ret
= WS_EXIT_INVALID_OPTION
;
1889 wth
= wtap_open_offline(argv
[ws_optind
], WTAP_TYPE_AUTO
, &read_err
, &read_err_info
, false);
1892 cfile_open_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
1893 ret
= WS_EXIT_INVALID_FILE
;
1898 fprintf(stderr
, "File %s is a %s capture file.\n", argv
[ws_optind
],
1899 wtap_file_type_subtype_description(wtap_file_type_subtype(wth
)));
1902 if (skip_radiotap
) {
1903 if (ignored_bytes
!= 0) {
1904 cmdarg_err("can't skip radiotap headers and %d byte(s)", ignored_bytes
);
1905 cmdarg_err_cont("at the start of packet at the same time");
1906 ret
= WS_EXIT_INVALID_OPTION
;
1910 if (wtap_file_encap(wth
) != WTAP_ENCAP_IEEE_802_11_RADIOTAP
) {
1911 cmdarg_err("can't skip radiotap header because input file has non-radiotap packets");
1912 if (wtap_file_encap(wth
) == WTAP_ENCAP_PER_PACKET
) {
1913 cmdarg_err_cont("expected '%s', not all packets are necessarily that type",
1914 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP
));
1916 cmdarg_err_cont("expected '%s', packets are '%s'",
1917 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP
),
1918 wtap_encap_description(wtap_file_encap(wth
)));
1920 ret
= WS_EXIT_INVALID_OPTION
;
1925 if (do_extract_secrets
) {
1926 if (edit_option_specified
) {
1927 cmdarg_err("can't extract secrets and use other options at the same time");
1928 ret
= WS_EXIT_INVALID_OPTION
;
1931 if (compression_type
!= WTAP_UNCOMPRESSED
) {
1932 cmdarg_err("compression isn't supported for extracting secrets");
1933 ret
= WS_EXIT_INVALID_OPTION
;
1936 ret
= extract_secrets(wth
, argv
[ws_optind
+1], &read_err
, &read_err_info
);
1938 if (read_err
!= 0) {
1939 /* Print a message noting that the read failed somewhere along the
1941 cfile_read_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
1946 wtap_dump_params_init_no_idbs(¶ms
, wth
);
1949 * Discard any secrets we read in while opening the file.
1951 if (discard_all_secrets
) {
1952 wtap_dump_params_discard_decryption_secrets(¶ms
);
1956 * Discard capture file comments.
1958 if (discard_cap_comments
) {
1959 for (unsigned b
= 0; b
< params
.shb_hdrs
->len
; b
++) {
1960 wtap_block_t shb
= g_array_index(params
.shb_hdrs
, wtap_block_t
, b
);
1961 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(shb
, OPT_COMMENT
, 0)) {
1968 * Add new capture file comments.
1970 if (capture_comments
!= NULL
) {
1971 for (unsigned b
= 0; b
< params
.shb_hdrs
->len
; b
++) {
1972 wtap_block_t shb
= g_array_index(params
.shb_hdrs
, wtap_block_t
, b
);
1973 for (unsigned c
= 0; c
< capture_comments
->len
; c
++) {
1974 char *comment
= (char *)g_ptr_array_index(capture_comments
, c
);
1975 wtap_block_add_string_option(shb
, OPT_COMMENT
, comment
, strlen(comment
));
1980 if (dsb_filenames
) {
1981 for (unsigned k
= 0; k
< dsb_filenames
->len
; k
++) {
1982 uint32_t secrets_type_id
= g_array_index(dsb_types
, uint32_t, k
);
1983 const char *secrets_filename
= (const char *)g_ptr_array_index(dsb_filenames
, k
);
1987 wtapng_dsb_mandatory_t
*dsb
;
1990 if (!g_file_get_contents(secrets_filename
, &data
, &data_len
, &err
)) {
1991 cmdarg_err("\"%s\" could not be read: %s", secrets_filename
, err
->message
);
1992 g_clear_error(&err
);
1993 ret
= WS_EXIT_INVALID_OPTION
;
1996 if (data_len
== 0) {
1997 cmdarg_err("\"%s\" is an empty file, ignoring", secrets_filename
);
2001 if (data_len
>= INT_MAX
) {
2002 cmdarg_err("\"%s\" is too large, ignoring", secrets_filename
);
2007 /* Warn for badly formatted files, but proceed anyway. */
2008 validate_secrets_file(secrets_filename
, secrets_type_id
, data
);
2010 block
= wtap_block_create(WTAP_BLOCK_DECRYPTION_SECRETS
);
2011 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(block
);
2012 dsb
->secrets_type
= secrets_type_id
;
2013 dsb
->secrets_len
= (unsigned)data_len
;
2014 dsb
->secrets_data
= data
;
2015 if (params
.dsbs_initial
== NULL
) {
2016 params
.dsbs_initial
= g_array_new(FALSE
, FALSE
, sizeof(wtap_block_t
));
2018 g_array_append_val(params
.dsbs_initial
, block
);
2023 * If an encapsulation type was specified, override the encapsulation
2024 * type of the input file.
2026 if (out_frame_type
!= -2)
2027 params
.encap
= out_frame_type
;
2030 * If a snapshot length was specified, and it's less than the snapshot
2031 * length of the input file, override the snapshot length of the input
2034 if (snaplen
!= 0 && snaplen
< wtap_snapshot_length(wth
))
2035 params
.snaplen
= snaplen
;
2038 * Now process the arguments following the input and output file
2039 * names, if any; they specify packets to include/exclude.
2041 for (i
= ws_optind
+ 2; i
< argc
; i
++)
2042 if (add_selection(argv
[i
], &max_packet_number
) == false)
2045 if (keep_em
&& max_selected
== 0) {
2046 cmdarg_err("must specify packets to keep when using -r");
2047 ret
= WS_EXIT_INVALID_OPTION
;
2052 max_packet_number
= UINT64_MAX
;
2054 if (dup_detect
|| dup_detect_by_time
) {
2055 for (i
= 0; i
< dup_window
; i
++) {
2056 memset(&fd_hash
[i
].digest
, 0, 16);
2058 nstime_set_unset(&fd_hash
[i
].frame_time
);
2062 /* Set up an array of all IDBs seen */
2063 idbs_seen
= g_array_new(FALSE
, FALSE
, sizeof(wtap_block_t
));
2065 /* Read all of the packets in turn */
2066 wtap_rec_init(&read_rec
);
2067 ws_buffer_init(&read_buf
, 1514);
2068 while (wtap_read(wth
, &read_rec
, &read_buf
, &read_err
, &read_err_info
, &data_offset
)) {
2070 * XXX - what about non-packet records in the file after this?
2071 * NRBs, DSBs, and ISBs are now written when wtap_dump_close() calls
2072 * pcapng_dump_finish(), and we handle IDBs below, but what about
2075 if (max_packet_number
<= read_count
)
2082 /* Extra actions for the first packet */
2083 if (read_count
== 1) {
2084 if (split_packet_count
!= 0 || !nstime_is_unset(&secs_per_block
)) {
2085 filename
= fileset_get_filename_by_pattern(block_cnt
++, rec
, fprefix
, fsuffix
);
2087 filename
= g_strdup(argv
[ws_optind
+1]);
2089 ws_assert(filename
);
2091 /* If we don't have an application name add one */
2092 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
) {
2093 wtap_block_add_string_option_format(g_array_index(params
.shb_hdrs
, wtap_block_t
, 0), OPT_SHB_USERAPPL
, "%s", get_appname_and_version());
2096 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
, &write_err
,
2097 &write_err_info
, compression_type
);
2100 cfile_dump_open_failure_message(filename
,
2101 write_err
, write_err_info
,
2102 out_file_type_subtype
);
2103 ret
= WS_EXIT_INVALID_FILE
;
2106 } /* first packet only handling */
2109 * Process whatever IDBs we haven't seen yet.
2111 if (!process_new_idbs(wth
, pdh
, idbs_seen
, &write_err
, &write_err_info
)) {
2112 cfile_write_failure_message(argv
[ws_optind
], filename
,
2113 write_err
, write_err_info
,
2115 out_file_type_subtype
);
2119 * Close the dump file, but don't report an error
2120 * or set the exit code, as we've already reported
2123 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2127 buf
= ws_buffer_start_ptr(&read_buf
);
2130 * Not all packets have time stamps. Only process the time
2131 * stamp if we have one.
2133 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2134 if (!nstime_is_unset(&secs_per_block
)) {
2135 if (nstime_is_unset(&block_next
)) {
2136 block_next
= rec
->ts
;
2137 nstime_add(&block_next
, &secs_per_block
);
2139 while (nstime_cmp(&rec
->ts
, &block_next
) > 0) { /* time for the next file */
2141 /* We presumably want to write the DSBs from files given
2142 * on the command line to every file.
2144 wtap_block_array_ref(params
.dsbs_initial
);
2145 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2146 cfile_close_failure_message(filename
, write_err
,
2152 /* Use the interval start time for the filename. */
2154 temp_rec
.ts
= block_next
;
2155 filename
= fileset_get_filename_by_pattern(block_cnt
++, &temp_rec
, fprefix
, fsuffix
);
2156 ws_assert(filename
);
2157 nstime_add(&block_next
, &secs_per_block
); /* reset for next interval */
2160 fprintf(stderr
, "Continuing writing in file %s\n", filename
);
2162 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
,
2163 &write_err
, &write_err_info
, compression_type
);
2166 cfile_dump_open_failure_message(filename
,
2169 out_file_type_subtype
);
2170 ret
= WS_EXIT_INVALID_FILE
;
2175 } /* time stamp handling */
2177 if (split_packet_count
!= 0) {
2178 /* time for the next file? */
2179 if (written_count
> 0 && (written_count
% split_packet_count
) == 0) {
2181 /* We presumably want to write the DSBs from files given
2182 * on the command line to every file.
2184 wtap_block_array_ref(params
.dsbs_initial
);
2185 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2186 cfile_close_failure_message(filename
, write_err
,
2193 filename
= fileset_get_filename_by_pattern(block_cnt
++, rec
, fprefix
, fsuffix
);
2194 ws_assert(filename
);
2197 fprintf(stderr
, "Continuing writing in file %s\n", filename
);
2199 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
,
2200 &write_err
, &write_err_info
, compression_type
);
2202 cfile_dump_open_failure_message(filename
,
2203 write_err
, write_err_info
,
2204 out_file_type_subtype
);
2205 ret
= WS_EXIT_INVALID_FILE
;
2209 } /* split packet handling */
2211 if (check_startstop
) {
2214 * Is the packet in the selected timeframe?
2215 * If the packet has no time stamp, the answer is "no".
2217 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2218 if (have_starttime
&& have_stoptime
) {
2219 ts_okay
= nstime_cmp(&rec
->ts
, &starttime
) >= 0 &&
2220 nstime_cmp(&rec
->ts
, &stoptime
) < 0;
2221 } else if (have_starttime
) {
2222 ts_okay
= nstime_cmp(&rec
->ts
, &starttime
) >= 0;
2223 } else if (have_stoptime
) {
2224 ts_okay
= nstime_cmp(&rec
->ts
, &stoptime
) < 0;
2229 * No selected timeframe, so all packets are "in the
2230 * selected timeframe".
2235 if (ts_okay
&& ((!selected(count
) && !keep_em
)
2236 || (selected(count
) && keep_em
))) {
2238 if (verbose
&& !dup_detect
&& !dup_detect_by_time
)
2239 fprintf(stderr
, "Packet: %" PRIu64
"\n", count
);
2241 /* We simply write it, perhaps after truncating it; we could
2242 * do other things, like modify it. */
2246 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2247 /* Do we adjust timestamps to ensure strict chronological
2249 if (do_strict_time_adjustment
) {
2250 if (previous_time
.secs
|| previous_time
.nsecs
) {
2251 if (!strict_time_adj
.is_negative
) {
2257 nstime_delta(&delta
, ¤t
, &previous_time
);
2259 if (delta
.secs
< 0 || delta
.nsecs
< 0) {
2261 * A negative delta indicates that the current packet
2262 * has an absolute timestamp less than the previous packet
2263 * that it is being compared to. This is NOT a normal
2264 * situation since trace files usually have packets in
2265 * chronological order (oldest to newest).
2266 * Copy and change rather than modify
2269 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
2271 temp_rec
.ts
.secs
= previous_time
.secs
+ strict_time_adj
.tv
.secs
;
2272 temp_rec
.ts
.nsecs
= previous_time
.nsecs
;
2273 if (temp_rec
.ts
.nsecs
+ strict_time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2276 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
- ONE_BILLION
;
2278 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
;
2284 * A negative strict time adjustment is requested.
2285 * Unconditionally set each timestamp to previous
2286 * packet's timestamp plus delta.
2287 * Copy and change rather than modify returned
2291 temp_rec
.ts
.secs
= previous_time
.secs
+ strict_time_adj
.tv
.secs
;
2292 temp_rec
.ts
.nsecs
= previous_time
.nsecs
;
2293 if (temp_rec
.ts
.nsecs
+ strict_time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2296 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
- ONE_BILLION
;
2298 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
;
2303 previous_time
= rec
->ts
;
2306 if (time_adj
.tv
.secs
!= 0) {
2307 /* Copy and change rather than modify returned rec */
2309 if (time_adj
.is_negative
)
2310 temp_rec
.ts
.secs
-= time_adj
.tv
.secs
;
2312 temp_rec
.ts
.secs
+= time_adj
.tv
.secs
;
2316 if (time_adj
.tv
.nsecs
!= 0) {
2317 /* Copy and change rather than modify returned rec */
2319 if (time_adj
.is_negative
) { /* subtract */
2320 if (temp_rec
.ts
.nsecs
< time_adj
.tv
.nsecs
) { /* borrow */
2322 temp_rec
.ts
.nsecs
+= ONE_BILLION
;
2324 temp_rec
.ts
.nsecs
-= time_adj
.tv
.nsecs
;
2326 if (temp_rec
.ts
.nsecs
+ time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2329 temp_rec
.ts
.nsecs
+= time_adj
.tv
.nsecs
- ONE_BILLION
;
2331 temp_rec
.ts
.nsecs
+= time_adj
.tv
.nsecs
;
2336 } /* time stamp adjustment */
2338 if (rec
->rec_type
== REC_TYPE_PACKET
) {
2340 /* Limit capture length to snaplen */
2341 if (rec
->rec_header
.packet_header
.caplen
> snaplen
) {
2342 /* Copy and change rather than modify returned rec */
2344 temp_rec
.rec_header
.packet_header
.caplen
= snaplen
;
2347 /* If -L, also set reported length to snaplen */
2348 if (adjlen
&& rec
->rec_header
.packet_header
.len
> snaplen
) {
2349 /* Copy and change rather than modify returned rec */
2351 temp_rec
.rec_header
.packet_header
.len
= snaplen
;
2357 * If an encapsulation type was specified, override the
2358 * encapsulation type of the packet.
2359 * Copy and change rather than modify returned rec.
2361 if (out_frame_type
!= -2) {
2363 temp_rec
.rec_header
.packet_header
.pkt_encap
= out_frame_type
;
2369 * Copy and change rather than modify returned rec.
2372 handle_chopping(chop
, &temp_rec
.rec_header
.packet_header
,
2373 &rec
->rec_header
.packet_header
, &buf
,
2377 /* set unused info */
2379 /* set unused bytes to zero so that duplicates check ignores unused bytes */
2380 set_unused_info(&rec
->rec_header
.packet_header
, buf
);
2383 /* remove vlan info */
2385 /* Copy and change rather than modify returned rec */
2387 remove_vlan_info(&rec
->rec_header
.packet_header
, buf
,
2388 &temp_rec
.rec_header
.packet_header
.caplen
);
2392 /* suppress duplicates by packet window */
2394 if (is_duplicate(buf
, rec
->rec_header
.packet_header
.caplen
)) {
2396 fprintf(stderr
, "Skipped: %" PRIu64
", Len: %u, MD5 Hash: ",
2398 rec
->rec_header
.packet_header
.caplen
);
2399 for (i
= 0; i
< 16; i
++)
2400 fprintf(stderr
, "%02x",
2401 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2402 fprintf(stderr
, "\n");
2409 fprintf(stderr
, "Packet: %" PRIu64
", Len: %u, MD5 Hash: ",
2411 rec
->rec_header
.packet_header
.caplen
);
2412 for (i
= 0; i
< 16; i
++)
2413 fprintf(stderr
, "%02x",
2414 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2415 fprintf(stderr
, "\n");
2418 } /* suppression of duplicates */
2420 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2421 /* suppress duplicates by time window */
2422 if (dup_detect_by_time
) {
2425 current
.secs
= rec
->ts
.secs
;
2426 current
.nsecs
= rec
->ts
.nsecs
;
2428 if (is_duplicate_rel_time(buf
,
2429 rec
->rec_header
.packet_header
.caplen
,
2432 fprintf(stderr
, "Skipped: %" PRIu64
", Len: %u, MD5 Hash: ",
2434 rec
->rec_header
.packet_header
.caplen
);
2435 for (i
= 0; i
< 16; i
++)
2436 fprintf(stderr
, "%02x",
2437 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2438 fprintf(stderr
, "\n");
2445 fprintf(stderr
, "Packet: %" PRIu64
", Len: %u, MD5 Hash: ",
2447 rec
->rec_header
.packet_header
.caplen
);
2448 for (i
= 0; i
< 16; i
++)
2449 fprintf(stderr
, "%02x",
2450 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2451 fprintf(stderr
, "\n");
2455 } /* suppress duplicates by time window */
2458 /* Random error mutation */
2459 do_mutation
= false;
2461 if (err_prob
> 0.0) {
2462 switch (rec
->rec_type
) {
2464 case REC_TYPE_PACKET
:
2465 caplen
= rec
->rec_header
.packet_header
.caplen
;
2469 case REC_TYPE_FT_SPECIFIC_EVENT
:
2470 case REC_TYPE_FT_SPECIFIC_REPORT
:
2471 caplen
= rec
->rec_header
.ft_specific_header
.record_len
;
2475 case REC_TYPE_SYSCALL
:
2476 caplen
= rec
->rec_header
.syscall_header
.event_filelen
;
2480 case REC_TYPE_SYSTEMD_JOURNAL_EXPORT
:
2481 caplen
= rec
->rec_header
.systemd_journal_export_header
.record_len
;
2486 if (change_offset
> caplen
) {
2487 fprintf(stderr
, "change offset %u is longer than caplen %u in packet %" PRIu64
"\n",
2488 change_offset
, caplen
, count
);
2489 do_mutation
= false;
2494 int real_data_start
= 0;
2496 /* Protect non-protocol data */
2497 switch (rec
->rec_type
) {
2499 case REC_TYPE_PACKET
:
2501 * XXX - any reason not to fuzz this part?
2503 if (rec
->rec_header
.packet_header
.pkt_encap
== WTAP_ENCAP_CATAPULT_DCT2000
)
2504 real_data_start
= find_dct2000_real_data(buf
);
2508 real_data_start
+= change_offset
;
2510 for (i
= real_data_start
; i
< (int) caplen
; i
++) {
2511 if (rand() <= err_prob
* RAND_MAX
) {
2512 err_type
= rand() / (RAND_MAX
/ ERR_WT_TOTAL
+ 1);
2514 if (err_type
< ERR_WT_BIT
) {
2515 buf
[i
] ^= 1 << (rand() / (RAND_MAX
/ 8 + 1));
2516 err_type
= ERR_WT_TOTAL
;
2518 err_type
-= ERR_WT_BYTE
;
2521 if (err_type
< ERR_WT_BYTE
) {
2522 buf
[i
] = rand() / (RAND_MAX
/ 255 + 1);
2523 err_type
= ERR_WT_TOTAL
;
2525 err_type
-= ERR_WT_BYTE
;
2528 if (err_type
< ERR_WT_ALNUM
) {
2529 buf
[i
] = ALNUM_CHARS
[rand() / (RAND_MAX
/ ALNUM_LEN
+ 1)];
2530 err_type
= ERR_WT_TOTAL
;
2532 err_type
-= ERR_WT_ALNUM
;
2535 if (err_type
< ERR_WT_FMT
) {
2536 if ((unsigned int)i
< caplen
- 2)
2537 (void) g_strlcpy((char*) &buf
[i
], "%s", 2);
2538 err_type
= ERR_WT_TOTAL
;
2540 err_type
-= ERR_WT_FMT
;
2543 if (err_type
< ERR_WT_AA
) {
2544 for (j
= i
; j
< (int) caplen
; j
++)
2550 } /* random error mutation */
2552 /* Discard all packet comments when writing */
2553 if (discard_pkt_comments
) {
2555 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(rec
->block
, OPT_COMMENT
, 0)) {
2556 temp_rec
.block_was_modified
= true;
2562 /* Find a packet comment we may need to write */
2563 if (frames_user_comments
) {
2564 const char *comment
=
2565 (const char*)g_tree_lookup(frames_user_comments
, &read_count
);
2566 if (comment
!= NULL
) {
2567 /* Copy and change rather than modify returned rec */
2570 /* Erase any existing comments before adding the new one */
2571 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(rec
->block
, OPT_COMMENT
, 0)) {
2572 temp_rec
.block_was_modified
= true;
2576 /* The comment is not modified by dumper, cast away. */
2577 wtap_block_add_string_option(rec
->block
, OPT_COMMENT
, (char *)comment
, strlen((char *)comment
));
2578 temp_rec
.block_was_modified
= true;
2581 /* Copy and change rather than modify returned rec */
2583 temp_rec
.block_was_modified
= false;
2588 if (discard_all_secrets
) {
2590 * Discard any secrets we've read since the last packet
2593 wtap_dump_discard_decryption_secrets(pdh
);
2596 /* Attempt to dump out current frame to the output file */
2597 if (!wtap_dump(pdh
, rec
, buf
, &write_err
, &write_err_info
)) {
2598 cfile_write_failure_message(argv
[ws_optind
], filename
,
2599 write_err
, write_err_info
,
2601 out_file_type_subtype
);
2605 * Close the dump file, but don't report an error
2606 * or set the exit code, as we've already reported
2609 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2615 wtap_rec_reset(&read_rec
);
2617 wtap_rec_cleanup(&read_rec
);
2618 ws_buffer_free(&read_buf
);
2621 fprintf(stderr
, "Total selected: %" PRIu64
"\n", written_count
);
2623 if (read_err
!= 0) {
2624 /* Print a message noting that the read failed somewhere along the
2626 cfile_read_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
2630 /* No valid packets found, open the outfile so we can write an
2633 filename
= g_strdup(argv
[ws_optind
+1]);
2635 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
, &write_err
,
2636 &write_err_info
, compression_type
);
2638 cfile_dump_open_failure_message(filename
,
2639 write_err
, write_err_info
,
2640 out_file_type_subtype
);
2641 ret
= WS_EXIT_INVALID_FILE
;
2647 * Process whatever IDBs we haven't seen yet.
2649 if (!process_new_idbs(wth
, pdh
, idbs_seen
, &write_err
, &write_err_info
)) {
2650 cfile_write_failure_message(argv
[ws_optind
], filename
,
2651 write_err
, write_err_info
,
2653 out_file_type_subtype
);
2657 * Close the dump file, but don't report an error
2658 * or set the exit code, as we've already reported
2661 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2665 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2666 cfile_close_failure_message(filename
, write_err
, write_err_info
);
2672 fprintf(stderr
, "%" PRIu64
" packet%s seen, %" PRIu64
" packet%s skipped with duplicate window of %i packets.\n",
2673 count
- 1, plurality(count
- 1, "", "s"), duplicate_count
,
2674 plurality(duplicate_count
, "", "s"), dup_window
);
2675 } else if (dup_detect_by_time
) {
2676 fprintf(stderr
, "%" PRIu64
" packet%s seen, %" PRIu64
" packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2677 count
- 1, plurality(count
- 1, "", "s"), duplicate_count
,
2678 plurality(duplicate_count
, "", "s"),
2679 (long)relative_time_window
.secs
,
2680 (long int)relative_time_window
.nsecs
);
2690 if (frames_user_comments
) {
2691 g_tree_destroy(frames_user_comments
);
2693 if (dsb_filenames
) {
2694 g_array_free(dsb_types
, TRUE
);
2695 g_ptr_array_free(dsb_filenames
, TRUE
);
2697 if (idbs_seen
!= NULL
) {
2698 for (unsigned b
= 0; b
< idbs_seen
->len
; b
++) {
2699 wtap_block_t if_data
= g_array_index(idbs_seen
, wtap_block_t
, b
);
2700 wtap_block_unref(if_data
);
2702 g_array_free(idbs_seen
, TRUE
);
2704 g_free(params
.idb_inf
);
2705 wtap_dump_params_cleanup(¶ms
);
2708 wtap_rec_reset(&read_rec
);
2711 if (capture_comments
!= NULL
) {
2712 g_ptr_array_free(capture_comments
, TRUE
);
2713 capture_comments
= NULL
;
2718 /* Skip meta-information read from file to return offset of real
2721 find_dct2000_real_data(uint8_t *buf
)
2725 for (n
= 0; buf
[n
] != '\0'; n
++); /* Context name */
2727 n
++; /* Context port number */
2728 for (; buf
[n
] != '\0'; n
++); /* Timestamp */
2730 for (; buf
[n
] != '\0'; n
++); /* Protocol name */
2732 for (; buf
[n
] != '\0'; n
++); /* Variant number (as string) */
2734 for (; buf
[n
] != '\0'; n
++); /* Outhdr (as string) */
2736 n
+= 2; /* Direction & encap */
2742 * We support up to 2 chopping regions in a single pass: one specified by the
2743 * positive chop length, and one by the negative chop length.
2746 handle_chopping(chop_t chop
, wtap_packet_header
*out_phdr
,
2747 const wtap_packet_header
*in_phdr
, uint8_t **buf
,
2750 /* If we're not chopping anything from one side, then the offset for that
2751 * side is meaningless. */
2752 if (chop
.len_begin
== 0)
2753 chop
.off_begin_pos
= chop
.off_begin_neg
= 0;
2754 if (chop
.len_end
== 0)
2755 chop
.off_end_pos
= chop
.off_end_neg
= 0;
2757 if (chop
.off_begin_neg
< 0) {
2758 chop
.off_begin_pos
+= in_phdr
->caplen
+ chop
.off_begin_neg
;
2759 chop
.off_begin_neg
= 0;
2761 if (chop
.off_end_pos
> 0) {
2762 chop
.off_end_neg
+= chop
.off_end_pos
- in_phdr
->caplen
;
2763 chop
.off_end_pos
= 0;
2766 /* If we've crossed chopping regions, swap them */
2767 if (chop
.len_begin
&& chop
.len_end
) {
2768 if (chop
.off_begin_pos
> ((int)in_phdr
->caplen
+ chop
.off_end_neg
)) {
2769 int tmp_len
, tmp_off
;
2771 tmp_off
= in_phdr
->caplen
+ chop
.off_end_neg
+ chop
.len_end
;
2772 tmp_len
= -chop
.len_end
;
2774 chop
.off_end_neg
= chop
.len_begin
+ chop
.off_begin_pos
- in_phdr
->caplen
;
2775 chop
.len_end
= -chop
.len_begin
;
2777 chop
.len_begin
= tmp_len
;
2778 chop
.off_begin_pos
= tmp_off
;
2782 /* Make sure we don't chop off more than we have available */
2783 if (in_phdr
->caplen
< (uint32_t)(chop
.off_begin_pos
- chop
.off_end_neg
)) {
2787 if ((uint32_t)(chop
.len_begin
- chop
.len_end
) >
2788 (in_phdr
->caplen
- (uint32_t)(chop
.off_begin_pos
- chop
.off_end_neg
))) {
2789 chop
.len_begin
= in_phdr
->caplen
- (chop
.off_begin_pos
- chop
.off_end_neg
);
2793 /* Handle chopping from the beginning. Note that if a beginning offset
2794 * was specified, we need to keep that piece */
2795 if (chop
.len_begin
> 0) {
2796 *out_phdr
= *in_phdr
;
2798 if (chop
.off_begin_pos
> 0) {
2799 memmove(*buf
+ chop
.off_begin_pos
,
2800 *buf
+ chop
.off_begin_pos
+ chop
.len_begin
,
2801 out_phdr
->caplen
- (chop
.off_begin_pos
+ chop
.len_begin
));
2803 *buf
+= chop
.len_begin
;
2805 out_phdr
->caplen
-= chop
.len_begin
;
2808 if (in_phdr
->len
> (uint32_t)chop
.len_begin
)
2809 out_phdr
->len
-= chop
.len_begin
;
2816 /* Handle chopping from the end. Note that if an ending offset was
2817 * specified, we need to keep that piece */
2818 if (chop
.len_end
< 0) {
2819 *out_phdr
= *in_phdr
;
2821 if (chop
.off_end_neg
< 0) {
2822 memmove(*buf
+ (int)out_phdr
->caplen
+ (chop
.len_end
+ chop
.off_end_neg
),
2823 *buf
+ (int)out_phdr
->caplen
+ chop
.off_end_neg
,
2826 out_phdr
->caplen
+= chop
.len_end
;
2829 if (((signed int) in_phdr
->len
+ chop
.len_end
) > 0)
2830 out_phdr
->len
+= chop
.len_end
;
2834 /*in_phdr = out_phdr;*/
2839 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2844 * indent-tabs-mode: nil
2847 * vi: set shiftwidth=4 tabstop=8 expandtab:
2848 * :indentSize=4:tabSize=8:noTabs=true: