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/strnatcmp.h>
57 #include <wsutil/str_util.h>
59 #include <wsutil/version_info.h>
60 #include <wsutil/pint.h>
61 #include <wsutil/strtoi.h>
62 #include <wsutil/ws_assert.h>
63 #include <wsutil/wslog.h>
64 #include <wiretap/wtap_opttypes.h>
66 #include "ui/failure_message.h"
68 #include "ringbuffer.h" /* For RINGBUFFER_MAX_NUM_FILES */
70 /* Additional exit codes */
71 #define CANT_EXTRACT_PREFIX 2
75 #define NANOSECS_PER_SEC 1000000000
78 * Some globals so we can pass things to various routines
83 uint64_t first
, second
;
87 * Duplicate frame detection
89 typedef struct _fd_hash_t
{
95 #define DEFAULT_DUP_DEPTH 5 /* Used with -d */
96 #define MAX_DUP_DEPTH 1000000 /* the maximum window (and actual size of fd_hash[]) for de-duplication */
98 static fd_hash_t fd_hash
[MAX_DUP_DEPTH
];
99 static int dup_window
= DEFAULT_DUP_DEPTH
;
100 static int cur_dup_entry
;
102 static uint32_t ignored_bytes
; /* Used with -I */
104 #define ONE_BILLION 1000000000
106 /* Weights of different errors we can introduce */
107 /* We should probably make these command-line arguments */
108 /* XXX - Should we add a bit-level error? */
109 #define ERR_WT_BIT 5 /* Flip a random bit */
110 #define ERR_WT_BYTE 5 /* Substitute a random byte */
111 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
112 #define ERR_WT_FMT 2 /* Substitute "%s" */
113 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
114 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
116 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
117 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
119 struct time_adjustment
{
124 typedef struct _chop_t
{
134 /* Table of user comments */
135 GTree
*frames_user_comments
;
136 GPtrArray
*capture_comments
;
138 #define MAX_SELECTIONS 512
139 static struct select_item selectfrm
[MAX_SELECTIONS
];
140 static unsigned max_selected
;
142 static int out_file_type_subtype
= WTAP_FILE_TYPE_SUBTYPE_UNKNOWN
;
143 static int out_frame_type
= -2; /* Leave frame type alone */
144 static bool verbose
; /* Not so verbose */
145 static struct time_adjustment time_adj
; /* no adjustment */
146 static nstime_t relative_time_window
; /* de-dup time window */
147 static double err_prob
= -1.0;
148 static nstime_t starttime
;
149 static bool have_starttime
;
150 static nstime_t stoptime
;
151 static bool have_stoptime
;
152 static bool check_startstop
;
153 static bool rem_vlan
;
154 static bool dup_detect
;
155 static bool dup_detect_by_time
;
156 static bool skip_radiotap
;
157 static bool discard_all_secrets
;
158 static bool discard_cap_comments
;
159 static bool set_unused
;
160 static bool discard_pkt_comments
;
161 static bool do_extract_secrets
;
163 static int do_strict_time_adjustment
;
164 static struct time_adjustment strict_time_adj
; /* strict time adjustment */
165 static nstime_t previous_time
; /* previous time */
167 static const struct {
170 } secrets_types
[] = {
171 { "tls", SECRETS_TYPE_TLS
},
172 { "ssh", SECRETS_TYPE_SSH
},
173 { "wg", SECRETS_TYPE_WIREGUARD
},
174 { "opcua", SECRETS_TYPE_OPCUA
},
177 static int find_dct2000_real_data(uint8_t *buf
);
178 static void handle_chopping(chop_t chop
, wtap_packet_header
*out_phdr
,
179 const wtap_packet_header
*in_phdr
, uint8_t **buf
,
183 abs_time_to_str_with_sec_resolution(const nstime_t
*abs_time
)
186 char *buf
= (char *)g_malloc(16);
188 tmp
= localtime(&abs_time
->secs
);
191 snprintf(buf
, 16, "%d%02d%02d%02d%02d%02d",
206 fileset_get_filename_by_pattern(unsigned idx
, const wtap_rec
*rec
,
207 char *fprefix
, char *fsuffix
)
213 snprintf(filenum
, sizeof(filenum
), "%05u", idx
% RINGBUFFER_MAX_NUM_FILES
);
214 if (rec
&& rec
->presence_flags
& WTAP_HAS_TS
) {
215 timestr
= abs_time_to_str_with_sec_resolution(&rec
->ts
);
216 abs_str
= g_strconcat(fprefix
, "_", filenum
, "_", timestr
, fsuffix
, NULL
);
219 abs_str
= g_strconcat(fprefix
, "_", filenum
, fsuffix
, NULL
);
225 fileset_extract_prefix_suffix(const char *fname
, char **fprefix
, char **fsuffix
, wtap_compression_type
*compression_typep
)
227 char *pfx
, *last_pathsep
;
229 wtap_compression_type compression_type
;
231 save_file
= g_strdup(fname
);
232 if (save_file
== NULL
) {
233 fprintf(stderr
, "editcap: Out of memory\n");
237 last_pathsep
= strrchr(save_file
, G_DIR_SEPARATOR
);
238 if (last_pathsep
== NULL
) {
239 last_pathsep
= save_file
;
241 pfx
= strrchr(last_pathsep
, '.');
243 /* The pathname has a "." in it, and it's in the last component
244 * of the pathname (because there is either only one component,
245 * i.e. last_pathsep is null as there are no path separators,
246 * or the "." is after the path separator before the last
249 * Treat it as a separator between the rest of the file name and
250 * the file name suffix, and arrange that the names given to the
251 * ring buffer files have the specified suffix, i.e. put the
252 * changing part of the name *before* the suffix. */
254 compression_type
= wtap_extension_to_compression_type(pfx
+ 1);
255 if (compression_type
!= WTAP_UNKNOWN_COMPRESSION
) {
256 char *pfx2
= strrchr(last_pathsep
, '.');
262 if (compression_typep
&& *compression_typep
== WTAP_UNKNOWN_COMPRESSION
) {
263 *compression_typep
= compression_type
;
265 /* XXX - What if there's an extension matching a compression type
266 * and the passed in compression type is known but something else?
269 *fprefix
= g_strdup(save_file
);
270 pfx
[0] = '.'; /* restore capfile_name */
271 *fsuffix
= g_strdup(pfx
);
273 /* Either there's no "." in the pathname, or it's in a directory
274 * component, so the last component has no suffix. */
275 *fprefix
= g_strdup(save_file
);
282 /* Add a selection item, a simple parser for now */
284 add_selection(char *sel
, uint64_t* max_selection
)
289 if (max_selected
>= MAX_SELECTIONS
) {
290 /* Let the user know we stopped selecting */
291 fprintf(stderr
, "Out of room for packet selections.\n");
296 fprintf(stderr
, "Add_Selected: %s\n", sel
);
298 if ((locn
= strchr(sel
, '-')) == NULL
) { /* No dash, so a single number? */
300 fprintf(stderr
, "Not inclusive ...");
302 selectfrm
[max_selected
].inclusive
= false;
303 selectfrm
[max_selected
].first
= get_uint64(sel
, "packet number");
304 if (selectfrm
[max_selected
].first
> *max_selection
)
305 *max_selection
= selectfrm
[max_selected
].first
;
308 fprintf(stderr
, " %" PRIu64
"\n", selectfrm
[max_selected
].first
);
311 fprintf(stderr
, "Inclusive ...");
313 *locn
= '\0'; /* split the range */
315 selectfrm
[max_selected
].inclusive
= true;
316 selectfrm
[max_selected
].first
= get_uint64(sel
, "beginning of packet range");
317 selectfrm
[max_selected
].second
= get_uint64(next
, "end of packet range");
319 if (selectfrm
[max_selected
].second
== 0)
321 /* Not a valid number, presume all */
322 selectfrm
[max_selected
].second
= *max_selection
= UINT64_MAX
;
324 else if (selectfrm
[max_selected
].second
> *max_selection
)
325 *max_selection
= selectfrm
[max_selected
].second
;
328 fprintf(stderr
, " %" PRIu64
", %" PRIu64
"\n", selectfrm
[max_selected
].first
,
329 selectfrm
[max_selected
].second
);
336 /* Was the packet selected? */
339 selected(uint64_t recno
)
343 for (i
= 0; i
< max_selected
; i
++) {
344 if (selectfrm
[i
].inclusive
) {
345 if (selectfrm
[i
].first
<= recno
&& selectfrm
[i
].second
>= recno
)
348 if (recno
== selectfrm
[i
].first
)
357 set_time_adjustment(char *optarg_str_p
)
366 /* skip leading whitespace */
367 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
370 /* check for a negative adjustment */
371 if (*optarg_str_p
== '-') {
372 time_adj
.is_negative
= 1;
376 /* collect whole number of seconds, if any */
377 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
381 val
= strtol(optarg_str_p
, &frac
, 10);
382 if (frac
== NULL
|| frac
== optarg_str_p
383 || val
== LONG_MIN
|| val
== LONG_MAX
) {
384 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
388 if (val
< 0) { /* implies '--' since we caught '-' above */
389 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
394 time_adj
.tv
.secs
= val
;
396 /* now collect the partial seconds, if any */
397 if (*frac
!= '\0') { /* chars left, so get fractional part */
398 val
= strtol(&(frac
[1]), &end
, 10);
399 /* if more than 9 fractional digits truncate to 9 */
400 if ((end
- &(frac
[1])) > 9) {
401 frac
[10] = 't'; /* 't' for truncate */
402 val
= strtol(&(frac
[1]), &end
, 10);
404 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
405 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
406 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
411 return true; /* no fractional digits */
414 /* adjust fractional portion from fractional to numerator
415 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
416 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
417 while(frac_digits
< 9) { /* this is frac of 10^9 */
422 time_adj
.tv
.nsecs
= (int)val
;
427 set_strict_time_adj(char *optarg_str_p
)
436 /* skip leading whitespace */
437 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
441 * check for a negative adjustment
442 * A negative strict adjustment value is a flag
443 * to adjust all frames by the specified delta time.
445 if (*optarg_str_p
== '-') {
446 strict_time_adj
.is_negative
= 1;
450 /* collect whole number of seconds, if any */
451 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
455 val
= strtol(optarg_str_p
, &frac
, 10);
456 if (frac
== NULL
|| frac
== optarg_str_p
457 || val
== LONG_MIN
|| val
== LONG_MAX
) {
458 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
462 if (val
< 0) { /* implies '--' since we caught '-' above */
463 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
468 strict_time_adj
.tv
.secs
= val
;
470 /* now collect the partial seconds, if any */
471 if (*frac
!= '\0') { /* chars left, so get fractional part */
472 val
= strtol(&(frac
[1]), &end
, 10);
473 /* if more than 9 fractional digits truncate to 9 */
474 if ((end
- &(frac
[1])) > 9) {
475 frac
[10] = 't'; /* 't' for truncate */
476 val
= strtol(&(frac
[1]), &end
, 10);
478 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
479 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
480 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
485 return true; /* no fractional digits */
488 /* adjust fractional portion from fractional to numerator
489 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
490 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
491 while(frac_digits
< 9) { /* this is frac of 10^9 */
496 strict_time_adj
.tv
.nsecs
= (int)val
;
501 set_rel_time(char *optarg_str_p
)
510 /* skip leading whitespace */
511 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
514 /* ignore negative adjustment */
515 if (*optarg_str_p
== '-')
518 /* collect whole number of seconds, if any */
519 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
523 val
= strtol(optarg_str_p
, &frac
, 10);
524 if (frac
== NULL
|| frac
== optarg_str_p
525 || val
== LONG_MIN
|| val
== LONG_MAX
) {
526 fprintf(stderr
, "1: editcap: \"%s\" isn't a valid rel time value\n",
530 if (val
< 0) { /* implies '--' since we caught '-' above */
531 fprintf(stderr
, "2: editcap: \"%s\" isn't a valid rel time value\n",
536 relative_time_window
.secs
= val
;
538 /* now collect the partial seconds, if any */
539 if (*frac
!= '\0') { /* chars left, so get fractional part */
540 val
= strtol(&(frac
[1]), &end
, 10);
541 /* if more than 9 fractional digits truncate to 9 */
542 if ((end
- &(frac
[1])) > 9) {
543 frac
[10] = 't'; /* 't' for truncate */
544 val
= strtol(&(frac
[1]), &end
, 10);
546 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
547 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
548 fprintf(stderr
, "3: editcap: \"%s\" isn't a valid rel time value\n",
553 return true; /* no fractional digits */
556 /* adjust fractional portion from fractional to numerator
557 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
558 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
559 while(frac_digits
< 9) { /* this is frac of 10^9 */
564 relative_time_window
.nsecs
= (int)val
;
568 #define SLL_ADDRLEN 8 /* length of address field */
570 uint16_t sll_pkttype
; /* packet type */
571 uint16_t sll_hatype
; /* link-layer address type */
572 uint16_t sll_halen
; /* link-layer address length */
573 uint8_t sll_addr
[SLL_ADDRLEN
]; /* link-layer address */
574 uint16_t sll_protocol
; /* protocol */
578 uint16_t sll2_protocol
; /* protocol */
579 uint16_t sll2_reserved_mbz
; /* reserved - must be zero */
580 uint32_t sll2_if_index
; /* 1-based interface index */
581 uint16_t sll2_hatype
; /* link-layer address type */
582 uint8_t sll2_pkttype
; /* packet type */
583 uint8_t sll2_halen
; /* link-layer address length */
584 uint8_t sll2_addr
[SLL_ADDRLEN
]; /* link-layer address */
589 sll_remove_vlan_info(uint8_t* fd
, uint32_t* len
) {
590 if (pntoh16(fd
+ offsetof(struct sll_header
, sll_protocol
)) == ETHERTYPE_VLAN
) {
592 /* point to start of vlan */
593 fd
= fd
+ offsetof(struct sll_header
, sll_protocol
);
594 /* bytes to read after vlan info */
595 rest_len
= *len
- (offsetof(struct sll_header
, sll_protocol
) + VLAN_SIZE
);
596 /* remove vlan info from packet */
597 memmove(fd
, fd
+ VLAN_SIZE
, rest_len
);
605 sll_set_unused_info(uint8_t* fd
) {
607 ha_len
= pntoh16(fd
+ offsetof(struct sll_header
, sll_halen
));
609 if (ha_len
< SLL_ADDRLEN
) {
611 unused
= SLL_ADDRLEN
- ha_len
;
612 /* point to end of sll_ddr */
613 fd
= fd
+ offsetof(struct sll_header
, sll_addr
) + ha_len
;
614 /* set zeros in the unused data */
615 memset(fd
, 0, unused
);
620 sll2_set_unused_info(uint8_t* fd
) {
622 ha_len
= *(fd
+ offsetof(struct sll2_header
, sll2_halen
));
624 if (ha_len
< SLL_ADDRLEN
) {
626 unused
= SLL_ADDRLEN
- ha_len
;
627 /* point to end of sll2_addr */
628 fd
= fd
+ offsetof(struct sll2_header
, sll2_addr
) + ha_len
;
629 /* set zeros in the unused data */
630 memset(fd
, 0, unused
);
635 remove_vlan_info(const wtap_packet_header
*phdr
, uint8_t* fd
, uint32_t* len
) {
636 switch (phdr
->pkt_encap
) {
638 sll_remove_vlan_info(fd
, len
);
641 /* no support for current pkt_encap */
647 set_unused_info(const wtap_packet_header
*phdr
, uint8_t* fd
) {
648 switch (phdr
->pkt_encap
) {
650 sll_set_unused_info(fd
);
652 case WTAP_ENCAP_SLL2
:
653 sll2_set_unused_info(fd
);
656 /* no support for current pkt_encap */
662 is_duplicate(uint8_t* fd
, uint32_t len
) {
664 const struct ieee80211_radiotap_header
* tap_header
;
666 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
667 uint32_t offset
= ignored_bytes
;
671 if (len
<= ignored_bytes
) {
675 /* Get the size of radiotap header and use that as offset (-p option) */
676 if (skip_radiotap
== true) {
677 tap_header
= (const struct ieee80211_radiotap_header
*)fd
;
678 offset
= pletoh16(&tap_header
->it_len
);
683 new_fd
= &fd
[offset
];
684 new_len
= len
- (offset
);
687 if (cur_dup_entry
>= dup_window
)
690 /* Calculate our digest */
691 gcry_md_hash_buffer(GCRY_MD_MD5
, fd_hash
[cur_dup_entry
].digest
, new_fd
, new_len
);
693 fd_hash
[cur_dup_entry
].len
= len
;
695 /* Look for duplicates */
696 for (i
= 0; i
< dup_window
; i
++) {
697 if (i
== cur_dup_entry
)
700 if (fd_hash
[i
].len
== fd_hash
[cur_dup_entry
].len
701 && memcmp(fd_hash
[i
].digest
, fd_hash
[cur_dup_entry
].digest
, 16) == 0) {
710 is_duplicate_rel_time(uint8_t* fd
, uint32_t len
, const nstime_t
*current
) {
713 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
714 uint32_t offset
= ignored_bytes
;
718 if (len
<= ignored_bytes
) {
722 new_fd
= &fd
[offset
];
723 new_len
= len
- (offset
);
726 if (cur_dup_entry
>= dup_window
)
729 /* Calculate our digest */
730 gcry_md_hash_buffer(GCRY_MD_MD5
, fd_hash
[cur_dup_entry
].digest
, new_fd
, new_len
);
732 fd_hash
[cur_dup_entry
].len
= len
;
733 fd_hash
[cur_dup_entry
].frame_time
.secs
= current
->secs
;
734 fd_hash
[cur_dup_entry
].frame_time
.nsecs
= current
->nsecs
;
737 * Look for relative time related duplicates.
738 * This is hopefully a reasonably efficient mechanism for
739 * finding duplicates by rel time in the fd_hash[] cache.
740 * We check starting from the most recently added hash
741 * entries and work backwards towards older packets.
742 * This approach allows the dup test to be terminated
743 * when the relative time of a cached entry is found to
744 * be beyond the dup time window.
746 * Of course this assumes that the input trace file is
747 * "well-formed" in the sense that the packet timestamps are
748 * in strict chronologically increasing order (which is NOT
749 * always the case!!).
751 * The fd_hash[] table was deliberately created large (1,000,000).
752 * Looking for time related duplicates in large trace files with
753 * non-fractional dup time window values can potentially take
754 * a long time to complete.
757 for (i
= cur_dup_entry
- 1;; i
--) {
764 if (i
== cur_dup_entry
) {
766 * We've decremented back to where we started.
772 if (nstime_is_unset(&(fd_hash
[i
].frame_time
))) {
774 * We've decremented to an unused fd_hash[] entry.
780 nstime_delta(&delta
, current
, &fd_hash
[i
].frame_time
);
782 if (delta
.secs
< 0 || delta
.nsecs
< 0) {
784 * A negative delta implies that the current packet
785 * has an absolute timestamp less than the cached packet
786 * that it is being compared to. This is NOT a normal
787 * situation since trace files usually have packets in
788 * chronological order (oldest to newest).
790 * There are several possible ways to deal with this:
791 * 1. 'continue' dup checking with the next cached frame.
792 * 2. 'break' from looking for a duplicate of the current frame.
793 * 3. Take the absolute value of the delta and see if that
794 * falls within the specified dup time window.
796 * Currently this code does option 1. But it would pretty
797 * easy to add yet-another-editcap-option to select one of
798 * the other behaviors for dealing with out-of-sequence
804 cmp
= nstime_cmp(&delta
, &relative_time_window
);
808 * The delta time indicates that we are now looking at
809 * cached packets beyond the specified dup time window.
813 } else if (fd_hash
[i
].len
== fd_hash
[cur_dup_entry
].len
814 && memcmp(fd_hash
[i
].digest
, fd_hash
[cur_dup_entry
].digest
, 16) == 0) {
823 print_usage(FILE *output
)
825 fprintf(output
, "\n");
826 fprintf(output
, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
827 fprintf(output
, "\n");
828 fprintf(output
, "<infile> and <outfile> must both be present; use '-' for stdin or stdout.\n");
829 fprintf(output
, "A single packet or a range of packets can be selected.\n");
830 fprintf(output
, "\n");
831 fprintf(output
, "Packet selection:\n");
832 fprintf(output
, " -r keep the selected packets; default is to delete them.\n");
833 fprintf(output
, " -A <start time> only read packets whose timestamp is after (or equal\n");
834 fprintf(output
, " to) the given time.\n");
835 fprintf(output
, " -B <stop time> only read packets whose timestamp is before the\n");
836 fprintf(output
, " given time.\n");
837 fprintf(output
, " Time format for -A/-B options is\n");
838 fprintf(output
, " YYYY-MM-DDThh:mm:ss[.nnnnnnnnn][Z|+-hh:mm]\n");
839 fprintf(output
, " Unix epoch timestamps are also supported.\n");
840 fprintf(output
, "\n");
841 fprintf(output
, "Duplicate packet removal:\n");
842 fprintf(output
, " --novlan remove vlan info from packets before checking for duplicates.\n");
843 fprintf(output
, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH
);
844 fprintf(output
, " -D <dup window> remove packet if duplicate; configurable <dup window>.\n");
845 fprintf(output
, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH
);
846 fprintf(output
, " NOTE: A <dup window> of 0 with -V (verbose option) is\n");
847 fprintf(output
, " useful to print MD5 hashes.\n");
848 fprintf(output
, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
849 fprintf(output
, " LESS THAN <dup time window> prior to current packet.\n");
850 fprintf(output
, " A <dup time window> is specified in relative seconds\n");
851 fprintf(output
, " (e.g. 0.000001).\n");
852 fprintf(output
, " NOTE: The use of the 'Duplicate packet removal' options with\n");
853 fprintf(output
, " other editcap options except -V may not always work as expected.\n");
854 fprintf(output
, " Specifically the -r, -t or -S options will very likely NOT have the\n");
855 fprintf(output
, " desired effect if combined with the -d, -D or -w.\n");
856 fprintf(output
, " --skip-radiotap-header skip radiotap header when checking for packet duplicates.\n");
857 fprintf(output
, " Useful when processing packets captured by multiple radios\n");
858 fprintf(output
, " on the same channel in the vicinity of each other.\n");
859 fprintf(output
, " --set-unused set unused byts to zero in sll link addr.\n");
860 fprintf(output
, "\n");
861 fprintf(output
, "Packet manipulation:\n");
862 fprintf(output
, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
863 fprintf(output
, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
864 fprintf(output
, " chop at the packet beginning, negative values at the\n");
865 fprintf(output
, " packet end. If an optional offset precedes the length,\n");
866 fprintf(output
, " then the bytes chopped will be offset from that value.\n");
867 fprintf(output
, " Positive offsets are from the packet beginning,\n");
868 fprintf(output
, " negative offsets are from the packet end. You can use\n");
869 fprintf(output
, " this option more than once, allowing up to 2 chopping\n");
870 fprintf(output
, " regions within a packet provided that at least 1\n");
871 fprintf(output
, " choplen is positive and at least 1 is negative.\n");
872 fprintf(output
, " -L adjust the frame (i.e. reported) length when chopping\n");
873 fprintf(output
, " and/or snapping.\n");
874 fprintf(output
, " -t <time adjustment> adjust the timestamp of each packet.\n");
875 fprintf(output
, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
876 fprintf(output
, " -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
877 fprintf(output
, " strict chronological increasing order. The <strict\n");
878 fprintf(output
, " adjustment> is specified in relative seconds with\n");
879 fprintf(output
, " values of 0 or 0.000001 being the most reasonable.\n");
880 fprintf(output
, " A negative adjustment value will modify timestamps so\n");
881 fprintf(output
, " that each packet's delta time is the absolute value\n");
882 fprintf(output
, " of the adjustment specified. A value of -0 will set\n");
883 fprintf(output
, " all packets to the timestamp of the first packet.\n");
884 fprintf(output
, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
885 fprintf(output
, " a particular packet byte will be randomly changed.\n");
886 fprintf(output
, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
887 fprintf(output
, " beginning of the packet. This allows one to preserve some\n");
888 fprintf(output
, " bytes, in order to have some headers untouched.\n");
889 fprintf(output
, " --seed <seed> When used in conjunction with -E, set the seed to use for\n");
890 fprintf(output
, " the pseudo-random number generator. This allows one to\n");
891 fprintf(output
, " repeat a particular sequence of errors.\n");
892 fprintf(output
, " -I <bytes to ignore> ignore the specified number of bytes at the beginning\n");
893 fprintf(output
, " of the frame during MD5 hash calculation, unless the\n");
894 fprintf(output
, " frame is too short, then the full frame is used.\n");
895 fprintf(output
, " Useful to remove duplicated packets taken on\n");
896 fprintf(output
, " several routers (different mac addresses for\n");
897 fprintf(output
, " example).\n");
898 fprintf(output
, " e.g. -I 26 in case of Ether/IP will ignore\n");
899 fprintf(output
, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
900 fprintf(output
, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
901 fprintf(output
, "\n");
902 fprintf(output
, "Output File(s):\n");
903 fprintf(output
, " if the output file(s) have the .gz extension, then\n");
904 fprintf(output
, " gzip compression will be used\n");
905 fprintf(output
, " -c <packets per file> split the packet output to different files based on\n");
906 fprintf(output
, " uniform packet counts with a maximum of\n");
907 fprintf(output
, " <packets per file> each.\n");
908 fprintf(output
, " -i <seconds per file> split the packet output to different files based on\n");
909 fprintf(output
, " uniform time intervals with a maximum of\n");
910 fprintf(output
, " <seconds per file> each.\n");
911 fprintf(output
, " -F <capture type> set the output file type; default is pcapng.\n");
912 fprintf(output
, " An empty \"-F\" option will list the file types.\n");
913 fprintf(output
, " -T <encap type> set the output file encapsulation type; default is the\n");
914 fprintf(output
, " same as the input file. An empty \"-T\" option will\n");
915 fprintf(output
, " list the encapsulation types.\n");
916 fprintf(output
, " --inject-secrets <type>,<file> Insert decryption secrets from <file>. List\n");
917 fprintf(output
, " supported secret types with \"--inject-secrets help\".\n");
918 fprintf(output
, " --extract-secrets Extract decryption secrets into the output file instead.\n");
919 fprintf(output
, " Incompatible with other options besides -V.\n");
920 fprintf(output
, " --discard-all-secrets Discard all decryption secrets from the input file\n");
921 fprintf(output
, " when writing the output file. Does not discard\n");
922 fprintf(output
, " secrets added by \"--inject-secrets\" in the same\n");
923 fprintf(output
, " command line.\n");
924 fprintf(output
, " --capture-comment <comment>\n");
925 fprintf(output
, " Add a capture file comment, if supported.\n");
926 fprintf(output
, " --discard-capture-comment\n");
927 fprintf(output
, " Discard capture file comments from the input file\n");
928 fprintf(output
, " when writing the output file. Does not discard\n");
929 fprintf(output
, " comments added by \"--capture-comment\" in the same\n");
930 fprintf(output
, " command line.\n");
931 fprintf(output
, " --discard-packet-comments\n");
932 fprintf(output
, " Discard all packet comments from the input file\n");
933 fprintf(output
, " when writing the output file. Does not discard\n");
934 fprintf(output
, " comments added by \"-a\" in the same command line.\n");
935 fprintf(output
, " --compress <type> Compress the output file using the type compression format.\n");
936 fprintf(output
, "\n");
937 fprintf(output
, "Miscellaneous:\n");
938 fprintf(output
, " -h, --help display this help and exit.\n");
939 fprintf(output
, " -V verbose output.\n");
940 fprintf(output
, " If -V is used with any of the 'Duplicate Packet\n");
941 fprintf(output
, " Removal' options (-d, -D or -w) then Packet lengths\n");
942 fprintf(output
, " and MD5 hashes are printed to standard-error.\n");
943 fprintf(output
, " -v, --version print version information and exit.\n");
947 const char *sstr
; /* The short string */
948 const char *lstr
; /* The long string */
952 string_nat_compare(const void *a
, const void *b
)
954 return ws_ascii_strnatcmp(((const struct string_elem
*)a
)->sstr
,
955 ((const struct string_elem
*)b
)->sstr
);
959 string_elem_print(void *data
, void *stream_ptr
)
961 fprintf((FILE *) stream_ptr
, " %s - %s\n",
962 ((struct string_elem
*)data
)->sstr
,
963 ((struct string_elem
*)data
)->lstr
);
967 list_capture_types(FILE *stream
) {
968 GArray
*writable_type_subtypes
;
970 fprintf(stream
, "editcap: The available capture file types for the \"-F\" flag are:\n");
971 writable_type_subtypes
= wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME
);
972 for (unsigned i
= 0; i
< writable_type_subtypes
->len
; i
++) {
973 int ft
= g_array_index(writable_type_subtypes
, int, i
);
974 fprintf(stream
, " %s - %s\n", wtap_file_type_subtype_name(ft
),
975 wtap_file_type_subtype_description(ft
));
977 g_array_free(writable_type_subtypes
, TRUE
);
981 list_encap_types(FILE *stream
) {
983 struct string_elem
*encaps
;
986 encaps
= g_new(struct string_elem
, WTAP_NUM_ENCAP_TYPES
);
987 fprintf(stream
, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
988 for (i
= 0; i
< WTAP_NUM_ENCAP_TYPES
; i
++) {
989 encaps
[i
].sstr
= wtap_encap_name(i
);
990 if (encaps
[i
].sstr
!= NULL
) {
991 encaps
[i
].lstr
= wtap_encap_description(i
);
992 list
= g_slist_insert_sorted(list
, &encaps
[i
], string_nat_compare
);
995 g_slist_foreach(list
, string_elem_print
, stream
);
1001 list_output_compression_types(void) {
1002 GSList
*output_compression_types
;
1004 fprintf(stderr
, "editcap: The available output compress type(s) for the \"--compress\" flag are:\n");
1005 output_compression_types
= wtap_get_all_output_compression_type_names_list();
1006 for (GSList
*compression_type
= output_compression_types
;
1007 compression_type
!= NULL
;
1008 compression_type
= g_slist_next(compression_type
)) {
1009 fprintf(stderr
, " %s\n", (const char *)compression_type
->data
);
1012 g_slist_free(output_compression_types
);
1016 list_secrets_types(FILE *stream
)
1018 for (unsigned i
= 0; i
< G_N_ELEMENTS(secrets_types
); i
++) {
1019 fprintf(stream
, " %s\n", secrets_types
[i
].str
);
1024 lookup_secrets_type(const char *type
)
1026 for (unsigned i
= 0; i
< G_N_ELEMENTS(secrets_types
); i
++) {
1027 if (!strcmp(secrets_types
[i
].str
, type
)) {
1028 return secrets_types
[i
].id
;
1035 validate_secrets_file(const char *filename
, uint32_t secrets_type
, const char *data
)
1037 if (secrets_type
== SECRETS_TYPE_TLS
) {
1039 * A key log file is unlikely going to look like either:
1040 * - a PEM-encoded private key file.
1041 * - a BER-encoded PKCS #12 file ("PFX file"). (Look for a Constructed
1042 * SEQUENCE tag, e.g. bytes 0x30 which happens to be ASCII '0'.)
1044 if (g_str_has_prefix(data
, "-----BEGIN ") || data
[0] == 0x30) {
1046 "editcap: Warning: \"%s\" is not a key log file, but an unsupported private key file. Decryption will not work.\n",
1053 framenum_compare(const void *a
, const void *b
, void *user_data _U_
)
1055 uint64_t *frame_a
= (uint64_t*)a
;
1056 uint64_t *frame_b
= (uint64_t*)b
;
1057 if (*frame_a
< *frame_b
)
1060 if (*frame_a
> *frame_b
)
1067 * Report an error in command-line arguments.
1070 editcap_cmdarg_err(const char *msg_format
, va_list ap
)
1072 fprintf(stderr
, "editcap: ");
1073 vfprintf(stderr
, msg_format
, ap
);
1074 fprintf(stderr
, "\n");
1078 * Report additional information for an error in command-line arguments.
1081 editcap_cmdarg_err_cont(const char *msg_format
, va_list ap
)
1083 vfprintf(stderr
, msg_format
, ap
);
1084 fprintf(stderr
, "\n");
1087 static wtap_dumper
*
1088 editcap_dump_open(const char *filename
, const wtap_dump_params
*params
,
1089 GArray
*idbs_seen
, int *err
, char **err_info
,
1090 wtap_compression_type compression_type
)
1094 if (strcmp(filename
, "-") == 0) {
1095 /* Write to the standard output. */
1096 pdh
= wtap_dump_open_stdout(out_file_type_subtype
, compression_type
,
1097 params
, err
, err_info
);
1099 pdh
= wtap_dump_open(filename
, out_file_type_subtype
, compression_type
,
1100 params
, err
, err_info
);
1106 * If the output file supports identifying the interfaces on which
1107 * packets arrive, add all the IDBs we've seen so far.
1109 * That mean that the abstract interface provided by libwiretap
1110 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1112 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh
),
1113 WTAP_BLOCK_IF_ID_AND_INFO
) != BLOCK_NOT_SUPPORTED
) {
1114 for (unsigned i
= 0; i
< idbs_seen
->len
; i
++) {
1115 wtap_block_t if_data
= g_array_index(idbs_seen
, wtap_block_t
, i
);
1116 wtap_block_t if_data_copy
;
1119 * Make a copy of this IDB, so that we can change the
1120 * encapsulation type without trashing the original.
1122 if_data_copy
= wtap_block_make_copy(if_data
);
1125 * If an encapsulation type was specified, override the
1126 * encapsulation type of the interface.
1128 if (out_frame_type
!= -2) {
1129 wtapng_if_descr_mandatory_t
*if_mand
;
1131 if_mand
= (wtapng_if_descr_mandatory_t
*)wtap_block_get_mandatory_data(if_data_copy
);
1132 if_mand
->wtap_encap
= out_frame_type
;
1136 * Add this possibly-modified IDB to the file to which
1137 * we're currently writing.
1139 if (!wtap_dump_add_idb(pdh
, if_data_copy
, err
, err_info
)) {
1141 char *close_err_info
;
1143 wtap_dump_close(pdh
, NULL
, &close_err
, &close_err_info
);
1144 g_free(close_err_info
);
1145 wtap_block_unref(if_data_copy
);
1150 * Release the copy - wtap_dump_add_idb() makes its own copy.
1152 wtap_block_unref(if_data_copy
);
1160 process_new_idbs(wtap
*wth
, wtap_dumper
*pdh
, GArray
*idbs_seen
,
1161 int *err
, char **err_info
)
1163 wtap_block_t if_data
;
1165 while ((if_data
= wtap_get_next_interface_description(wth
)) != NULL
) {
1167 * Only add interface blocks if the output file supports (meaning
1170 * That mean that the abstract interface provided by libwiretap
1171 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1173 if (pdh
!= NULL
&& wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh
),
1174 WTAP_BLOCK_IF_ID_AND_INFO
) != BLOCK_NOT_SUPPORTED
) {
1175 wtap_block_t if_data_copy
;
1178 * Make a copy of this IDB, so that we can change the
1179 * encapsulation type without trashing the original.
1181 if_data_copy
= wtap_block_make_copy(if_data
);
1184 * If an encapsulation type was specified, override the
1185 * encapsulation type of the interface.
1187 if (out_frame_type
!= -2) {
1188 wtapng_if_descr_mandatory_t
*if_mand
;
1190 if_mand
= (wtapng_if_descr_mandatory_t
*)wtap_block_get_mandatory_data(if_data_copy
);
1191 if_mand
->wtap_encap
= out_frame_type
;
1195 * Add this possibly-modified IDB to the file to which
1196 * we're currently writing.
1198 if (!wtap_dump_add_idb(pdh
, if_data_copy
, err
, err_info
))
1202 * Release the copy - wtap_dump_add_idb() makes its own copy.
1204 wtap_block_unref(if_data_copy
);
1207 * Also add an unmodified copy to the set of IDBs we've seen,
1208 * in case we start writing to another file (which would be
1209 * of the same type as the current file, and thus will also
1210 * require interface IDs).
1212 if_data_copy
= wtap_block_make_copy(if_data
);
1213 g_array_append_val(idbs_seen
, if_data_copy
);
1220 extract_secrets(wtap
*wth
, char* filename
, int *err
, char **err_info
)
1225 char *fprefix
= NULL
;
1226 char *fsuffix
= NULL
;
1228 /* Read all of the packets in turn */
1229 wtap_rec_init(&read_rec
);
1230 ws_buffer_init(&read_buf
, 1514);
1231 while (wtap_read(wth
, &read_rec
, &read_buf
, err
, err_info
, &offset
)) {
1232 /* Do we want to respect the max packet number on the command line?
1233 * Probably more confusing than it's worth, because a user might
1234 * not know if a DSB is at the end of the file.
1236 wtap_rec_reset(&read_rec
);
1238 wtap_rec_cleanup(&read_rec
);
1239 ws_buffer_free(&read_buf
);
1241 wtapng_dsb_mandatory_t
*dsb
;
1242 if (strcmp(filename
, "-") == 0) {
1243 /* Sure. Why not. */
1244 for (unsigned dsb_num
= 0; dsb_num
< wtap_file_get_num_dsbs(wth
); ++dsb_num
) {
1245 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, dsb_num
));
1247 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to standard out.\n",
1248 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
);
1250 if (fwrite(dsb
->secrets_data
, 1, dsb
->secrets_len
, stdout
) != dsb
->secrets_len
) {
1254 } else if (wtap_file_get_num_dsbs(wth
) == 1) {
1255 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, 0));
1257 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1258 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
,
1261 if (!write_file_binary_mode(filename
, dsb
->secrets_data
, dsb
->secrets_len
)) {
1265 /* We have more than one DSB, so write multiple files. While for some
1266 * types, we could combine the information from different DSBs togther
1267 * (and most of those are text-based, so we'd want to write in text
1268 * mode so that the line endings are uniform (which makes testing
1269 * harder), we don't know that for every type.
1271 if (!fileset_extract_prefix_suffix(filename
, &fprefix
, &fsuffix
, NULL
)) {
1272 return CANT_EXTRACT_PREFIX
;
1274 char *extract_filename
;
1275 for (unsigned dsb_num
= 0; dsb_num
< wtap_file_get_num_dsbs(wth
); ++dsb_num
) {
1276 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, dsb_num
));
1277 extract_filename
= fileset_get_filename_by_pattern(dsb_num
, NULL
, fprefix
, fsuffix
);
1279 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1280 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
,
1283 if (!write_file_binary_mode(extract_filename
, dsb
->secrets_data
, dsb
->secrets_len
)) {
1284 /* write_file_binary_mode already reports failures */
1285 g_free(extract_filename
);
1291 g_free(extract_filename
);
1296 return EXIT_SUCCESS
;
1300 main(int argc
, char *argv
[])
1302 char *configuration_init_error
;
1304 int i
, j
, read_err
, write_err
;
1305 char *read_err_info
, *write_err_info
;
1308 #define LONGOPT_NO_VLAN LONGOPT_BASE_APPLICATION+1
1309 #define LONGOPT_SKIP_RADIOTAP_HEADER LONGOPT_BASE_APPLICATION+2
1310 #define LONGOPT_SEED LONGOPT_BASE_APPLICATION+3
1311 #define LONGOPT_INJECT_SECRETS LONGOPT_BASE_APPLICATION+4
1312 #define LONGOPT_DISCARD_ALL_SECRETS LONGOPT_BASE_APPLICATION+5
1313 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
1314 #define LONGOPT_DISCARD_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+7
1315 #define LONGOPT_SET_UNUSED LONGOPT_BASE_APPLICATION+8
1316 #define LONGOPT_DISCARD_PACKET_COMMENTS LONGOPT_BASE_APPLICATION+9
1317 #define LONGOPT_EXTRACT_SECRETS LONGOPT_BASE_APPLICATION+10
1318 #define LONGOPT_COMPRESS LONGOPT_BASE_APPLICATION+11
1320 static const struct ws_option long_options
[] = {
1321 {"novlan", ws_no_argument
, NULL
, LONGOPT_NO_VLAN
},
1322 {"skip-radiotap-header", ws_no_argument
, NULL
, LONGOPT_SKIP_RADIOTAP_HEADER
},
1323 {"seed", ws_required_argument
, NULL
, LONGOPT_SEED
},
1324 {"inject-secrets", ws_required_argument
, NULL
, LONGOPT_INJECT_SECRETS
},
1325 {"discard-all-secrets", ws_no_argument
, NULL
, LONGOPT_DISCARD_ALL_SECRETS
},
1326 {"help", ws_no_argument
, NULL
, 'h'},
1327 {"version", ws_no_argument
, NULL
, 'v'},
1328 {"capture-comment", ws_required_argument
, NULL
, LONGOPT_CAPTURE_COMMENT
},
1329 {"discard-capture-comment", ws_no_argument
, NULL
, LONGOPT_DISCARD_CAPTURE_COMMENT
},
1330 {"set-unused", ws_no_argument
, NULL
, LONGOPT_SET_UNUSED
},
1331 {"discard-packet-comments", ws_no_argument
, NULL
, LONGOPT_DISCARD_PACKET_COMMENTS
},
1332 {"extract-secrets", ws_no_argument
, NULL
, LONGOPT_EXTRACT_SECRETS
},
1333 {"compress", ws_required_argument
, NULL
, LONGOPT_COMPRESS
},
1338 uint32_t snaplen
= 0; /* No limit */
1339 chop_t chop
= {0, 0, 0, 0, 0, 0}; /* No chop */
1340 bool adjlen
= false;
1341 wtap_dumper
*pdh
= NULL
;
1342 GArray
*idbs_seen
= NULL
;
1344 uint64_t duplicate_count
= 0;
1345 int64_t data_offset
;
1348 uint64_t read_count
= 0;
1349 uint64_t split_packet_count
= 0;
1350 uint64_t written_count
= 0;
1351 char *filename
= NULL
;
1353 nstime_t secs_per_block
= NSTIME_INIT_UNSET
;
1355 nstime_t block_next
= NSTIME_INIT_UNSET
;
1356 char *fprefix
= NULL
;
1357 char *fsuffix
= NULL
;
1358 uint32_t change_offset
= 0;
1359 uint64_t max_packet_number
= 0;
1360 GArray
*dsb_types
= NULL
;
1361 GPtrArray
*dsb_filenames
= NULL
;
1364 const wtap_rec
*rec
;
1366 wtap_dump_params params
= WTAP_DUMP_PARAMS_INIT
;
1367 char *shb_user_appl
;
1370 int ret
= EXIT_SUCCESS
;
1371 bool valid_seed
= false;
1372 unsigned int seed
= 0;
1373 bool edit_option_specified
= false;
1374 wtap_compression_type compression_type
= WTAP_UNKNOWN_COMPRESSION
;
1376 cmdarg_err_init(editcap_cmdarg_err
, editcap_cmdarg_err_cont
);
1377 memset(&read_rec
, 0, sizeof *rec
);
1379 /* Initialize log handler early so we can have proper logging during startup. */
1380 ws_log_init("editcap", vcmdarg_err
);
1382 /* Early logging command-line initialization. */
1383 ws_log_parse_args(&argc
, argv
, vcmdarg_err
, WS_EXIT_INVALID_OPTION
);
1385 ws_noisy("Finished log init and parsing command line log arguments");
1388 create_app_running_mutex();
1391 /* Initialize the version information. */
1392 ws_init_version_info("Editcap", NULL
, NULL
);
1395 * Get credential information for later use.
1397 init_process_policies();
1400 * Attempt to get the pathname of the directory containing the
1403 configuration_init_error
= configuration_init(argv
[0], NULL
);
1404 if (configuration_init_error
!= NULL
) {
1405 cmdarg_err("Can't get pathname of directory containing the editcap program: %s.",
1406 configuration_init_error
);
1407 g_free(configuration_init_error
);
1410 init_report_failure_message("editcap");
1414 /* Process the options */
1415 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) {
1416 if (opt
!= LONGOPT_EXTRACT_SECRETS
&& opt
!= 'V') {
1417 edit_option_specified
= true;
1420 case LONGOPT_NO_VLAN
:
1426 case LONGOPT_SKIP_RADIOTAP_HEADER
:
1428 skip_radiotap
= true;
1434 if (sscanf(ws_optarg
, "%u", &seed
) != 1) {
1435 cmdarg_err("\"%s\" isn't a valid seed", ws_optarg
);
1436 ret
= WS_EXIT_INVALID_OPTION
;
1443 case LONGOPT_INJECT_SECRETS
:
1445 uint32_t secrets_type_id
= 0;
1446 const char *secrets_filename
= NULL
;
1447 if (strcmp("help", ws_optarg
) == 0) {
1448 list_secrets_types(stdout
);
1451 char **splitted
= g_strsplit(ws_optarg
, ",", 2);
1452 if (splitted
[0] && splitted
[0][0] != '\0') {
1453 secrets_type_id
= lookup_secrets_type(splitted
[0]);
1454 if (secrets_type_id
== 0) {
1455 cmdarg_err("\"%s\" isn't a valid secrets type", splitted
[0]);
1456 g_strfreev(splitted
);
1457 ret
= WS_EXIT_INVALID_OPTION
;
1460 secrets_filename
= splitted
[1];
1462 cmdarg_err("no secrets type was specified for --inject-secrets");
1463 g_strfreev(splitted
);
1464 ret
= WS_EXIT_INVALID_OPTION
;
1467 if (!dsb_filenames
) {
1468 dsb_types
= g_array_new(FALSE
, FALSE
, sizeof(uint32_t));
1469 dsb_filenames
= g_ptr_array_new_with_free_func(g_free
);
1471 g_array_append_val(dsb_types
, secrets_type_id
);
1472 g_ptr_array_add(dsb_filenames
, g_strdup(secrets_filename
));
1473 g_strfreev(splitted
);
1477 case LONGOPT_DISCARD_ALL_SECRETS
:
1479 discard_all_secrets
= true;
1483 case LONGOPT_CAPTURE_COMMENT
:
1486 * Make sure this would fit in a pcapng option.
1488 * XXX - 65535 is the maximum size for an option in pcapng;
1489 * what if another capture file format supports larger
1492 if (strlen(ws_optarg
) > 65535) {
1493 /* It doesn't fit. Tell the user and give up. */
1494 cmdarg_err("Capture comment %u is too large to save in a capture file.",
1495 capture_comments
->len
+ 1);
1496 ret
= WS_EXIT_INVALID_OPTION
;
1500 /* pcapng supports multiple comments, so support them here too.
1502 if (!capture_comments
) {
1503 capture_comments
= g_ptr_array_new_with_free_func(g_free
);
1505 g_ptr_array_add(capture_comments
, g_strdup(ws_optarg
));
1509 case LONGOPT_DISCARD_CAPTURE_COMMENT
:
1511 discard_cap_comments
= true;
1515 case LONGOPT_SET_UNUSED
:
1521 case LONGOPT_DISCARD_PACKET_COMMENTS
:
1523 discard_pkt_comments
= true;
1527 case LONGOPT_EXTRACT_SECRETS
:
1529 do_extract_secrets
= true;
1530 /* XXX - Would it make sense to specify what types of secrets
1531 * to extract (or any)?
1536 case LONGOPT_COMPRESS
:
1538 compression_type
= wtap_name_to_compression_type(ws_optarg
);
1539 if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1540 cmdarg_err("\"%s\" isn't a valid output compression mode",
1542 list_output_compression_types();
1550 uint64_t frame_number
;
1551 int string_start_index
= 0;
1553 if ((sscanf(ws_optarg
, "%" SCNu64
":%n", &frame_number
, &string_start_index
) < 1) || (string_start_index
== 0)) {
1554 cmdarg_err("\"%s\" isn't a valid <frame>:<comment>", ws_optarg
);
1555 ret
= WS_EXIT_INVALID_OPTION
;
1560 * Make sure this would fit in a pcapng option.
1562 * XXX - 65535 is the maximum size for an option in pcapng;
1563 * what if another capture file format supports larger
1566 if (strlen(ws_optarg
+string_start_index
) > 65535) {
1567 /* It doesn't fit. Tell the user and give up. */
1568 cmdarg_err("A comment for frame %" PRIu64
" is too large to save in a capture file.",
1570 ret
= WS_EXIT_INVALID_OPTION
;
1574 /* Lazily create the table */
1575 if (!frames_user_comments
) {
1576 frames_user_comments
= g_tree_new_full(framenum_compare
, NULL
, g_free
, g_free
);
1579 /* Insert this entry (framenum -> comment) */
1580 uint64_t *frame_p
= g_new(uint64_t, 1);
1581 *frame_p
= frame_number
;
1582 g_tree_replace(frames_user_comments
, frame_p
, g_strdup(ws_optarg
+string_start_index
));
1591 check_startstop
= true;
1592 if ((NULL
!= iso8601_to_nstime(&in_time
, ws_optarg
, ISO8601_DATETIME
)) || (NULL
!= unix_epoch_to_nstime(&in_time
, ws_optarg
))) {
1594 nstime_copy(&starttime
, &in_time
);
1595 have_starttime
= true;
1597 nstime_copy(&stoptime
, &in_time
);
1598 have_stoptime
= true;
1603 cmdarg_err("\"%s\" isn't a valid date and time", ws_optarg
);
1604 ret
= WS_EXIT_INVALID_OPTION
;
1610 split_packet_count
= get_nonzero_uint64(ws_optarg
, "packet count");
1615 int choplen
= 0, chopoff
= 0;
1617 switch (sscanf(ws_optarg
, "%d:%d", &chopoff
, &choplen
)) {
1618 case 1: /* only the chop length was specified */
1623 case 2: /* both an offset and chop length was specified */
1627 cmdarg_err("\"%s\" isn't a valid chop length or offset:length", ws_optarg
);
1628 ret
= WS_EXIT_INVALID_OPTION
;
1634 chop
.len_begin
+= choplen
;
1636 chop
.off_begin_pos
+= chopoff
;
1638 chop
.off_begin_neg
+= chopoff
;
1639 } else if (choplen
< 0) {
1640 chop
.len_end
+= choplen
;
1642 chop
.off_end_pos
+= chopoff
;
1644 chop
.off_end_neg
+= chopoff
;
1651 dup_detect_by_time
= false;
1652 dup_window
= DEFAULT_DUP_DEPTH
;
1657 dup_detect_by_time
= false;
1658 dup_window
= get_uint32(ws_optarg
, "duplicate window");
1659 if (dup_window
> MAX_DUP_DEPTH
) {
1660 cmdarg_err("\"%d\" duplicate window value must be between 0 and %d inclusive.",
1661 dup_window
, MAX_DUP_DEPTH
);
1662 ret
= WS_EXIT_INVALID_OPTION
;
1668 err_prob
= g_ascii_strtod(ws_optarg
, &p
);
1669 if (p
== ws_optarg
|| err_prob
< 0.0 || err_prob
> 1.0) {
1670 cmdarg_err("probability \"%s\" must be between 0.0 and 1.0", ws_optarg
);
1671 ret
= WS_EXIT_INVALID_OPTION
;
1677 out_file_type_subtype
= wtap_name_to_file_type_subtype(ws_optarg
);
1678 if (out_file_type_subtype
< 0) {
1679 cmdarg_err("\"%s\" isn't a valid capture file type\n", ws_optarg
);
1680 list_capture_types(stderr
);
1681 ret
= WS_EXIT_INVALID_OPTION
;
1687 show_help_header("Edit and/or translate the format of capture files.");
1688 print_usage(stdout
);
1692 case 'i': /* break capture file based on time interval */
1694 double spb
= get_positive_double(ws_optarg
, "time interval");
1696 cmdarg_err("The specified interval is zero");
1697 ret
= WS_EXIT_INVALID_OPTION
;
1701 double spb_int
, spb_frac
;
1702 spb_frac
= modf(spb
, &spb_int
);
1703 secs_per_block
.secs
= (time_t) spb_int
;
1704 secs_per_block
.nsecs
= (int) (NANOSECS_PER_SEC
* spb_frac
);
1708 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1709 ignored_bytes
= get_uint32(ws_optarg
, "number of bytes to ignore");
1717 change_offset
= get_uint32(ws_optarg
, "change offset");
1722 cmdarg_err("-r was specified twice");
1723 ret
= WS_EXIT_INVALID_OPTION
;
1730 snaplen
= get_nonzero_uint32(ws_optarg
, "snapshot length");
1734 if (!set_strict_time_adj(ws_optarg
)) {
1735 ret
= WS_EXIT_INVALID_OPTION
;
1738 do_strict_time_adjustment
= true;
1742 if (!set_time_adjustment(ws_optarg
)) {
1743 ret
= WS_EXIT_INVALID_OPTION
;
1749 out_frame_type
= wtap_name_to_encap(ws_optarg
);
1750 if (out_frame_type
< 0) {
1751 cmdarg_err("\"%s\" isn't a valid encapsulation type\n", ws_optarg
);
1752 list_encap_types(stderr
);
1753 ret
= WS_EXIT_INVALID_OPTION
;
1760 cmdarg_err("-V was specified twice");
1761 ret
= WS_EXIT_INVALID_OPTION
;
1774 dup_detect_by_time
= true;
1775 dup_window
= MAX_DUP_DEPTH
;
1776 if (!set_rel_time(ws_optarg
)) {
1777 ret
= WS_EXIT_INVALID_OPTION
;
1782 case '?': /* Bad options - print usage */
1786 list_capture_types(stdout
);
1789 list_encap_types(stdout
);
1791 case LONGOPT_COMPRESS
:
1792 list_output_compression_types();
1795 print_usage(stderr
);
1796 ret
= WS_EXIT_INVALID_OPTION
;
1802 } /* processing command-line options */
1805 fprintf(stderr
, "Optind = %i, argc = %i\n", ws_optind
, argc
);
1808 if ((argc
- ws_optind
) < 2) {
1809 print_usage(stderr
);
1810 ret
= WS_EXIT_INVALID_OPTION
;
1814 if (out_file_type_subtype
== WTAP_FILE_TYPE_SUBTYPE_UNKNOWN
) {
1815 /* default to pcapng */
1816 out_file_type_subtype
= wtap_pcapng_file_type_subtype();
1819 if (split_packet_count
!= 0 || !nstime_is_unset(&secs_per_block
)) {
1820 if (!fileset_extract_prefix_suffix(argv
[ws_optind
+1], &fprefix
, &fsuffix
, &compression_type
)) {
1821 ret
= CANT_EXTRACT_PREFIX
;
1824 } else if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1825 /* An explicitly specified compression type overrides filename
1826 * magic. (Should we allow specifying "no" compression with, e.g.
1827 * a ".gz" extension?) */
1828 const char *sfx
= strrchr(argv
[ws_optind
+1], '.');
1830 compression_type
= wtap_extension_to_compression_type(sfx
+ 1);
1834 if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1835 compression_type
= WTAP_UNCOMPRESSED
;
1838 if (!wtap_can_write_compression_type(compression_type
)) {
1839 cmdarg_err("Output files can't be written as %s",
1840 wtap_compression_type_description(compression_type
));
1841 ret
= WS_EXIT_INVALID_OPTION
;
1845 if (compression_type
!= WTAP_UNCOMPRESSED
&& !wtap_dump_can_compress(out_file_type_subtype
)) {
1846 cmdarg_err("The file format %s can't be written to output compressed format",
1847 wtap_file_type_subtype_name(out_file_type_subtype
));
1848 ret
= WS_EXIT_INVALID_OPTION
;
1852 if (err_prob
>= 0.0) {
1854 seed
= (unsigned int) (time(NULL
) + ws_getpid());
1857 fprintf(stderr
, "Using seed %u\n", seed
);
1862 if (have_starttime
&& have_stoptime
&&
1863 nstime_cmp(&starttime
, &stoptime
) > 0) {
1864 cmdarg_err("start time is after the stop time");
1865 ret
= WS_EXIT_INVALID_OPTION
;
1869 if (split_packet_count
!= 0 && !nstime_is_unset(&secs_per_block
)) {
1870 cmdarg_err("can't split on both packet count and time interval");
1871 cmdarg_err_cont("at the same time");
1872 ret
= WS_EXIT_INVALID_OPTION
;
1876 wth
= wtap_open_offline(argv
[ws_optind
], WTAP_TYPE_AUTO
, &read_err
, &read_err_info
, false);
1879 cfile_open_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
1880 ret
= WS_EXIT_INVALID_FILE
;
1885 fprintf(stderr
, "File %s is a %s capture file.\n", argv
[ws_optind
],
1886 wtap_file_type_subtype_description(wtap_file_type_subtype(wth
)));
1889 if (skip_radiotap
) {
1890 if (ignored_bytes
!= 0) {
1891 cmdarg_err("can't skip radiotap headers and %d byte(s)", ignored_bytes
);
1892 cmdarg_err_cont("at the start of packet at the same time");
1893 ret
= WS_EXIT_INVALID_OPTION
;
1897 if (wtap_file_encap(wth
) != WTAP_ENCAP_IEEE_802_11_RADIOTAP
) {
1898 cmdarg_err("can't skip radiotap header because input file has non-radiotap packets");
1899 if (wtap_file_encap(wth
) == WTAP_ENCAP_PER_PACKET
) {
1900 cmdarg_err_cont("expected '%s', not all packets are necessarily that type",
1901 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP
));
1903 cmdarg_err_cont("expected '%s', packets are '%s'",
1904 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP
),
1905 wtap_encap_description(wtap_file_encap(wth
)));
1907 ret
= WS_EXIT_INVALID_OPTION
;
1912 if (do_extract_secrets
) {
1913 if (edit_option_specified
) {
1914 cmdarg_err("can't extract secrets and use other options at the same time");
1915 ret
= WS_EXIT_INVALID_OPTION
;
1918 if (compression_type
!= WTAP_UNCOMPRESSED
) {
1919 cmdarg_err("compression isn't supported for extracting secrets");
1920 ret
= WS_EXIT_INVALID_OPTION
;
1923 ret
= extract_secrets(wth
, argv
[ws_optind
+1], &read_err
, &read_err_info
);
1925 if (read_err
!= 0) {
1926 /* Print a message noting that the read failed somewhere along the
1928 cfile_read_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
1933 wtap_dump_params_init_no_idbs(¶ms
, wth
);
1936 * Discard any secrets we read in while opening the file.
1938 if (discard_all_secrets
) {
1939 wtap_dump_params_discard_decryption_secrets(¶ms
);
1943 * Discard capture file comments.
1945 if (discard_cap_comments
) {
1946 for (unsigned b
= 0; b
< params
.shb_hdrs
->len
; b
++) {
1947 wtap_block_t shb
= g_array_index(params
.shb_hdrs
, wtap_block_t
, b
);
1948 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(shb
, OPT_COMMENT
, 0)) {
1955 * Add new capture file comments.
1957 if (capture_comments
!= NULL
) {
1958 for (unsigned b
= 0; b
< params
.shb_hdrs
->len
; b
++) {
1959 wtap_block_t shb
= g_array_index(params
.shb_hdrs
, wtap_block_t
, b
);
1960 for (unsigned c
= 0; c
< capture_comments
->len
; c
++) {
1961 char *comment
= (char *)g_ptr_array_index(capture_comments
, c
);
1962 wtap_block_add_string_option(shb
, OPT_COMMENT
, comment
, strlen(comment
));
1967 if (dsb_filenames
) {
1968 for (unsigned k
= 0; k
< dsb_filenames
->len
; k
++) {
1969 uint32_t secrets_type_id
= g_array_index(dsb_types
, uint32_t, k
);
1970 const char *secrets_filename
= (const char *)g_ptr_array_index(dsb_filenames
, k
);
1974 wtapng_dsb_mandatory_t
*dsb
;
1977 if (!g_file_get_contents(secrets_filename
, &data
, &data_len
, &err
)) {
1978 cmdarg_err("\"%s\" could not be read: %s", secrets_filename
, err
->message
);
1979 g_clear_error(&err
);
1980 ret
= WS_EXIT_INVALID_OPTION
;
1983 if (data_len
== 0) {
1984 cmdarg_err("\"%s\" is an empty file, ignoring", secrets_filename
);
1988 if (data_len
>= INT_MAX
) {
1989 cmdarg_err("\"%s\" is too large, ignoring", secrets_filename
);
1994 /* Warn for badly formatted files, but proceed anyway. */
1995 validate_secrets_file(secrets_filename
, secrets_type_id
, data
);
1997 block
= wtap_block_create(WTAP_BLOCK_DECRYPTION_SECRETS
);
1998 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(block
);
1999 dsb
->secrets_type
= secrets_type_id
;
2000 dsb
->secrets_len
= (unsigned)data_len
;
2001 dsb
->secrets_data
= data
;
2002 if (params
.dsbs_initial
== NULL
) {
2003 params
.dsbs_initial
= g_array_new(FALSE
, FALSE
, sizeof(wtap_block_t
));
2005 g_array_append_val(params
.dsbs_initial
, block
);
2010 * If an encapsulation type was specified, override the encapsulation
2011 * type of the input file.
2013 if (out_frame_type
!= -2)
2014 params
.encap
= out_frame_type
;
2017 * If a snapshot length was specified, and it's less than the snapshot
2018 * length of the input file, override the snapshot length of the input
2021 if (snaplen
!= 0 && snaplen
< wtap_snapshot_length(wth
))
2022 params
.snaplen
= snaplen
;
2025 * Now process the arguments following the input and output file
2026 * names, if any; they specify packets to include/exclude.
2028 for (i
= ws_optind
+ 2; i
< argc
; i
++)
2029 if (add_selection(argv
[i
], &max_packet_number
) == false)
2032 if (keep_em
&& max_selected
== 0) {
2033 cmdarg_err("must specify packets to keep when using -r");
2034 ret
= WS_EXIT_INVALID_OPTION
;
2039 max_packet_number
= UINT64_MAX
;
2041 if (dup_detect
|| dup_detect_by_time
) {
2042 for (i
= 0; i
< dup_window
; i
++) {
2043 memset(&fd_hash
[i
].digest
, 0, 16);
2045 nstime_set_unset(&fd_hash
[i
].frame_time
);
2049 /* Set up an array of all IDBs seen */
2050 idbs_seen
= g_array_new(FALSE
, FALSE
, sizeof(wtap_block_t
));
2052 /* Read all of the packets in turn */
2053 wtap_rec_init(&read_rec
);
2054 ws_buffer_init(&read_buf
, 1514);
2055 while (wtap_read(wth
, &read_rec
, &read_buf
, &read_err
, &read_err_info
, &data_offset
)) {
2057 * XXX - what about non-packet records in the file after this?
2058 * NRBs, DSBs, and ISBs are now written when wtap_dump_close() calls
2059 * pcapng_dump_finish(), and we handle IDBs below, but what about
2062 if (max_packet_number
<= read_count
)
2069 /* Extra actions for the first packet */
2070 if (read_count
== 1) {
2071 if (split_packet_count
!= 0 || !nstime_is_unset(&secs_per_block
)) {
2072 filename
= fileset_get_filename_by_pattern(block_cnt
++, rec
, fprefix
, fsuffix
);
2074 filename
= g_strdup(argv
[ws_optind
+1]);
2076 ws_assert(filename
);
2078 /* If we don't have an application name add one */
2079 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
) {
2080 wtap_block_add_string_option_format(g_array_index(params
.shb_hdrs
, wtap_block_t
, 0), OPT_SHB_USERAPPL
, "%s", get_appname_and_version());
2083 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
, &write_err
,
2084 &write_err_info
, compression_type
);
2087 cfile_dump_open_failure_message(filename
,
2088 write_err
, write_err_info
,
2089 out_file_type_subtype
);
2090 ret
= WS_EXIT_INVALID_FILE
;
2093 } /* first packet only handling */
2096 * Process whatever IDBs we haven't seen yet.
2098 if (!process_new_idbs(wth
, pdh
, idbs_seen
, &write_err
, &write_err_info
)) {
2099 cfile_write_failure_message(argv
[ws_optind
], filename
,
2100 write_err
, write_err_info
,
2102 out_file_type_subtype
);
2106 * Close the dump file, but don't report an error
2107 * or set the exit code, as we've already reported
2110 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2114 buf
= ws_buffer_start_ptr(&read_buf
);
2117 * Not all packets have time stamps. Only process the time
2118 * stamp if we have one.
2120 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2121 if (!nstime_is_unset(&secs_per_block
)) {
2122 if (nstime_is_unset(&block_next
)) {
2123 block_next
= rec
->ts
;
2124 nstime_add(&block_next
, &secs_per_block
);
2126 while (nstime_cmp(&rec
->ts
, &block_next
) > 0) { /* time for the next file */
2128 /* We presumably want to write the DSBs from files given
2129 * on the command line to every file.
2131 wtap_block_array_ref(params
.dsbs_initial
);
2132 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2133 cfile_close_failure_message(filename
, write_err
,
2139 /* Use the interval start time for the filename. */
2141 temp_rec
.ts
= block_next
;
2142 filename
= fileset_get_filename_by_pattern(block_cnt
++, &temp_rec
, fprefix
, fsuffix
);
2143 ws_assert(filename
);
2144 nstime_add(&block_next
, &secs_per_block
); /* reset for next interval */
2147 fprintf(stderr
, "Continuing writing in file %s\n", filename
);
2149 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
,
2150 &write_err
, &write_err_info
, compression_type
);
2153 cfile_dump_open_failure_message(filename
,
2156 out_file_type_subtype
);
2157 ret
= WS_EXIT_INVALID_FILE
;
2162 } /* time stamp handling */
2164 if (split_packet_count
!= 0) {
2165 /* time for the next file? */
2166 if (written_count
> 0 && (written_count
% split_packet_count
) == 0) {
2168 /* We presumably want to write the DSBs from files given
2169 * on the command line to every file.
2171 wtap_block_array_ref(params
.dsbs_initial
);
2172 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2173 cfile_close_failure_message(filename
, write_err
,
2180 filename
= fileset_get_filename_by_pattern(block_cnt
++, rec
, fprefix
, fsuffix
);
2181 ws_assert(filename
);
2184 fprintf(stderr
, "Continuing writing in file %s\n", filename
);
2186 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
,
2187 &write_err
, &write_err_info
, compression_type
);
2189 cfile_dump_open_failure_message(filename
,
2190 write_err
, write_err_info
,
2191 out_file_type_subtype
);
2192 ret
= WS_EXIT_INVALID_FILE
;
2196 } /* split packet handling */
2198 if (check_startstop
) {
2201 * Is the packet in the selected timeframe?
2202 * If the packet has no time stamp, the answer is "no".
2204 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2205 if (have_starttime
&& have_stoptime
) {
2206 ts_okay
= nstime_cmp(&rec
->ts
, &starttime
) >= 0 &&
2207 nstime_cmp(&rec
->ts
, &stoptime
) < 0;
2208 } else if (have_starttime
) {
2209 ts_okay
= nstime_cmp(&rec
->ts
, &starttime
) >= 0;
2210 } else if (have_stoptime
) {
2211 ts_okay
= nstime_cmp(&rec
->ts
, &stoptime
) < 0;
2216 * No selected timeframe, so all packets are "in the
2217 * selected timeframe".
2222 if (ts_okay
&& ((!selected(count
) && !keep_em
)
2223 || (selected(count
) && keep_em
))) {
2225 if (verbose
&& !dup_detect
&& !dup_detect_by_time
)
2226 fprintf(stderr
, "Packet: %" PRIu64
"\n", count
);
2228 /* We simply write it, perhaps after truncating it; we could
2229 * do other things, like modify it. */
2233 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2234 /* Do we adjust timestamps to ensure strict chronological
2236 if (do_strict_time_adjustment
) {
2237 if (previous_time
.secs
|| previous_time
.nsecs
) {
2238 if (!strict_time_adj
.is_negative
) {
2244 nstime_delta(&delta
, ¤t
, &previous_time
);
2246 if (delta
.secs
< 0 || delta
.nsecs
< 0) {
2248 * A negative delta indicates that the current packet
2249 * has an absolute timestamp less than the previous packet
2250 * that it is being compared to. This is NOT a normal
2251 * situation since trace files usually have packets in
2252 * chronological order (oldest to newest).
2253 * Copy and change rather than modify
2256 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
2258 temp_rec
.ts
.secs
= previous_time
.secs
+ strict_time_adj
.tv
.secs
;
2259 temp_rec
.ts
.nsecs
= previous_time
.nsecs
;
2260 if (temp_rec
.ts
.nsecs
+ strict_time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2263 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
- ONE_BILLION
;
2265 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
;
2271 * A negative strict time adjustment is requested.
2272 * Unconditionally set each timestamp to previous
2273 * packet's timestamp plus delta.
2274 * Copy and change rather than modify returned
2278 temp_rec
.ts
.secs
= previous_time
.secs
+ strict_time_adj
.tv
.secs
;
2279 temp_rec
.ts
.nsecs
= previous_time
.nsecs
;
2280 if (temp_rec
.ts
.nsecs
+ strict_time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2283 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
- ONE_BILLION
;
2285 temp_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
;
2290 previous_time
= rec
->ts
;
2293 if (time_adj
.tv
.secs
!= 0) {
2294 /* Copy and change rather than modify returned rec */
2296 if (time_adj
.is_negative
)
2297 temp_rec
.ts
.secs
-= time_adj
.tv
.secs
;
2299 temp_rec
.ts
.secs
+= time_adj
.tv
.secs
;
2303 if (time_adj
.tv
.nsecs
!= 0) {
2304 /* Copy and change rather than modify returned rec */
2306 if (time_adj
.is_negative
) { /* subtract */
2307 if (temp_rec
.ts
.nsecs
< time_adj
.tv
.nsecs
) { /* borrow */
2309 temp_rec
.ts
.nsecs
+= ONE_BILLION
;
2311 temp_rec
.ts
.nsecs
-= time_adj
.tv
.nsecs
;
2313 if (temp_rec
.ts
.nsecs
+ time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2316 temp_rec
.ts
.nsecs
+= time_adj
.tv
.nsecs
- ONE_BILLION
;
2318 temp_rec
.ts
.nsecs
+= time_adj
.tv
.nsecs
;
2323 } /* time stamp adjustment */
2325 if (rec
->rec_type
== REC_TYPE_PACKET
) {
2327 /* Limit capture length to snaplen */
2328 if (rec
->rec_header
.packet_header
.caplen
> snaplen
) {
2329 /* Copy and change rather than modify returned rec */
2331 temp_rec
.rec_header
.packet_header
.caplen
= snaplen
;
2334 /* If -L, also set reported length to snaplen */
2335 if (adjlen
&& rec
->rec_header
.packet_header
.len
> snaplen
) {
2336 /* Copy and change rather than modify returned rec */
2338 temp_rec
.rec_header
.packet_header
.len
= snaplen
;
2344 * If an encapsulation type was specified, override the
2345 * encapsulation type of the packet.
2346 * Copy and change rather than modify returned rec.
2348 if (out_frame_type
!= -2) {
2350 temp_rec
.rec_header
.packet_header
.pkt_encap
= out_frame_type
;
2356 * Copy and change rather than modify returned rec.
2359 handle_chopping(chop
, &temp_rec
.rec_header
.packet_header
,
2360 &rec
->rec_header
.packet_header
, &buf
,
2364 /* set unused info */
2366 /* set unused bytes to zero so that duplicates check ignores unused bytes */
2367 set_unused_info(&rec
->rec_header
.packet_header
, buf
);
2370 /* remove vlan info */
2372 /* Copy and change rather than modify returned rec */
2374 remove_vlan_info(&rec
->rec_header
.packet_header
, buf
,
2375 &temp_rec
.rec_header
.packet_header
.caplen
);
2379 /* suppress duplicates by packet window */
2381 if (is_duplicate(buf
, rec
->rec_header
.packet_header
.caplen
)) {
2383 fprintf(stderr
, "Skipped: %" PRIu64
", Len: %u, MD5 Hash: ",
2385 rec
->rec_header
.packet_header
.caplen
);
2386 for (i
= 0; i
< 16; i
++)
2387 fprintf(stderr
, "%02x",
2388 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2389 fprintf(stderr
, "\n");
2396 fprintf(stderr
, "Packet: %" 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");
2405 } /* suppression of duplicates */
2407 if (rec
->presence_flags
& WTAP_HAS_TS
) {
2408 /* suppress duplicates by time window */
2409 if (dup_detect_by_time
) {
2412 current
.secs
= rec
->ts
.secs
;
2413 current
.nsecs
= rec
->ts
.nsecs
;
2415 if (is_duplicate_rel_time(buf
,
2416 rec
->rec_header
.packet_header
.caplen
,
2419 fprintf(stderr
, "Skipped: %" PRIu64
", Len: %u, MD5 Hash: ",
2421 rec
->rec_header
.packet_header
.caplen
);
2422 for (i
= 0; i
< 16; i
++)
2423 fprintf(stderr
, "%02x",
2424 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2425 fprintf(stderr
, "\n");
2432 fprintf(stderr
, "Packet: %" 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");
2442 } /* suppress duplicates by time window */
2445 /* Random error mutation */
2446 do_mutation
= false;
2448 if (err_prob
> 0.0) {
2449 switch (rec
->rec_type
) {
2451 case REC_TYPE_PACKET
:
2452 caplen
= rec
->rec_header
.packet_header
.caplen
;
2456 case REC_TYPE_FT_SPECIFIC_EVENT
:
2457 case REC_TYPE_FT_SPECIFIC_REPORT
:
2458 caplen
= rec
->rec_header
.ft_specific_header
.record_len
;
2462 case REC_TYPE_SYSCALL
:
2463 caplen
= rec
->rec_header
.syscall_header
.event_filelen
;
2467 case REC_TYPE_SYSTEMD_JOURNAL_EXPORT
:
2468 caplen
= rec
->rec_header
.systemd_journal_export_header
.record_len
;
2473 if (change_offset
> caplen
) {
2474 fprintf(stderr
, "change offset %u is longer than caplen %u in packet %" PRIu64
"\n",
2475 change_offset
, caplen
, count
);
2476 do_mutation
= false;
2481 int real_data_start
= 0;
2483 /* Protect non-protocol data */
2484 switch (rec
->rec_type
) {
2486 case REC_TYPE_PACKET
:
2488 * XXX - any reason not to fuzz this part?
2490 if (rec
->rec_header
.packet_header
.pkt_encap
== WTAP_ENCAP_CATAPULT_DCT2000
)
2491 real_data_start
= find_dct2000_real_data(buf
);
2495 real_data_start
+= change_offset
;
2497 for (i
= real_data_start
; i
< (int) caplen
; i
++) {
2498 if (rand() <= err_prob
* RAND_MAX
) {
2499 err_type
= rand() / (RAND_MAX
/ ERR_WT_TOTAL
+ 1);
2501 if (err_type
< ERR_WT_BIT
) {
2502 buf
[i
] ^= 1 << (rand() / (RAND_MAX
/ 8 + 1));
2503 err_type
= ERR_WT_TOTAL
;
2505 err_type
-= ERR_WT_BYTE
;
2508 if (err_type
< ERR_WT_BYTE
) {
2509 buf
[i
] = rand() / (RAND_MAX
/ 255 + 1);
2510 err_type
= ERR_WT_TOTAL
;
2512 err_type
-= ERR_WT_BYTE
;
2515 if (err_type
< ERR_WT_ALNUM
) {
2516 buf
[i
] = ALNUM_CHARS
[rand() / (RAND_MAX
/ ALNUM_LEN
+ 1)];
2517 err_type
= ERR_WT_TOTAL
;
2519 err_type
-= ERR_WT_ALNUM
;
2522 if (err_type
< ERR_WT_FMT
) {
2523 if ((unsigned int)i
< caplen
- 2)
2524 (void) g_strlcpy((char*) &buf
[i
], "%s", 2);
2525 err_type
= ERR_WT_TOTAL
;
2527 err_type
-= ERR_WT_FMT
;
2530 if (err_type
< ERR_WT_AA
) {
2531 for (j
= i
; j
< (int) caplen
; j
++)
2537 } /* random error mutation */
2539 /* Discard all packet comments when writing */
2540 if (discard_pkt_comments
) {
2542 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(rec
->block
, OPT_COMMENT
, 0)) {
2543 temp_rec
.block_was_modified
= true;
2549 /* Find a packet comment we may need to write */
2550 if (frames_user_comments
) {
2551 const char *comment
=
2552 (const char*)g_tree_lookup(frames_user_comments
, &read_count
);
2553 if (comment
!= NULL
) {
2554 /* Copy and change rather than modify returned rec */
2557 /* Erase any existing comments before adding the new one */
2558 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(rec
->block
, OPT_COMMENT
, 0)) {
2559 temp_rec
.block_was_modified
= true;
2563 /* The comment is not modified by dumper, cast away. */
2564 wtap_block_add_string_option(rec
->block
, OPT_COMMENT
, (char *)comment
, strlen((char *)comment
));
2565 temp_rec
.block_was_modified
= true;
2568 /* Copy and change rather than modify returned rec */
2570 temp_rec
.block_was_modified
= false;
2575 if (discard_all_secrets
) {
2577 * Discard any secrets we've read since the last packet
2580 wtap_dump_discard_decryption_secrets(pdh
);
2583 /* Attempt to dump out current frame to the output file */
2584 if (!wtap_dump(pdh
, rec
, buf
, &write_err
, &write_err_info
)) {
2585 cfile_write_failure_message(argv
[ws_optind
], filename
,
2586 write_err
, write_err_info
,
2588 out_file_type_subtype
);
2592 * Close the dump file, but don't report an error
2593 * or set the exit code, as we've already reported
2596 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2602 wtap_rec_reset(&read_rec
);
2604 wtap_rec_cleanup(&read_rec
);
2605 ws_buffer_free(&read_buf
);
2608 fprintf(stderr
, "Total selected: %" PRIu64
"\n", written_count
);
2610 if (read_err
!= 0) {
2611 /* Print a message noting that the read failed somewhere along the
2613 cfile_read_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
2617 /* No valid packets found, open the outfile so we can write an
2620 filename
= g_strdup(argv
[ws_optind
+1]);
2622 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
, &write_err
,
2623 &write_err_info
, compression_type
);
2625 cfile_dump_open_failure_message(filename
,
2626 write_err
, write_err_info
,
2627 out_file_type_subtype
);
2628 ret
= WS_EXIT_INVALID_FILE
;
2634 * Process whatever IDBs we haven't seen yet.
2636 if (!process_new_idbs(wth
, pdh
, idbs_seen
, &write_err
, &write_err_info
)) {
2637 cfile_write_failure_message(argv
[ws_optind
], filename
,
2638 write_err
, write_err_info
,
2640 out_file_type_subtype
);
2644 * Close the dump file, but don't report an error
2645 * or set the exit code, as we've already reported
2648 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2652 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2653 cfile_close_failure_message(filename
, write_err
, write_err_info
);
2659 fprintf(stderr
, "%" PRIu64
" packet%s seen, %" PRIu64
" packet%s skipped with duplicate window of %i packets.\n",
2660 count
- 1, plurality(count
- 1, "", "s"), duplicate_count
,
2661 plurality(duplicate_count
, "", "s"), dup_window
);
2662 } else if (dup_detect_by_time
) {
2663 fprintf(stderr
, "%" PRIu64
" packet%s seen, %" PRIu64
" packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2664 count
- 1, plurality(count
- 1, "", "s"), duplicate_count
,
2665 plurality(duplicate_count
, "", "s"),
2666 (long)relative_time_window
.secs
,
2667 (long int)relative_time_window
.nsecs
);
2677 if (frames_user_comments
) {
2678 g_tree_destroy(frames_user_comments
);
2680 if (dsb_filenames
) {
2681 g_array_free(dsb_types
, TRUE
);
2682 g_ptr_array_free(dsb_filenames
, TRUE
);
2684 if (idbs_seen
!= NULL
) {
2685 for (unsigned b
= 0; b
< idbs_seen
->len
; b
++) {
2686 wtap_block_t if_data
= g_array_index(idbs_seen
, wtap_block_t
, b
);
2687 wtap_block_unref(if_data
);
2689 g_array_free(idbs_seen
, TRUE
);
2691 g_free(params
.idb_inf
);
2692 wtap_dump_params_cleanup(¶ms
);
2695 wtap_rec_reset(&read_rec
);
2698 if (capture_comments
!= NULL
) {
2699 g_ptr_array_free(capture_comments
, TRUE
);
2700 capture_comments
= NULL
;
2705 /* Skip meta-information read from file to return offset of real
2708 find_dct2000_real_data(uint8_t *buf
)
2712 for (n
= 0; buf
[n
] != '\0'; n
++); /* Context name */
2714 n
++; /* Context port number */
2715 for (; buf
[n
] != '\0'; n
++); /* Timestamp */
2717 for (; buf
[n
] != '\0'; n
++); /* Protocol name */
2719 for (; buf
[n
] != '\0'; n
++); /* Variant number (as string) */
2721 for (; buf
[n
] != '\0'; n
++); /* Outhdr (as string) */
2723 n
+= 2; /* Direction & encap */
2729 * We support up to 2 chopping regions in a single pass: one specified by the
2730 * positive chop length, and one by the negative chop length.
2733 handle_chopping(chop_t chop
, wtap_packet_header
*out_phdr
,
2734 const wtap_packet_header
*in_phdr
, uint8_t **buf
,
2737 /* If we're not chopping anything from one side, then the offset for that
2738 * side is meaningless. */
2739 if (chop
.len_begin
== 0)
2740 chop
.off_begin_pos
= chop
.off_begin_neg
= 0;
2741 if (chop
.len_end
== 0)
2742 chop
.off_end_pos
= chop
.off_end_neg
= 0;
2744 if (chop
.off_begin_neg
< 0) {
2745 chop
.off_begin_pos
+= in_phdr
->caplen
+ chop
.off_begin_neg
;
2746 chop
.off_begin_neg
= 0;
2748 if (chop
.off_end_pos
> 0) {
2749 chop
.off_end_neg
+= chop
.off_end_pos
- in_phdr
->caplen
;
2750 chop
.off_end_pos
= 0;
2753 /* If we've crossed chopping regions, swap them */
2754 if (chop
.len_begin
&& chop
.len_end
) {
2755 if (chop
.off_begin_pos
> ((int)in_phdr
->caplen
+ chop
.off_end_neg
)) {
2756 int tmp_len
, tmp_off
;
2758 tmp_off
= in_phdr
->caplen
+ chop
.off_end_neg
+ chop
.len_end
;
2759 tmp_len
= -chop
.len_end
;
2761 chop
.off_end_neg
= chop
.len_begin
+ chop
.off_begin_pos
- in_phdr
->caplen
;
2762 chop
.len_end
= -chop
.len_begin
;
2764 chop
.len_begin
= tmp_len
;
2765 chop
.off_begin_pos
= tmp_off
;
2769 /* Make sure we don't chop off more than we have available */
2770 if (in_phdr
->caplen
< (uint32_t)(chop
.off_begin_pos
- chop
.off_end_neg
)) {
2774 if ((uint32_t)(chop
.len_begin
- chop
.len_end
) >
2775 (in_phdr
->caplen
- (uint32_t)(chop
.off_begin_pos
- chop
.off_end_neg
))) {
2776 chop
.len_begin
= in_phdr
->caplen
- (chop
.off_begin_pos
- chop
.off_end_neg
);
2780 /* Handle chopping from the beginning. Note that if a beginning offset
2781 * was specified, we need to keep that piece */
2782 if (chop
.len_begin
> 0) {
2783 *out_phdr
= *in_phdr
;
2785 if (chop
.off_begin_pos
> 0) {
2786 memmove(*buf
+ chop
.off_begin_pos
,
2787 *buf
+ chop
.off_begin_pos
+ chop
.len_begin
,
2788 out_phdr
->caplen
- (chop
.off_begin_pos
+ chop
.len_begin
));
2790 *buf
+= chop
.len_begin
;
2792 out_phdr
->caplen
-= chop
.len_begin
;
2795 if (in_phdr
->len
> (uint32_t)chop
.len_begin
)
2796 out_phdr
->len
-= chop
.len_begin
;
2803 /* Handle chopping from the end. Note that if an ending offset was
2804 * specified, we need to keep that piece */
2805 if (chop
.len_end
< 0) {
2806 *out_phdr
= *in_phdr
;
2808 if (chop
.off_end_neg
< 0) {
2809 memmove(*buf
+ (int)out_phdr
->caplen
+ (chop
.len_end
+ chop
.off_end_neg
),
2810 *buf
+ (int)out_phdr
->caplen
+ chop
.off_end_neg
,
2813 out_phdr
->caplen
+= chop
.len_end
;
2816 if (((signed int) in_phdr
->len
+ chop
.len_end
) > 0)
2817 out_phdr
->len
+= chop
.len_end
;
2821 /*in_phdr = out_phdr;*/
2826 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2831 * indent-tabs-mode: nil
2834 * vi: set shiftwidth=4 tabstop=8 expandtab:
2835 * :indentSize=4:tabSize=8:noTabs=true: