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 unsigned find_dct2000_real_data(const uint8_t *buf
);
178 static void handle_chopping(chop_t chop
, wtap_packet_header
*phdr
,
179 uint8_t **buf
, bool adjlen
);
182 abs_time_to_str_with_sec_resolution(const nstime_t
*abs_time
)
185 char *buf
= (char *)g_malloc(16);
187 tmp
= localtime(&abs_time
->secs
);
190 snprintf(buf
, 16, "%d%02d%02d%02d%02d%02d",
205 fileset_get_filename_by_pattern(unsigned idx
, const nstime_t
*ts
,
206 char *fprefix
, char *fsuffix
)
212 snprintf(filenum
, sizeof(filenum
), "%05u", idx
% RINGBUFFER_MAX_NUM_FILES
);
214 timestr
= abs_time_to_str_with_sec_resolution(ts
);
215 abs_str
= g_strconcat(fprefix
, "_", filenum
, "_", timestr
, fsuffix
, NULL
);
218 abs_str
= g_strconcat(fprefix
, "_", filenum
, fsuffix
, NULL
);
224 fileset_extract_prefix_suffix(const char *fname
, char **fprefix
, char **fsuffix
, wtap_compression_type
*compression_typep
)
226 char *pfx
, *last_pathsep
;
228 wtap_compression_type compression_type
;
230 save_file
= g_strdup(fname
);
231 if (save_file
== NULL
) {
232 fprintf(stderr
, "editcap: Out of memory\n");
236 last_pathsep
= strrchr(save_file
, G_DIR_SEPARATOR
);
237 if (last_pathsep
== NULL
) {
238 last_pathsep
= save_file
;
240 pfx
= strrchr(last_pathsep
, '.');
242 /* The pathname has a "." in it, and it's in the last component
243 * of the pathname (because there is either only one component,
244 * i.e. last_pathsep is null as there are no path separators,
245 * or the "." is after the path separator before the last
248 * Treat it as a separator between the rest of the file name and
249 * the file name suffix, and arrange that the names given to the
250 * ring buffer files have the specified suffix, i.e. put the
251 * changing part of the name *before* the suffix. */
253 compression_type
= wtap_extension_to_compression_type(pfx
+ 1);
254 if (compression_type
!= WTAP_UNKNOWN_COMPRESSION
) {
255 char *pfx2
= strrchr(last_pathsep
, '.');
261 if (compression_typep
&& *compression_typep
== WTAP_UNKNOWN_COMPRESSION
) {
262 *compression_typep
= compression_type
;
264 /* XXX - What if there's an extension matching a compression type
265 * and the passed in compression type is known but something else?
268 *fprefix
= g_strdup(save_file
);
269 pfx
[0] = '.'; /* restore capfile_name */
270 *fsuffix
= g_strdup(pfx
);
272 /* Either there's no "." in the pathname, or it's in a directory
273 * component, so the last component has no suffix. */
274 *fprefix
= g_strdup(save_file
);
281 /* Add a selection item, a simple parser for now */
283 add_selection(char *sel
, uint64_t* max_selection
)
288 if (max_selected
>= MAX_SELECTIONS
) {
289 /* Let the user know we stopped selecting */
290 fprintf(stderr
, "Out of room for packet selections.\n");
295 fprintf(stderr
, "Add_Selected: %s\n", sel
);
297 if ((locn
= strchr(sel
, '-')) == NULL
) { /* No dash, so a single number? */
299 fprintf(stderr
, "Not inclusive ...");
301 selectfrm
[max_selected
].inclusive
= false;
302 selectfrm
[max_selected
].first
= get_uint64(sel
, "packet number");
303 if (selectfrm
[max_selected
].first
> *max_selection
)
304 *max_selection
= selectfrm
[max_selected
].first
;
307 fprintf(stderr
, " %" PRIu64
"\n", selectfrm
[max_selected
].first
);
310 fprintf(stderr
, "Inclusive ...");
312 *locn
= '\0'; /* split the range */
314 selectfrm
[max_selected
].inclusive
= true;
315 selectfrm
[max_selected
].first
= get_uint64(sel
, "beginning of packet range");
316 selectfrm
[max_selected
].second
= get_uint64(next
, "end of packet range");
318 if (selectfrm
[max_selected
].second
== 0)
320 /* Not a valid number, presume all */
321 selectfrm
[max_selected
].second
= *max_selection
= UINT64_MAX
;
323 else if (selectfrm
[max_selected
].second
> *max_selection
)
324 *max_selection
= selectfrm
[max_selected
].second
;
327 fprintf(stderr
, " %" PRIu64
", %" PRIu64
"\n", selectfrm
[max_selected
].first
,
328 selectfrm
[max_selected
].second
);
335 /* Was the packet selected? */
338 selected(uint64_t recno
)
342 for (i
= 0; i
< max_selected
; i
++) {
343 if (selectfrm
[i
].inclusive
) {
344 if (selectfrm
[i
].first
<= recno
&& selectfrm
[i
].second
>= recno
)
347 if (recno
== selectfrm
[i
].first
)
356 set_time_adjustment(char *optarg_str_p
)
365 /* skip leading whitespace */
366 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
369 /* check for a negative adjustment */
370 if (*optarg_str_p
== '-') {
371 time_adj
.is_negative
= 1;
375 /* collect whole number of seconds, if any */
376 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
380 val
= strtol(optarg_str_p
, &frac
, 10);
381 if (frac
== NULL
|| frac
== optarg_str_p
382 || val
== LONG_MIN
|| val
== LONG_MAX
) {
383 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
387 if (val
< 0) { /* implies '--' since we caught '-' above */
388 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
393 time_adj
.tv
.secs
= val
;
395 /* now collect the partial seconds, if any */
396 if (*frac
!= '\0') { /* chars left, so get fractional part */
397 val
= strtol(&(frac
[1]), &end
, 10);
398 /* if more than 9 fractional digits truncate to 9 */
399 if ((end
- &(frac
[1])) > 9) {
400 frac
[10] = 't'; /* 't' for truncate */
401 val
= strtol(&(frac
[1]), &end
, 10);
403 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
404 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
405 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
410 return true; /* no fractional digits */
413 /* adjust fractional portion from fractional to numerator
414 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
415 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
416 while(frac_digits
< 9) { /* this is frac of 10^9 */
421 time_adj
.tv
.nsecs
= (int)val
;
426 set_strict_time_adj(char *optarg_str_p
)
435 /* skip leading whitespace */
436 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
440 * check for a negative adjustment
441 * A negative strict adjustment value is a flag
442 * to adjust all frames by the specified delta time.
444 if (*optarg_str_p
== '-') {
445 strict_time_adj
.is_negative
= 1;
449 /* collect whole number of seconds, if any */
450 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
454 val
= strtol(optarg_str_p
, &frac
, 10);
455 if (frac
== NULL
|| frac
== optarg_str_p
456 || val
== LONG_MIN
|| val
== LONG_MAX
) {
457 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
461 if (val
< 0) { /* implies '--' since we caught '-' above */
462 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
467 strict_time_adj
.tv
.secs
= val
;
469 /* now collect the partial seconds, if any */
470 if (*frac
!= '\0') { /* chars left, so get fractional part */
471 val
= strtol(&(frac
[1]), &end
, 10);
472 /* if more than 9 fractional digits truncate to 9 */
473 if ((end
- &(frac
[1])) > 9) {
474 frac
[10] = 't'; /* 't' for truncate */
475 val
= strtol(&(frac
[1]), &end
, 10);
477 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
478 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
479 fprintf(stderr
, "editcap: \"%s\" isn't a valid time adjustment\n",
484 return true; /* no fractional digits */
487 /* adjust fractional portion from fractional to numerator
488 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
489 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
490 while(frac_digits
< 9) { /* this is frac of 10^9 */
495 strict_time_adj
.tv
.nsecs
= (int)val
;
500 set_rel_time(char *optarg_str_p
)
509 /* skip leading whitespace */
510 while (*optarg_str_p
== ' ' || *optarg_str_p
== '\t')
513 /* ignore negative adjustment */
514 if (*optarg_str_p
== '-')
517 /* collect whole number of seconds, if any */
518 if (*optarg_str_p
== '.') { /* only fractional (i.e., .5 is ok) */
522 val
= strtol(optarg_str_p
, &frac
, 10);
523 if (frac
== NULL
|| frac
== optarg_str_p
524 || val
== LONG_MIN
|| val
== LONG_MAX
) {
525 fprintf(stderr
, "1: editcap: \"%s\" isn't a valid rel time value\n",
529 if (val
< 0) { /* implies '--' since we caught '-' above */
530 fprintf(stderr
, "2: editcap: \"%s\" isn't a valid rel time value\n",
535 relative_time_window
.secs
= val
;
537 /* now collect the partial seconds, if any */
538 if (*frac
!= '\0') { /* chars left, so get fractional part */
539 val
= strtol(&(frac
[1]), &end
, 10);
540 /* if more than 9 fractional digits truncate to 9 */
541 if ((end
- &(frac
[1])) > 9) {
542 frac
[10] = 't'; /* 't' for truncate */
543 val
= strtol(&(frac
[1]), &end
, 10);
545 if (*frac
!= '.' || end
== NULL
|| end
== frac
|| val
< 0
546 || val
>= ONE_BILLION
|| val
== LONG_MIN
|| val
== LONG_MAX
) {
547 fprintf(stderr
, "3: editcap: \"%s\" isn't a valid rel time value\n",
552 return true; /* no fractional digits */
555 /* adjust fractional portion from fractional to numerator
556 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
557 frac_digits
= end
- frac
- 1; /* fractional digit count (remember '.') */
558 while(frac_digits
< 9) { /* this is frac of 10^9 */
563 relative_time_window
.nsecs
= (int)val
;
567 #define SLL_ADDRLEN 8 /* length of address field */
569 uint16_t sll_pkttype
; /* packet type */
570 uint16_t sll_hatype
; /* link-layer address type */
571 uint16_t sll_halen
; /* link-layer address length */
572 uint8_t sll_addr
[SLL_ADDRLEN
]; /* link-layer address */
573 uint16_t sll_protocol
; /* protocol */
577 uint16_t sll2_protocol
; /* protocol */
578 uint16_t sll2_reserved_mbz
; /* reserved - must be zero */
579 uint32_t sll2_if_index
; /* 1-based interface index */
580 uint16_t sll2_hatype
; /* link-layer address type */
581 uint8_t sll2_pkttype
; /* packet type */
582 uint8_t sll2_halen
; /* link-layer address length */
583 uint8_t sll2_addr
[SLL_ADDRLEN
]; /* link-layer address */
588 sll_remove_vlan_info(uint8_t* fd
, uint32_t* len
) {
589 if (pntoh16(fd
+ offsetof(struct sll_header
, sll_protocol
)) == ETHERTYPE_VLAN
) {
591 /* point to start of vlan */
592 fd
= fd
+ offsetof(struct sll_header
, sll_protocol
);
593 /* bytes to read after vlan info */
594 rest_len
= *len
- (offsetof(struct sll_header
, sll_protocol
) + VLAN_SIZE
);
595 /* remove vlan info from packet */
596 memmove(fd
, fd
+ VLAN_SIZE
, rest_len
);
604 sll_set_unused_info(uint8_t* fd
) {
606 ha_len
= pntoh16(fd
+ offsetof(struct sll_header
, sll_halen
));
608 if (ha_len
< SLL_ADDRLEN
) {
610 unused
= SLL_ADDRLEN
- ha_len
;
611 /* point to end of sll_ddr */
612 fd
= fd
+ offsetof(struct sll_header
, sll_addr
) + ha_len
;
613 /* set zeros in the unused data */
614 memset(fd
, 0, unused
);
619 sll2_set_unused_info(uint8_t* fd
) {
621 ha_len
= *(fd
+ offsetof(struct sll2_header
, sll2_halen
));
623 if (ha_len
< SLL_ADDRLEN
) {
625 unused
= SLL_ADDRLEN
- ha_len
;
626 /* point to end of sll2_addr */
627 fd
= fd
+ offsetof(struct sll2_header
, sll2_addr
) + ha_len
;
628 /* set zeros in the unused data */
629 memset(fd
, 0, unused
);
634 remove_vlan_info(wtap_packet_header
*phdr
, uint8_t* fd
) {
635 switch (phdr
->pkt_encap
) {
637 sll_remove_vlan_info(fd
, &phdr
->caplen
);
640 /* no support for current pkt_encap */
646 set_unused_info(const wtap_packet_header
*phdr
, uint8_t* fd
) {
647 switch (phdr
->pkt_encap
) {
649 sll_set_unused_info(fd
);
651 case WTAP_ENCAP_SLL2
:
652 sll2_set_unused_info(fd
);
655 /* no support for current pkt_encap */
661 is_duplicate(uint8_t* fd
, uint32_t len
) {
663 const struct ieee80211_radiotap_header
* tap_header
;
665 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
666 uint32_t offset
= ignored_bytes
;
670 if (len
<= ignored_bytes
) {
674 /* Get the size of radiotap header and use that as offset (-p option) */
675 if (skip_radiotap
== true) {
676 tap_header
= (const struct ieee80211_radiotap_header
*)fd
;
677 offset
= pletoh16(&tap_header
->it_len
);
682 new_fd
= &fd
[offset
];
683 new_len
= len
- (offset
);
686 if (cur_dup_entry
>= dup_window
)
689 /* Calculate our digest */
690 gcry_md_hash_buffer(GCRY_MD_MD5
, fd_hash
[cur_dup_entry
].digest
, new_fd
, new_len
);
692 fd_hash
[cur_dup_entry
].len
= len
;
694 /* Look for duplicates */
695 for (i
= 0; i
< dup_window
; i
++) {
696 if (i
== cur_dup_entry
)
699 if (fd_hash
[i
].len
== fd_hash
[cur_dup_entry
].len
700 && memcmp(fd_hash
[i
].digest
, fd_hash
[cur_dup_entry
].digest
, 16) == 0) {
709 is_duplicate_rel_time(uint8_t* fd
, uint32_t len
, const nstime_t
*current
) {
712 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
713 uint32_t offset
= ignored_bytes
;
717 if (len
<= ignored_bytes
) {
721 new_fd
= &fd
[offset
];
722 new_len
= len
- (offset
);
725 if (cur_dup_entry
>= dup_window
)
728 /* Calculate our digest */
729 gcry_md_hash_buffer(GCRY_MD_MD5
, fd_hash
[cur_dup_entry
].digest
, new_fd
, new_len
);
731 fd_hash
[cur_dup_entry
].len
= len
;
732 fd_hash
[cur_dup_entry
].frame_time
.secs
= current
->secs
;
733 fd_hash
[cur_dup_entry
].frame_time
.nsecs
= current
->nsecs
;
736 * Look for relative time related duplicates.
737 * This is hopefully a reasonably efficient mechanism for
738 * finding duplicates by rel time in the fd_hash[] cache.
739 * We check starting from the most recently added hash
740 * entries and work backwards towards older packets.
741 * This approach allows the dup test to be terminated
742 * when the relative time of a cached entry is found to
743 * be beyond the dup time window.
745 * Of course this assumes that the input trace file is
746 * "well-formed" in the sense that the packet timestamps are
747 * in strict chronologically increasing order (which is NOT
748 * always the case!!).
750 * The fd_hash[] table was deliberately created large (1,000,000).
751 * Looking for time related duplicates in large trace files with
752 * non-fractional dup time window values can potentially take
753 * a long time to complete.
756 for (i
= cur_dup_entry
- 1;; i
--) {
763 if (i
== cur_dup_entry
) {
765 * We've decremented back to where we started.
771 if (nstime_is_unset(&(fd_hash
[i
].frame_time
))) {
773 * We've decremented to an unused fd_hash[] entry.
779 nstime_delta(&delta
, current
, &fd_hash
[i
].frame_time
);
781 if (delta
.secs
< 0 || delta
.nsecs
< 0) {
783 * A negative delta implies that the current packet
784 * has an absolute timestamp less than the cached packet
785 * that it is being compared to. This is NOT a normal
786 * situation since trace files usually have packets in
787 * chronological order (oldest to newest).
789 * There are several possible ways to deal with this:
790 * 1. 'continue' dup checking with the next cached frame.
791 * 2. 'break' from looking for a duplicate of the current frame.
792 * 3. Take the absolute value of the delta and see if that
793 * falls within the specified dup time window.
795 * Currently this code does option 1. But it would pretty
796 * easy to add yet-another-editcap-option to select one of
797 * the other behaviors for dealing with out-of-sequence
803 cmp
= nstime_cmp(&delta
, &relative_time_window
);
807 * The delta time indicates that we are now looking at
808 * cached packets beyond the specified dup time window.
812 } else if (fd_hash
[i
].len
== fd_hash
[cur_dup_entry
].len
813 && memcmp(fd_hash
[i
].digest
, fd_hash
[cur_dup_entry
].digest
, 16) == 0) {
822 mutate_packet_data(wtap_rec
*rec
, uint8_t *buf
, uint32_t change_offset
, uint64_t count
)
825 unsigned real_data_start
= 0;
827 switch (rec
->rec_type
) {
829 case REC_TYPE_PACKET
:
830 caplen
= rec
->rec_header
.packet_header
.caplen
;
833 * Protect some non-protocol data.
834 * XXX - any reason not to fuzz this part?
836 if (rec
->rec_header
.packet_header
.pkt_encap
== WTAP_ENCAP_CATAPULT_DCT2000
)
837 real_data_start
= find_dct2000_real_data(buf
);
840 case REC_TYPE_FT_SPECIFIC_EVENT
:
841 case REC_TYPE_FT_SPECIFIC_REPORT
:
842 caplen
= rec
->rec_header
.ft_specific_header
.record_len
;
845 case REC_TYPE_SYSCALL
:
846 caplen
= rec
->rec_header
.syscall_header
.event_filelen
;
849 case REC_TYPE_SYSTEMD_JOURNAL_EXPORT
:
850 caplen
= rec
->rec_header
.systemd_journal_export_header
.record_len
;
854 /* We don't mutate anything else. */
858 if (change_offset
> caplen
) {
859 fprintf(stderr
, "change offset %u is longer than caplen %u in packet %" PRIu64
"\n",
860 change_offset
, caplen
, count
);
864 real_data_start
+= change_offset
;
866 for (unsigned i
= real_data_start
; i
< caplen
; i
++) {
867 if (rand() <= err_prob
* RAND_MAX
) {
868 int err_type
= rand() / (RAND_MAX
/ ERR_WT_TOTAL
+ 1);
870 if (err_type
< ERR_WT_BIT
) {
871 buf
[i
] ^= 1 << (rand() / (RAND_MAX
/ 8 + 1));
872 err_type
= ERR_WT_TOTAL
;
874 err_type
-= ERR_WT_BYTE
;
877 if (err_type
< ERR_WT_BYTE
) {
878 buf
[i
] = rand() / (RAND_MAX
/ 255 + 1);
879 err_type
= ERR_WT_TOTAL
;
881 err_type
-= ERR_WT_BYTE
;
884 if (err_type
< ERR_WT_ALNUM
) {
885 buf
[i
] = ALNUM_CHARS
[rand() / (RAND_MAX
/ ALNUM_LEN
+ 1)];
886 err_type
= ERR_WT_TOTAL
;
888 err_type
-= ERR_WT_ALNUM
;
891 if (err_type
< ERR_WT_FMT
) {
893 (void) g_strlcpy((char*) &buf
[i
], "%s", 2);
894 err_type
= ERR_WT_TOTAL
;
896 err_type
-= ERR_WT_FMT
;
899 if (err_type
< ERR_WT_AA
) {
900 for (unsigned j
= i
; j
< caplen
; j
++)
909 print_usage(FILE *output
)
911 fprintf(output
, "\n");
912 fprintf(output
, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
913 fprintf(output
, "\n");
914 fprintf(output
, "<infile> and <outfile> must both be present; use '-' for stdin or stdout.\n");
915 fprintf(output
, "A single packet or a range of packets can be selected.\n");
916 fprintf(output
, "\n");
917 fprintf(output
, "Packet selection:\n");
918 fprintf(output
, " -r keep the selected packets; default is to delete them.\n");
919 fprintf(output
, " -A <start time> only read packets whose timestamp is after (or equal\n");
920 fprintf(output
, " to) the given time.\n");
921 fprintf(output
, " -B <stop time> only read packets whose timestamp is before the\n");
922 fprintf(output
, " given time.\n");
923 fprintf(output
, " Time format for -A/-B options is\n");
924 fprintf(output
, " YYYY-MM-DDThh:mm:ss[.nnnnnnnnn][Z|+-hh:mm]\n");
925 fprintf(output
, " Unix epoch timestamps are also supported.\n");
926 fprintf(output
, "\n");
927 fprintf(output
, "Duplicate packet removal:\n");
928 fprintf(output
, " --novlan remove vlan info from packets before checking for duplicates.\n");
929 fprintf(output
, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH
);
930 fprintf(output
, " -D <dup window> remove packet if duplicate; configurable <dup window>.\n");
931 fprintf(output
, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH
);
932 fprintf(output
, " NOTE: A <dup window> of 0 with -V (verbose option) is\n");
933 fprintf(output
, " useful to print MD5 hashes.\n");
934 fprintf(output
, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
935 fprintf(output
, " LESS THAN <dup time window> prior to current packet.\n");
936 fprintf(output
, " A <dup time window> is specified in relative seconds\n");
937 fprintf(output
, " (e.g. 0.000001).\n");
938 fprintf(output
, " NOTE: The use of the 'Duplicate packet removal' options with\n");
939 fprintf(output
, " other editcap options except -V may not always work as expected.\n");
940 fprintf(output
, " Specifically the -r, -t or -S options will very likely NOT have the\n");
941 fprintf(output
, " desired effect if combined with the -d, -D or -w.\n");
942 fprintf(output
, " --skip-radiotap-header skip radiotap header when checking for packet duplicates.\n");
943 fprintf(output
, " Useful when processing packets captured by multiple radios\n");
944 fprintf(output
, " on the same channel in the vicinity of each other.\n");
945 fprintf(output
, " --set-unused set unused byts to zero in sll link addr.\n");
946 fprintf(output
, "\n");
947 fprintf(output
, "Packet manipulation:\n");
948 fprintf(output
, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
949 fprintf(output
, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
950 fprintf(output
, " chop at the packet beginning, negative values at the\n");
951 fprintf(output
, " packet end. If an optional offset precedes the length,\n");
952 fprintf(output
, " then the bytes chopped will be offset from that value.\n");
953 fprintf(output
, " Positive offsets are from the packet beginning,\n");
954 fprintf(output
, " negative offsets are from the packet end. You can use\n");
955 fprintf(output
, " this option more than once, allowing up to 2 chopping\n");
956 fprintf(output
, " regions within a packet provided that at least 1\n");
957 fprintf(output
, " choplen is positive and at least 1 is negative.\n");
958 fprintf(output
, " -L adjust the frame (i.e. reported) length when chopping\n");
959 fprintf(output
, " and/or snapping.\n");
960 fprintf(output
, " -t <time adjustment> adjust the timestamp of each packet.\n");
961 fprintf(output
, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
962 fprintf(output
, " -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
963 fprintf(output
, " strict chronological increasing order. The <strict\n");
964 fprintf(output
, " adjustment> is specified in relative seconds with\n");
965 fprintf(output
, " values of 0 or 0.000001 being the most reasonable.\n");
966 fprintf(output
, " A negative adjustment value will modify timestamps so\n");
967 fprintf(output
, " that each packet's delta time is the absolute value\n");
968 fprintf(output
, " of the adjustment specified. A value of -0 will set\n");
969 fprintf(output
, " all packets to the timestamp of the first packet.\n");
970 fprintf(output
, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
971 fprintf(output
, " a particular packet byte will be randomly changed.\n");
972 fprintf(output
, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
973 fprintf(output
, " beginning of the packet. This allows one to preserve some\n");
974 fprintf(output
, " bytes, in order to have some headers untouched.\n");
975 fprintf(output
, " --seed <seed> When used in conjunction with -E, set the seed to use for\n");
976 fprintf(output
, " the pseudo-random number generator. This allows one to\n");
977 fprintf(output
, " repeat a particular sequence of errors.\n");
978 fprintf(output
, " -I <bytes to ignore> ignore the specified number of bytes at the beginning\n");
979 fprintf(output
, " of the frame during MD5 hash calculation, unless the\n");
980 fprintf(output
, " frame is too short, then the full frame is used.\n");
981 fprintf(output
, " Useful to remove duplicated packets taken on\n");
982 fprintf(output
, " several routers (different mac addresses for\n");
983 fprintf(output
, " example).\n");
984 fprintf(output
, " e.g. -I 26 in case of Ether/IP will ignore\n");
985 fprintf(output
, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
986 fprintf(output
, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
987 fprintf(output
, "\n");
988 fprintf(output
, "Output File(s):\n");
989 fprintf(output
, " if the output file(s) have the .gz extension, then\n");
990 fprintf(output
, " gzip compression will be used\n");
991 fprintf(output
, " -c <packets per file> split the packet output to different files based on\n");
992 fprintf(output
, " uniform packet counts with a maximum of\n");
993 fprintf(output
, " <packets per file> each.\n");
994 fprintf(output
, " -i <seconds per file> split the packet output to different files based on\n");
995 fprintf(output
, " uniform time intervals with a maximum of\n");
996 fprintf(output
, " <seconds per file> each.\n");
997 fprintf(output
, " -F <capture type> set the output file type; default is pcapng.\n");
998 fprintf(output
, " An empty \"-F\" option will list the file types.\n");
999 fprintf(output
, " -T <encap type> set the output file encapsulation type; default is the\n");
1000 fprintf(output
, " same as the input file. An empty \"-T\" option will\n");
1001 fprintf(output
, " list the encapsulation types.\n");
1002 fprintf(output
, " --inject-secrets <type>,<file> Insert decryption secrets from <file>. List\n");
1003 fprintf(output
, " supported secret types with \"--inject-secrets help\".\n");
1004 fprintf(output
, " --extract-secrets Extract decryption secrets into the output file instead.\n");
1005 fprintf(output
, " Incompatible with other options besides -V.\n");
1006 fprintf(output
, " --discard-all-secrets Discard all decryption secrets from the input file\n");
1007 fprintf(output
, " when writing the output file. Does not discard\n");
1008 fprintf(output
, " secrets added by \"--inject-secrets\" in the same\n");
1009 fprintf(output
, " command line.\n");
1010 fprintf(output
, " --capture-comment <comment>\n");
1011 fprintf(output
, " Add a capture file comment, if supported.\n");
1012 fprintf(output
, " --discard-capture-comment\n");
1013 fprintf(output
, " Discard capture file comments from the input file\n");
1014 fprintf(output
, " when writing the output file. Does not discard\n");
1015 fprintf(output
, " comments added by \"--capture-comment\" in the same\n");
1016 fprintf(output
, " command line.\n");
1017 fprintf(output
, " --discard-packet-comments\n");
1018 fprintf(output
, " Discard all packet comments from the input file\n");
1019 fprintf(output
, " when writing the output file. Does not discard\n");
1020 fprintf(output
, " comments added by \"-a\" in the same command line.\n");
1021 fprintf(output
, " --compress <type> Compress the output file using the type compression format.\n");
1022 fprintf(output
, "\n");
1023 fprintf(output
, "Miscellaneous:\n");
1024 fprintf(output
, " -h, --help display this help and exit.\n");
1025 fprintf(output
, " -V verbose output.\n");
1026 fprintf(output
, " If -V is used with any of the 'Duplicate Packet\n");
1027 fprintf(output
, " Removal' options (-d, -D or -w) then Packet lengths\n");
1028 fprintf(output
, " and MD5 hashes are printed to standard-error.\n");
1029 fprintf(output
, " -v, --version print version information and exit.\n");
1032 struct string_elem
{
1033 const char *sstr
; /* The short string */
1034 const char *lstr
; /* The long string */
1038 string_nat_compare(const void *a
, const void *b
)
1040 return ws_ascii_strnatcmp(((const struct string_elem
*)a
)->sstr
,
1041 ((const struct string_elem
*)b
)->sstr
);
1045 string_elem_print(void *data
, void *stream_ptr
)
1047 fprintf((FILE *) stream_ptr
, " %s - %s\n",
1048 ((struct string_elem
*)data
)->sstr
,
1049 ((struct string_elem
*)data
)->lstr
);
1053 list_capture_types(FILE *stream
) {
1054 GArray
*writable_type_subtypes
;
1056 fprintf(stream
, "editcap: The available capture file types for the \"-F\" flag are:\n");
1057 writable_type_subtypes
= wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME
);
1058 for (unsigned i
= 0; i
< writable_type_subtypes
->len
; i
++) {
1059 int ft
= g_array_index(writable_type_subtypes
, int, i
);
1060 fprintf(stream
, " %s - %s\n", wtap_file_type_subtype_name(ft
),
1061 wtap_file_type_subtype_description(ft
));
1063 g_array_free(writable_type_subtypes
, TRUE
);
1067 list_encap_types(FILE *stream
) {
1069 struct string_elem
*encaps
;
1070 GSList
*list
= NULL
;
1072 encaps
= g_new(struct string_elem
, WTAP_NUM_ENCAP_TYPES
);
1073 fprintf(stream
, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
1074 for (i
= 0; i
< WTAP_NUM_ENCAP_TYPES
; i
++) {
1075 encaps
[i
].sstr
= wtap_encap_name(i
);
1076 if (encaps
[i
].sstr
!= NULL
) {
1077 encaps
[i
].lstr
= wtap_encap_description(i
);
1078 list
= g_slist_insert_sorted(list
, &encaps
[i
], string_nat_compare
);
1081 g_slist_foreach(list
, string_elem_print
, stream
);
1087 list_output_compression_types(void) {
1088 GSList
*output_compression_types
;
1090 fprintf(stderr
, "editcap: The available output compress type(s) for the \"--compress\" flag are:\n");
1091 output_compression_types
= wtap_get_all_output_compression_type_names_list();
1092 for (GSList
*compression_type
= output_compression_types
;
1093 compression_type
!= NULL
;
1094 compression_type
= g_slist_next(compression_type
)) {
1095 fprintf(stderr
, " %s\n", (const char *)compression_type
->data
);
1098 g_slist_free(output_compression_types
);
1102 list_secrets_types(FILE *stream
)
1104 for (unsigned i
= 0; i
< G_N_ELEMENTS(secrets_types
); i
++) {
1105 fprintf(stream
, " %s\n", secrets_types
[i
].str
);
1110 lookup_secrets_type(const char *type
)
1112 for (unsigned i
= 0; i
< G_N_ELEMENTS(secrets_types
); i
++) {
1113 if (!strcmp(secrets_types
[i
].str
, type
)) {
1114 return secrets_types
[i
].id
;
1121 validate_secrets_file(const char *filename
, uint32_t secrets_type
, const char *data
)
1123 if (secrets_type
== SECRETS_TYPE_TLS
) {
1125 * A key log file is unlikely going to look like either:
1126 * - a PEM-encoded private key file.
1127 * - a BER-encoded PKCS #12 file ("PFX file"). (Look for a Constructed
1128 * SEQUENCE tag, e.g. bytes 0x30 which happens to be ASCII '0'.)
1130 if (g_str_has_prefix(data
, "-----BEGIN ") || data
[0] == 0x30) {
1132 "editcap: Warning: \"%s\" is not a key log file, but an unsupported private key file. Decryption will not work.\n",
1139 framenum_compare(const void *a
, const void *b
, void *user_data _U_
)
1141 uint64_t *frame_a
= (uint64_t*)a
;
1142 uint64_t *frame_b
= (uint64_t*)b
;
1143 if (*frame_a
< *frame_b
)
1146 if (*frame_a
> *frame_b
)
1152 static wtap_dumper
*
1153 editcap_dump_open(const char *filename
, const wtap_dump_params
*params
,
1154 GArray
*idbs_seen
, int *err
, char **err_info
,
1155 wtap_compression_type compression_type
)
1159 if (strcmp(filename
, "-") == 0) {
1160 /* Write to the standard output. */
1161 pdh
= wtap_dump_open_stdout(out_file_type_subtype
, compression_type
,
1162 params
, err
, err_info
);
1164 pdh
= wtap_dump_open(filename
, out_file_type_subtype
, compression_type
,
1165 params
, err
, err_info
);
1171 * If the output file supports identifying the interfaces on which
1172 * packets arrive, add all the IDBs we've seen so far.
1174 * That mean that the abstract interface provided by libwiretap
1175 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1177 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh
),
1178 WTAP_BLOCK_IF_ID_AND_INFO
) != BLOCK_NOT_SUPPORTED
) {
1179 for (unsigned i
= 0; i
< idbs_seen
->len
; i
++) {
1180 wtap_block_t if_data
= g_array_index(idbs_seen
, wtap_block_t
, i
);
1181 wtap_block_t if_data_copy
;
1184 * Make a copy of this IDB, so that we can change the
1185 * encapsulation type without trashing the original.
1187 if_data_copy
= wtap_block_make_copy(if_data
);
1190 * If an encapsulation type was specified, override the
1191 * encapsulation type of the interface.
1193 if (out_frame_type
!= -2) {
1194 wtapng_if_descr_mandatory_t
*if_mand
;
1196 if_mand
= (wtapng_if_descr_mandatory_t
*)wtap_block_get_mandatory_data(if_data_copy
);
1197 if_mand
->wtap_encap
= out_frame_type
;
1201 * Add this possibly-modified IDB to the file to which
1202 * we're currently writing.
1204 if (!wtap_dump_add_idb(pdh
, if_data_copy
, err
, err_info
)) {
1206 char *close_err_info
;
1208 wtap_dump_close(pdh
, NULL
, &close_err
, &close_err_info
);
1209 g_free(close_err_info
);
1210 wtap_block_unref(if_data_copy
);
1215 * Release the copy - wtap_dump_add_idb() makes its own copy.
1217 wtap_block_unref(if_data_copy
);
1225 process_new_idbs(wtap
*wth
, wtap_dumper
*pdh
, GArray
*idbs_seen
,
1226 int *err
, char **err_info
)
1228 wtap_block_t if_data
;
1230 while ((if_data
= wtap_get_next_interface_description(wth
)) != NULL
) {
1232 * Only add interface blocks if the output file supports (meaning
1235 * That mean that the abstract interface provided by libwiretap
1236 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1238 if (pdh
!= NULL
&& wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh
),
1239 WTAP_BLOCK_IF_ID_AND_INFO
) != BLOCK_NOT_SUPPORTED
) {
1240 wtap_block_t if_data_copy
;
1243 * Make a copy of this IDB, so that we can change the
1244 * encapsulation type without trashing the original.
1246 if_data_copy
= wtap_block_make_copy(if_data
);
1249 * If an encapsulation type was specified, override the
1250 * encapsulation type of the interface.
1252 if (out_frame_type
!= -2) {
1253 wtapng_if_descr_mandatory_t
*if_mand
;
1255 if_mand
= (wtapng_if_descr_mandatory_t
*)wtap_block_get_mandatory_data(if_data_copy
);
1256 if_mand
->wtap_encap
= out_frame_type
;
1260 * Add this possibly-modified IDB to the file to which
1261 * we're currently writing.
1263 if (!wtap_dump_add_idb(pdh
, if_data_copy
, err
, err_info
))
1267 * Release the copy - wtap_dump_add_idb() makes its own copy.
1269 wtap_block_unref(if_data_copy
);
1272 * Also add an unmodified copy to the set of IDBs we've seen,
1273 * in case we start writing to another file (which would be
1274 * of the same type as the current file, and thus will also
1275 * require interface IDs).
1277 if_data_copy
= wtap_block_make_copy(if_data
);
1278 g_array_append_val(idbs_seen
, if_data_copy
);
1285 extract_secrets(wtap
*wth
, char* filename
, int *err
, char **err_info
)
1289 char *fprefix
= NULL
;
1290 char *fsuffix
= NULL
;
1292 /* Read all of the packets in turn */
1293 wtap_rec_init(&read_rec
, 1514);
1294 while (wtap_read(wth
, &read_rec
, err
, err_info
, &offset
)) {
1295 /* Do we want to respect the max packet number on the command line?
1296 * Probably more confusing than it's worth, because a user might
1297 * not know if a DSB is at the end of the file.
1299 wtap_rec_reset(&read_rec
);
1301 wtap_rec_cleanup(&read_rec
);
1303 wtapng_dsb_mandatory_t
*dsb
;
1304 if (strcmp(filename
, "-") == 0) {
1305 /* Sure. Why not. */
1306 for (unsigned dsb_num
= 0; dsb_num
< wtap_file_get_num_dsbs(wth
); ++dsb_num
) {
1307 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, dsb_num
));
1309 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to standard out.\n",
1310 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
);
1312 if (fwrite(dsb
->secrets_data
, 1, dsb
->secrets_len
, stdout
) != dsb
->secrets_len
) {
1316 } else if (wtap_file_get_num_dsbs(wth
) == 1) {
1317 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, 0));
1319 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1320 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
,
1323 if (!write_file_binary_mode(filename
, dsb
->secrets_data
, dsb
->secrets_len
)) {
1327 /* We have more than one DSB, so write multiple files. While for some
1328 * types, we could combine the information from different DSBs togther
1329 * (and most of those are text-based, so we'd want to write in text
1330 * mode so that the line endings are uniform (which makes testing
1331 * harder), we don't know that for every type.
1333 if (!fileset_extract_prefix_suffix(filename
, &fprefix
, &fsuffix
, NULL
)) {
1334 return CANT_EXTRACT_PREFIX
;
1336 char *extract_filename
;
1337 for (unsigned dsb_num
= 0; dsb_num
< wtap_file_get_num_dsbs(wth
); ++dsb_num
) {
1338 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth
, dsb_num
));
1339 extract_filename
= fileset_get_filename_by_pattern(dsb_num
, NULL
, fprefix
, fsuffix
);
1341 fprintf(stderr
, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1342 secrets_type_description(dsb
->secrets_type
), dsb
->secrets_type
,
1345 if (!write_file_binary_mode(extract_filename
, dsb
->secrets_data
, dsb
->secrets_len
)) {
1346 /* write_file_binary_mode already reports failures */
1347 g_free(extract_filename
);
1353 g_free(extract_filename
);
1358 return EXIT_SUCCESS
;
1362 main(int argc
, char *argv
[])
1364 char *configuration_init_error
;
1366 int i
, read_err
, write_err
;
1367 char *read_err_info
, *write_err_info
;
1370 #define LONGOPT_NO_VLAN LONGOPT_BASE_APPLICATION+1
1371 #define LONGOPT_SKIP_RADIOTAP_HEADER LONGOPT_BASE_APPLICATION+2
1372 #define LONGOPT_SEED LONGOPT_BASE_APPLICATION+3
1373 #define LONGOPT_INJECT_SECRETS LONGOPT_BASE_APPLICATION+4
1374 #define LONGOPT_DISCARD_ALL_SECRETS LONGOPT_BASE_APPLICATION+5
1375 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
1376 #define LONGOPT_DISCARD_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+7
1377 #define LONGOPT_SET_UNUSED LONGOPT_BASE_APPLICATION+8
1378 #define LONGOPT_DISCARD_PACKET_COMMENTS LONGOPT_BASE_APPLICATION+9
1379 #define LONGOPT_EXTRACT_SECRETS LONGOPT_BASE_APPLICATION+10
1380 #define LONGOPT_COMPRESS LONGOPT_BASE_APPLICATION+11
1382 static const struct ws_option long_options
[] = {
1383 {"novlan", ws_no_argument
, NULL
, LONGOPT_NO_VLAN
},
1384 {"skip-radiotap-header", ws_no_argument
, NULL
, LONGOPT_SKIP_RADIOTAP_HEADER
},
1385 {"seed", ws_required_argument
, NULL
, LONGOPT_SEED
},
1386 {"inject-secrets", ws_required_argument
, NULL
, LONGOPT_INJECT_SECRETS
},
1387 {"discard-all-secrets", ws_no_argument
, NULL
, LONGOPT_DISCARD_ALL_SECRETS
},
1388 {"help", ws_no_argument
, NULL
, 'h'},
1389 {"version", ws_no_argument
, NULL
, 'v'},
1390 {"capture-comment", ws_required_argument
, NULL
, LONGOPT_CAPTURE_COMMENT
},
1391 {"discard-capture-comment", ws_no_argument
, NULL
, LONGOPT_DISCARD_CAPTURE_COMMENT
},
1392 {"set-unused", ws_no_argument
, NULL
, LONGOPT_SET_UNUSED
},
1393 {"discard-packet-comments", ws_no_argument
, NULL
, LONGOPT_DISCARD_PACKET_COMMENTS
},
1394 {"extract-secrets", ws_no_argument
, NULL
, LONGOPT_EXTRACT_SECRETS
},
1395 {"compress", ws_required_argument
, NULL
, LONGOPT_COMPRESS
},
1400 uint32_t snaplen
= 0; /* No limit */
1401 chop_t chop
= {0, 0, 0, 0, 0, 0}; /* No chop */
1402 bool adjlen
= false;
1403 wtap_dumper
*pdh
= NULL
;
1404 GArray
*idbs_seen
= NULL
;
1406 uint64_t duplicate_count
= 0;
1407 int64_t data_offset
;
1409 uint64_t read_count
= 0;
1410 uint64_t split_packet_count
= 0;
1411 uint64_t written_count
= 0;
1412 char *filename
= NULL
;
1414 nstime_t secs_per_block
= NSTIME_INIT_UNSET
;
1416 nstime_t block_next
= NSTIME_INIT_UNSET
;
1417 char *fprefix
= NULL
;
1418 char *fsuffix
= NULL
;
1419 uint32_t change_offset
= 0;
1420 uint64_t max_packet_number
= 0;
1421 GArray
*dsb_types
= NULL
;
1422 GPtrArray
*dsb_filenames
= NULL
;
1424 wtap_dump_params params
= WTAP_DUMP_PARAMS_INIT
;
1425 char *shb_user_appl
;
1426 int ret
= EXIT_SUCCESS
;
1427 bool valid_seed
= false;
1428 unsigned int seed
= 0;
1429 bool edit_option_specified
= false;
1430 wtap_compression_type compression_type
= WTAP_UNKNOWN_COMPRESSION
;
1432 /* Set the program name. */
1433 g_set_prgname("editcap");
1435 cmdarg_err_init(stderr_cmdarg_err
, stderr_cmdarg_err_cont
);
1436 memset(&read_rec
, 0, sizeof read_rec
);
1438 /* Initialize log handler early so we can have proper logging during startup. */
1439 ws_log_init(vcmdarg_err
);
1441 /* Early logging command-line initialization. */
1442 ws_log_parse_args(&argc
, argv
, vcmdarg_err
, WS_EXIT_INVALID_OPTION
);
1444 ws_noisy("Finished log init and parsing command line log arguments");
1447 create_app_running_mutex();
1451 * Get credential information for later use.
1453 init_process_policies();
1456 * Attempt to get the pathname of the directory containing the
1459 configuration_init_error
= configuration_init(argv
[0]);
1460 if (configuration_init_error
!= NULL
) {
1461 cmdarg_err("Can't get pathname of directory containing the editcap program: %s.",
1462 configuration_init_error
);
1463 g_free(configuration_init_error
);
1466 /* Initialize the version information. */
1467 ws_init_version_info("Editcap", NULL
, NULL
);
1469 init_report_failure_message("editcap");
1473 /* Process the options */
1474 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) {
1475 if (opt
!= LONGOPT_EXTRACT_SECRETS
&& opt
!= 'V') {
1476 edit_option_specified
= true;
1479 case LONGOPT_NO_VLAN
:
1485 case LONGOPT_SKIP_RADIOTAP_HEADER
:
1487 skip_radiotap
= true;
1493 if (sscanf(ws_optarg
, "%u", &seed
) != 1) {
1494 cmdarg_err("\"%s\" isn't a valid seed", ws_optarg
);
1495 ret
= WS_EXIT_INVALID_OPTION
;
1502 case LONGOPT_INJECT_SECRETS
:
1504 uint32_t secrets_type_id
= 0;
1505 const char *secrets_filename
= NULL
;
1506 if (strcmp("help", ws_optarg
) == 0) {
1507 list_secrets_types(stdout
);
1510 char **splitted
= g_strsplit(ws_optarg
, ",", 2);
1511 if (splitted
[0] && splitted
[0][0] != '\0') {
1512 secrets_type_id
= lookup_secrets_type(splitted
[0]);
1513 if (secrets_type_id
== 0) {
1514 cmdarg_err("\"%s\" isn't a valid secrets type", splitted
[0]);
1515 g_strfreev(splitted
);
1516 ret
= WS_EXIT_INVALID_OPTION
;
1519 secrets_filename
= splitted
[1];
1521 cmdarg_err("no secrets type was specified for --inject-secrets");
1522 g_strfreev(splitted
);
1523 ret
= WS_EXIT_INVALID_OPTION
;
1526 if (!dsb_filenames
) {
1527 dsb_types
= g_array_new(FALSE
, FALSE
, sizeof(uint32_t));
1528 dsb_filenames
= g_ptr_array_new_with_free_func(g_free
);
1530 g_array_append_val(dsb_types
, secrets_type_id
);
1531 g_ptr_array_add(dsb_filenames
, g_strdup(secrets_filename
));
1532 g_strfreev(splitted
);
1536 case LONGOPT_DISCARD_ALL_SECRETS
:
1538 discard_all_secrets
= true;
1542 case LONGOPT_CAPTURE_COMMENT
:
1545 * Make sure this would fit in a pcapng option.
1547 * XXX - 65535 is the maximum size for an option in pcapng;
1548 * what if another capture file format supports larger
1551 if (strlen(ws_optarg
) > 65535) {
1552 /* It doesn't fit. Tell the user and give up. */
1553 cmdarg_err("Capture comment %u is too large to save in a capture file.",
1554 capture_comments
->len
+ 1);
1555 ret
= WS_EXIT_INVALID_OPTION
;
1559 /* pcapng supports multiple comments, so support them here too.
1561 if (!capture_comments
) {
1562 capture_comments
= g_ptr_array_new_with_free_func(g_free
);
1564 g_ptr_array_add(capture_comments
, g_strdup(ws_optarg
));
1568 case LONGOPT_DISCARD_CAPTURE_COMMENT
:
1570 discard_cap_comments
= true;
1574 case LONGOPT_SET_UNUSED
:
1580 case LONGOPT_DISCARD_PACKET_COMMENTS
:
1582 discard_pkt_comments
= true;
1586 case LONGOPT_EXTRACT_SECRETS
:
1588 do_extract_secrets
= true;
1589 /* XXX - Would it make sense to specify what types of secrets
1590 * to extract (or any)?
1595 case LONGOPT_COMPRESS
:
1597 compression_type
= wtap_name_to_compression_type(ws_optarg
);
1598 if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1599 cmdarg_err("\"%s\" isn't a valid output compression mode",
1601 list_output_compression_types();
1609 uint64_t frame_number
;
1610 int string_start_index
= 0;
1612 if ((sscanf(ws_optarg
, "%" SCNu64
":%n", &frame_number
, &string_start_index
) < 1) || (string_start_index
== 0)) {
1613 cmdarg_err("\"%s\" isn't a valid <frame>:<comment>", ws_optarg
);
1614 ret
= WS_EXIT_INVALID_OPTION
;
1619 * Make sure this would fit in a pcapng option.
1621 * XXX - 65535 is the maximum size for an option in pcapng;
1622 * what if another capture file format supports larger
1625 if (strlen(ws_optarg
+string_start_index
) > 65535) {
1626 /* It doesn't fit. Tell the user and give up. */
1627 cmdarg_err("A comment for frame %" PRIu64
" is too large to save in a capture file.",
1629 ret
= WS_EXIT_INVALID_OPTION
;
1633 /* Lazily create the table */
1634 if (!frames_user_comments
) {
1635 frames_user_comments
= g_tree_new_full(framenum_compare
, NULL
, g_free
, g_free
);
1638 /* Insert this entry (framenum -> comment) */
1639 uint64_t *frame_p
= g_new(uint64_t, 1);
1640 *frame_p
= frame_number
;
1641 g_tree_replace(frames_user_comments
, frame_p
, g_strdup(ws_optarg
+string_start_index
));
1650 check_startstop
= true;
1651 if ((NULL
!= iso8601_to_nstime(&in_time
, ws_optarg
, ISO8601_DATETIME
)) || (NULL
!= unix_epoch_to_nstime(&in_time
, ws_optarg
))) {
1653 nstime_copy(&starttime
, &in_time
);
1654 have_starttime
= true;
1656 nstime_copy(&stoptime
, &in_time
);
1657 have_stoptime
= true;
1662 cmdarg_err("\"%s\" isn't a valid date and time", ws_optarg
);
1663 ret
= WS_EXIT_INVALID_OPTION
;
1669 split_packet_count
= get_nonzero_uint64(ws_optarg
, "packet count");
1674 int choplen
= 0, chopoff
= 0;
1676 switch (sscanf(ws_optarg
, "%d:%d", &chopoff
, &choplen
)) {
1677 case 1: /* only the chop length was specified */
1682 case 2: /* both an offset and chop length was specified */
1686 cmdarg_err("\"%s\" isn't a valid chop length or offset:length", ws_optarg
);
1687 ret
= WS_EXIT_INVALID_OPTION
;
1693 chop
.len_begin
+= choplen
;
1695 chop
.off_begin_pos
+= chopoff
;
1697 chop
.off_begin_neg
+= chopoff
;
1698 } else if (choplen
< 0) {
1699 chop
.len_end
+= choplen
;
1701 chop
.off_end_pos
+= chopoff
;
1703 chop
.off_end_neg
+= chopoff
;
1710 dup_detect_by_time
= false;
1711 dup_window
= DEFAULT_DUP_DEPTH
;
1716 dup_detect_by_time
= false;
1717 dup_window
= get_uint32(ws_optarg
, "duplicate window");
1718 if (dup_window
> MAX_DUP_DEPTH
) {
1719 cmdarg_err("\"%d\" duplicate window value must be between 0 and %d inclusive.",
1720 dup_window
, MAX_DUP_DEPTH
);
1721 ret
= WS_EXIT_INVALID_OPTION
;
1727 err_prob
= g_ascii_strtod(ws_optarg
, &p
);
1728 if (p
== ws_optarg
|| err_prob
< 0.0 || err_prob
> 1.0) {
1729 cmdarg_err("probability \"%s\" must be between 0.0 and 1.0", ws_optarg
);
1730 ret
= WS_EXIT_INVALID_OPTION
;
1736 out_file_type_subtype
= wtap_name_to_file_type_subtype(ws_optarg
);
1737 if (out_file_type_subtype
< 0) {
1738 cmdarg_err("\"%s\" isn't a valid capture file type\n", ws_optarg
);
1739 list_capture_types(stderr
);
1740 ret
= WS_EXIT_INVALID_OPTION
;
1746 show_help_header("Edit and/or translate the format of capture files.");
1747 print_usage(stdout
);
1751 case 'i': /* break capture file based on time interval */
1753 double spb
= get_positive_double(ws_optarg
, "time interval");
1755 cmdarg_err("The specified interval is zero");
1756 ret
= WS_EXIT_INVALID_OPTION
;
1760 double spb_int
, spb_frac
;
1761 spb_frac
= modf(spb
, &spb_int
);
1762 secs_per_block
.secs
= (time_t) spb_int
;
1763 secs_per_block
.nsecs
= (int) (NANOSECS_PER_SEC
* spb_frac
);
1767 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1768 ignored_bytes
= get_uint32(ws_optarg
, "number of bytes to ignore");
1776 change_offset
= get_uint32(ws_optarg
, "change offset");
1781 cmdarg_err("-r was specified twice");
1782 ret
= WS_EXIT_INVALID_OPTION
;
1789 snaplen
= get_nonzero_uint32(ws_optarg
, "snapshot length");
1793 if (!set_strict_time_adj(ws_optarg
)) {
1794 ret
= WS_EXIT_INVALID_OPTION
;
1797 do_strict_time_adjustment
= true;
1801 if (!set_time_adjustment(ws_optarg
)) {
1802 ret
= WS_EXIT_INVALID_OPTION
;
1808 out_frame_type
= wtap_name_to_encap(ws_optarg
);
1809 if (out_frame_type
< 0) {
1810 cmdarg_err("\"%s\" isn't a valid encapsulation type\n", ws_optarg
);
1811 list_encap_types(stderr
);
1812 ret
= WS_EXIT_INVALID_OPTION
;
1819 cmdarg_err("-V was specified twice");
1820 ret
= WS_EXIT_INVALID_OPTION
;
1833 dup_detect_by_time
= true;
1834 dup_window
= MAX_DUP_DEPTH
;
1835 if (!set_rel_time(ws_optarg
)) {
1836 ret
= WS_EXIT_INVALID_OPTION
;
1841 case '?': /* Bad options - print usage */
1845 list_capture_types(stdout
);
1848 list_encap_types(stdout
);
1850 case LONGOPT_COMPRESS
:
1851 list_output_compression_types();
1854 print_usage(stderr
);
1855 ret
= WS_EXIT_INVALID_OPTION
;
1861 } /* processing command-line options */
1864 fprintf(stderr
, "Optind = %i, argc = %i\n", ws_optind
, argc
);
1867 if ((argc
- ws_optind
) < 2) {
1868 print_usage(stderr
);
1869 ret
= WS_EXIT_INVALID_OPTION
;
1873 if (out_file_type_subtype
== WTAP_FILE_TYPE_SUBTYPE_UNKNOWN
) {
1874 /* default to pcapng */
1875 out_file_type_subtype
= wtap_pcapng_file_type_subtype();
1878 if (split_packet_count
!= 0 || !nstime_is_unset(&secs_per_block
)) {
1879 if (!fileset_extract_prefix_suffix(argv
[ws_optind
+1], &fprefix
, &fsuffix
, &compression_type
)) {
1880 ret
= CANT_EXTRACT_PREFIX
;
1883 } else if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1884 /* An explicitly specified compression type overrides filename
1885 * magic. (Should we allow specifying "no" compression with, e.g.
1886 * a ".gz" extension?) */
1887 const char *sfx
= strrchr(argv
[ws_optind
+1], '.');
1889 compression_type
= wtap_extension_to_compression_type(sfx
+ 1);
1893 if (compression_type
== WTAP_UNKNOWN_COMPRESSION
) {
1894 compression_type
= WTAP_UNCOMPRESSED
;
1897 if (!wtap_can_write_compression_type(compression_type
)) {
1898 cmdarg_err("Output files can't be written as %s",
1899 wtap_compression_type_description(compression_type
));
1900 ret
= WS_EXIT_INVALID_OPTION
;
1904 if (compression_type
!= WTAP_UNCOMPRESSED
&& !wtap_dump_can_compress(out_file_type_subtype
)) {
1905 cmdarg_err("The file format %s can't be written to output compressed format",
1906 wtap_file_type_subtype_name(out_file_type_subtype
));
1907 ret
= WS_EXIT_INVALID_OPTION
;
1911 if (err_prob
>= 0.0) {
1913 seed
= (unsigned int) (time(NULL
) + ws_getpid());
1916 fprintf(stderr
, "Using seed %u\n", seed
);
1921 if (have_starttime
&& have_stoptime
&&
1922 nstime_cmp(&starttime
, &stoptime
) > 0) {
1923 cmdarg_err("start time is after the stop time");
1924 ret
= WS_EXIT_INVALID_OPTION
;
1928 if (split_packet_count
!= 0 && !nstime_is_unset(&secs_per_block
)) {
1929 cmdarg_err("can't split on both packet count and time interval");
1930 cmdarg_err_cont("at the same time");
1931 ret
= WS_EXIT_INVALID_OPTION
;
1935 wth
= wtap_open_offline(argv
[ws_optind
], WTAP_TYPE_AUTO
, &read_err
, &read_err_info
, false);
1938 cfile_open_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
1939 ret
= WS_EXIT_INVALID_FILE
;
1944 fprintf(stderr
, "File %s is a %s capture file.\n", argv
[ws_optind
],
1945 wtap_file_type_subtype_description(wtap_file_type_subtype(wth
)));
1948 if (skip_radiotap
) {
1949 if (ignored_bytes
!= 0) {
1950 cmdarg_err("can't skip radiotap headers and %d byte(s)", ignored_bytes
);
1951 cmdarg_err_cont("at the start of packet at the same time");
1952 ret
= WS_EXIT_INVALID_OPTION
;
1956 if (wtap_file_encap(wth
) != WTAP_ENCAP_IEEE_802_11_RADIOTAP
) {
1957 cmdarg_err("can't skip radiotap header because input file has non-radiotap packets");
1958 if (wtap_file_encap(wth
) == WTAP_ENCAP_PER_PACKET
) {
1959 cmdarg_err_cont("expected '%s', not all packets are necessarily that type",
1960 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP
));
1962 cmdarg_err_cont("expected '%s', packets are '%s'",
1963 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP
),
1964 wtap_encap_description(wtap_file_encap(wth
)));
1966 ret
= WS_EXIT_INVALID_OPTION
;
1971 if (do_extract_secrets
) {
1972 if (edit_option_specified
) {
1973 cmdarg_err("can't extract secrets and use other options at the same time");
1974 ret
= WS_EXIT_INVALID_OPTION
;
1977 if (compression_type
!= WTAP_UNCOMPRESSED
) {
1978 cmdarg_err("compression isn't supported for extracting secrets");
1979 ret
= WS_EXIT_INVALID_OPTION
;
1982 ret
= extract_secrets(wth
, argv
[ws_optind
+1], &read_err
, &read_err_info
);
1984 if (read_err
!= 0) {
1985 /* Print a message noting that the read failed somewhere along the
1987 cfile_read_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
1992 wtap_dump_params_init_no_idbs(¶ms
, wth
);
1995 * Discard any secrets we read in while opening the file.
1997 if (discard_all_secrets
) {
1998 wtap_dump_params_discard_decryption_secrets(¶ms
);
2002 * Discard capture file comments.
2004 if (discard_cap_comments
) {
2005 for (unsigned b
= 0; b
< params
.shb_hdrs
->len
; b
++) {
2006 wtap_block_t shb
= g_array_index(params
.shb_hdrs
, wtap_block_t
, b
);
2007 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(shb
, OPT_COMMENT
, 0)) {
2014 * Add new capture file comments.
2016 if (capture_comments
!= NULL
) {
2017 for (unsigned b
= 0; b
< params
.shb_hdrs
->len
; b
++) {
2018 wtap_block_t shb
= g_array_index(params
.shb_hdrs
, wtap_block_t
, b
);
2019 for (unsigned c
= 0; c
< capture_comments
->len
; c
++) {
2020 char *comment
= (char *)g_ptr_array_index(capture_comments
, c
);
2021 wtap_block_add_string_option(shb
, OPT_COMMENT
, comment
, strlen(comment
));
2026 if (dsb_filenames
) {
2027 for (unsigned k
= 0; k
< dsb_filenames
->len
; k
++) {
2028 uint32_t secrets_type_id
= g_array_index(dsb_types
, uint32_t, k
);
2029 const char *secrets_filename
= (const char *)g_ptr_array_index(dsb_filenames
, k
);
2033 wtapng_dsb_mandatory_t
*dsb
;
2036 if (!g_file_get_contents(secrets_filename
, &data
, &data_len
, &err
)) {
2037 cmdarg_err("\"%s\" could not be read: %s", secrets_filename
, err
->message
);
2038 g_clear_error(&err
);
2039 ret
= WS_EXIT_INVALID_OPTION
;
2042 if (data_len
== 0) {
2043 cmdarg_err("\"%s\" is an empty file, ignoring", secrets_filename
);
2047 if (data_len
>= INT_MAX
) {
2048 cmdarg_err("\"%s\" is too large, ignoring", secrets_filename
);
2053 /* Warn for badly formatted files, but proceed anyway. */
2054 validate_secrets_file(secrets_filename
, secrets_type_id
, data
);
2056 block
= wtap_block_create(WTAP_BLOCK_DECRYPTION_SECRETS
);
2057 dsb
= (wtapng_dsb_mandatory_t
*)wtap_block_get_mandatory_data(block
);
2058 dsb
->secrets_type
= secrets_type_id
;
2059 dsb
->secrets_len
= (unsigned)data_len
;
2060 dsb
->secrets_data
= data
;
2061 if (params
.dsbs_initial
== NULL
) {
2062 params
.dsbs_initial
= g_array_new(FALSE
, FALSE
, sizeof(wtap_block_t
));
2064 g_array_append_val(params
.dsbs_initial
, block
);
2069 * If an encapsulation type was specified, override the encapsulation
2070 * type of the input file.
2072 if (out_frame_type
!= -2)
2073 params
.encap
= out_frame_type
;
2076 * If a snapshot length was specified, and it's less than the snapshot
2077 * length of the input file, override the snapshot length of the input
2080 if (snaplen
!= 0 && snaplen
< wtap_snapshot_length(wth
))
2081 params
.snaplen
= snaplen
;
2084 * Now process the arguments following the input and output file
2085 * names, if any; they specify packets to include/exclude.
2087 for (i
= ws_optind
+ 2; i
< argc
; i
++)
2088 if (add_selection(argv
[i
], &max_packet_number
) == false)
2091 if (keep_em
&& max_selected
== 0) {
2092 cmdarg_err("must specify packets to keep when using -r");
2093 ret
= WS_EXIT_INVALID_OPTION
;
2098 max_packet_number
= UINT64_MAX
;
2100 if (dup_detect
|| dup_detect_by_time
) {
2101 for (i
= 0; i
< dup_window
; i
++) {
2102 memset(&fd_hash
[i
].digest
, 0, 16);
2104 nstime_set_unset(&fd_hash
[i
].frame_time
);
2108 /* Set up an array of all IDBs seen */
2109 idbs_seen
= g_array_new(FALSE
, FALSE
, sizeof(wtap_block_t
));
2111 /* Read all of the packets in turn */
2112 wtap_rec_init(&read_rec
, 1514);
2113 while (wtap_read(wth
, &read_rec
, &read_err
, &read_err_info
, &data_offset
)) {
2115 * XXX - what about non-packet records in the file after this?
2116 * NRBs, DSBs, and ISBs are now written when wtap_dump_close() calls
2117 * pcapng_dump_finish(), and we handle IDBs below, but what about
2120 if (max_packet_number
<= read_count
)
2125 /* Extra actions for the first packet */
2126 if (read_count
== 1) {
2127 if (split_packet_count
!= 0 || !nstime_is_unset(&secs_per_block
)) {
2128 filename
= fileset_get_filename_by_pattern(block_cnt
++,
2129 (read_rec
.presence_flags
& WTAP_HAS_TS
) ? &read_rec
.ts
: NULL
,
2132 filename
= g_strdup(argv
[ws_optind
+1]);
2134 ws_assert(filename
);
2136 /* If we don't have an application name add one */
2137 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
) {
2138 wtap_block_add_string_option_format(g_array_index(params
.shb_hdrs
, wtap_block_t
, 0), OPT_SHB_USERAPPL
, "%s", get_appname_and_version());
2141 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
, &write_err
,
2142 &write_err_info
, compression_type
);
2145 cfile_dump_open_failure_message(filename
,
2146 write_err
, write_err_info
,
2147 out_file_type_subtype
);
2148 ret
= WS_EXIT_INVALID_FILE
;
2151 } /* first packet only handling */
2154 * Process whatever IDBs we haven't seen yet.
2156 if (!process_new_idbs(wth
, pdh
, idbs_seen
, &write_err
, &write_err_info
)) {
2157 cfile_write_failure_message(argv
[ws_optind
], filename
,
2158 write_err
, write_err_info
,
2160 out_file_type_subtype
);
2164 * Close the dump file, but don't report an error
2165 * or set the exit code, as we've already reported
2168 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2172 buf
= ws_buffer_start_ptr(&read_rec
.data
);
2175 * Not all packets have time stamps. Only process the time
2176 * stamp if we have one.
2178 if (read_rec
.presence_flags
& WTAP_HAS_TS
) {
2179 if (!nstime_is_unset(&secs_per_block
)) {
2180 if (nstime_is_unset(&block_next
)) {
2181 block_next
= read_rec
.ts
;
2182 nstime_add(&block_next
, &secs_per_block
);
2184 while (nstime_cmp(&read_rec
.ts
, &block_next
) > 0) { /* time for the next file */
2186 /* We presumably want to write the DSBs from files given
2187 * on the command line to every file.
2189 wtap_block_array_ref(params
.dsbs_initial
);
2190 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2191 cfile_close_failure_message(filename
, write_err
,
2197 /* Use the interval start time for the filename. */
2198 filename
= fileset_get_filename_by_pattern(block_cnt
++, &block_next
, fprefix
, fsuffix
);
2199 ws_assert(filename
);
2200 nstime_add(&block_next
, &secs_per_block
); /* reset for next interval */
2203 fprintf(stderr
, "Continuing writing in file %s\n", filename
);
2205 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
,
2206 &write_err
, &write_err_info
, compression_type
);
2209 cfile_dump_open_failure_message(filename
,
2212 out_file_type_subtype
);
2213 ret
= WS_EXIT_INVALID_FILE
;
2218 } /* time stamp handling */
2220 if (split_packet_count
!= 0) {
2221 /* time for the next file? */
2222 if (written_count
> 0 && (written_count
% split_packet_count
) == 0) {
2224 /* We presumably want to write the DSBs from files given
2225 * on the command line to every file.
2227 wtap_block_array_ref(params
.dsbs_initial
);
2228 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2229 cfile_close_failure_message(filename
, write_err
,
2236 filename
= fileset_get_filename_by_pattern(block_cnt
++,
2237 (read_rec
.presence_flags
& WTAP_HAS_TS
) ? &read_rec
.ts
: NULL
,
2239 ws_assert(filename
);
2242 fprintf(stderr
, "Continuing writing in file %s\n", filename
);
2244 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
,
2245 &write_err
, &write_err_info
, compression_type
);
2247 cfile_dump_open_failure_message(filename
,
2248 write_err
, write_err_info
,
2249 out_file_type_subtype
);
2250 ret
= WS_EXIT_INVALID_FILE
;
2254 } /* split packet handling */
2256 if (check_startstop
) {
2259 * Is the packet in the selected timeframe?
2260 * If the packet has no time stamp, the answer is "no".
2262 if (read_rec
.presence_flags
& WTAP_HAS_TS
) {
2263 if (have_starttime
&& have_stoptime
) {
2264 ts_okay
= nstime_cmp(&read_rec
.ts
, &starttime
) >= 0 &&
2265 nstime_cmp(&read_rec
.ts
, &stoptime
) < 0;
2266 } else if (have_starttime
) {
2267 ts_okay
= nstime_cmp(&read_rec
.ts
, &starttime
) >= 0;
2268 } else if (have_stoptime
) {
2269 ts_okay
= nstime_cmp(&read_rec
.ts
, &stoptime
) < 0;
2274 * No selected timeframe, so all packets are "in the
2275 * selected timeframe".
2280 if (ts_okay
&& ((!selected(count
) && !keep_em
)
2281 || (selected(count
) && keep_em
))) {
2282 /* Write the record, possibly after modifying it. */
2284 if (verbose
&& !dup_detect
&& !dup_detect_by_time
)
2285 fprintf(stderr
, "Packet: %" PRIu64
"\n", count
);
2287 if (read_rec
.presence_flags
& WTAP_HAS_TS
) {
2288 /* Do we adjust timestamps to ensure strict chronological
2290 if (do_strict_time_adjustment
) {
2291 if (previous_time
.secs
|| previous_time
.nsecs
) {
2292 if (!strict_time_adj
.is_negative
) {
2296 current
= read_rec
.ts
;
2298 nstime_delta(&delta
, ¤t
, &previous_time
);
2300 if (delta
.secs
< 0 || delta
.nsecs
< 0) {
2302 * A negative delta indicates that the current packet
2303 * has an absolute timestamp less than the previous packet
2304 * that it is being compared to. This is NOT a normal
2305 * situation since trace files usually have packets in
2306 * chronological order (oldest to newest).
2308 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
2309 read_rec
.ts
.secs
= previous_time
.secs
+ strict_time_adj
.tv
.secs
;
2310 read_rec
.ts
.nsecs
= previous_time
.nsecs
;
2311 if (read_rec
.ts
.nsecs
+ strict_time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2314 read_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
- ONE_BILLION
;
2316 read_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
;
2321 * A negative strict time adjustment is requested.
2322 * Unconditionally set each timestamp to previous
2323 * packet's timestamp plus delta.
2325 read_rec
.ts
.secs
= previous_time
.secs
+ strict_time_adj
.tv
.secs
;
2326 read_rec
.ts
.nsecs
= previous_time
.nsecs
;
2327 if (read_rec
.ts
.nsecs
+ strict_time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2330 read_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
- ONE_BILLION
;
2332 read_rec
.ts
.nsecs
+= strict_time_adj
.tv
.nsecs
;
2336 previous_time
= read_rec
.ts
;
2339 if (time_adj
.tv
.secs
!= 0) {
2340 if (time_adj
.is_negative
)
2341 read_rec
.ts
.secs
-= time_adj
.tv
.secs
;
2343 read_rec
.ts
.secs
+= time_adj
.tv
.secs
;
2346 if (time_adj
.tv
.nsecs
!= 0) {
2347 if (time_adj
.is_negative
) { /* subtract */
2348 if (read_rec
.ts
.nsecs
< time_adj
.tv
.nsecs
) { /* borrow */
2350 read_rec
.ts
.nsecs
+= ONE_BILLION
;
2352 read_rec
.ts
.nsecs
-= time_adj
.tv
.nsecs
;
2354 if (read_rec
.ts
.nsecs
+ time_adj
.tv
.nsecs
>= ONE_BILLION
) {
2357 read_rec
.ts
.nsecs
+= time_adj
.tv
.nsecs
- ONE_BILLION
;
2359 read_rec
.ts
.nsecs
+= time_adj
.tv
.nsecs
;
2363 } /* time stamp adjustment */
2365 if (read_rec
.rec_type
== REC_TYPE_PACKET
) {
2367 /* Limit capture length to snaplen */
2368 if (read_rec
.rec_header
.packet_header
.caplen
> snaplen
) {
2369 read_rec
.rec_header
.packet_header
.caplen
= snaplen
;
2371 /* If -L, also set reported length to snaplen */
2372 if (adjlen
&& read_rec
.rec_header
.packet_header
.len
> snaplen
) {
2373 read_rec
.rec_header
.packet_header
.len
= snaplen
;
2378 * If an encapsulation type was specified, override the
2379 * encapsulation type of the packet.
2381 if (out_frame_type
!= -2) {
2382 read_rec
.rec_header
.packet_header
.pkt_encap
= out_frame_type
;
2388 handle_chopping(chop
, &read_rec
.rec_header
.packet_header
,
2391 /* set unused info */
2393 /* set unused bytes to zero so that duplicates check ignores unused bytes */
2394 set_unused_info(&read_rec
.rec_header
.packet_header
, buf
);
2397 /* remove vlan info */
2399 remove_vlan_info(&read_rec
.rec_header
.packet_header
, buf
);
2402 /* suppress duplicates by packet window */
2404 if (is_duplicate(buf
, read_rec
.rec_header
.packet_header
.caplen
)) {
2406 fprintf(stderr
, "Skipped: %" PRIu64
", Len: %u, MD5 Hash: ",
2408 read_rec
.rec_header
.packet_header
.caplen
);
2409 for (i
= 0; i
< 16; i
++)
2410 fprintf(stderr
, "%02x",
2411 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2412 fprintf(stderr
, "\n");
2419 fprintf(stderr
, "Packet: %" PRIu64
", Len: %u, MD5 Hash: ",
2421 read_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");
2428 } /* suppression of duplicates */
2430 if (read_rec
.presence_flags
& WTAP_HAS_TS
) {
2431 /* suppress duplicates by time window */
2432 if (dup_detect_by_time
) {
2435 current
.secs
= read_rec
.ts
.secs
;
2436 current
.nsecs
= read_rec
.ts
.nsecs
;
2438 if (is_duplicate_rel_time(buf
,
2439 read_rec
.rec_header
.packet_header
.caplen
,
2442 fprintf(stderr
, "Skipped: %" PRIu64
", Len: %u, MD5 Hash: ",
2444 read_rec
.rec_header
.packet_header
.caplen
);
2445 for (i
= 0; i
< 16; i
++)
2446 fprintf(stderr
, "%02x",
2447 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2448 fprintf(stderr
, "\n");
2455 fprintf(stderr
, "Packet: %" PRIu64
", Len: %u, MD5 Hash: ",
2457 read_rec
.rec_header
.packet_header
.caplen
);
2458 for (i
= 0; i
< 16; i
++)
2459 fprintf(stderr
, "%02x",
2460 (unsigned char)fd_hash
[cur_dup_entry
].digest
[i
]);
2461 fprintf(stderr
, "\n");
2465 } /* suppress duplicates by time window */
2468 /* Random error mutation */
2469 if (err_prob
> 0.0) {
2470 mutate_packet_data(&read_rec
, buf
, change_offset
, count
);
2471 } /* random error mutation */
2473 /* Discard all packet comments when writing */
2474 if (discard_pkt_comments
) {
2475 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(read_rec
.block
, OPT_COMMENT
, 0)) {
2476 read_rec
.block_was_modified
= true;
2480 /* Find a packet comment we may need to write */
2481 if (frames_user_comments
) {
2482 const char *comment
=
2483 (const char*)g_tree_lookup(frames_user_comments
, &read_count
);
2484 if (comment
!= NULL
) {
2485 /* Erase any existing comments before adding the new one */
2486 while (WTAP_OPTTYPE_SUCCESS
== wtap_block_remove_nth_option_instance(read_rec
.block
, OPT_COMMENT
, 0)) {
2487 read_rec
.block_was_modified
= true;
2490 /* The comment is not modified by dumper, cast away. */
2491 wtap_block_add_string_option(read_rec
.block
, OPT_COMMENT
, (char *)comment
, strlen((char *)comment
));
2492 read_rec
.block_was_modified
= true;
2494 read_rec
.block_was_modified
= false;
2498 if (discard_all_secrets
) {
2500 * Discard any secrets we've read since the last packet
2503 wtap_dump_discard_decryption_secrets(pdh
);
2506 /* Attempt to dump out current frame to the output file */
2507 if (!wtap_dump(pdh
, &read_rec
, buf
, &write_err
, &write_err_info
)) {
2508 cfile_write_failure_message(argv
[ws_optind
], filename
,
2509 write_err
, write_err_info
,
2511 out_file_type_subtype
);
2515 * Close the dump file, but don't report an error
2516 * or set the exit code, as we've already reported
2519 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2525 wtap_rec_reset(&read_rec
);
2527 wtap_rec_cleanup(&read_rec
);
2530 fprintf(stderr
, "Total selected: %" PRIu64
"\n", written_count
);
2532 if (read_err
!= 0) {
2533 /* Print a message noting that the read failed somewhere along the
2535 cfile_read_failure_message(argv
[ws_optind
], read_err
, read_err_info
);
2539 /* No valid packets found, open the outfile so we can write an
2542 filename
= g_strdup(argv
[ws_optind
+1]);
2544 pdh
= editcap_dump_open(filename
, ¶ms
, idbs_seen
, &write_err
,
2545 &write_err_info
, compression_type
);
2547 cfile_dump_open_failure_message(filename
,
2548 write_err
, write_err_info
,
2549 out_file_type_subtype
);
2550 ret
= WS_EXIT_INVALID_FILE
;
2556 * Process whatever IDBs we haven't seen yet.
2558 if (!process_new_idbs(wth
, pdh
, idbs_seen
, &write_err
, &write_err_info
)) {
2559 cfile_write_failure_message(argv
[ws_optind
], filename
,
2560 write_err
, write_err_info
,
2562 out_file_type_subtype
);
2566 * Close the dump file, but don't report an error
2567 * or set the exit code, as we've already reported
2570 wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
);
2574 if (!wtap_dump_close(pdh
, NULL
, &write_err
, &write_err_info
)) {
2575 cfile_close_failure_message(filename
, write_err
, write_err_info
);
2581 fprintf(stderr
, "%" PRIu64
" packet%s seen, %" PRIu64
" packet%s skipped with duplicate window of %i packets.\n",
2582 count
- 1, plurality(count
- 1, "", "s"), duplicate_count
,
2583 plurality(duplicate_count
, "", "s"), dup_window
);
2584 } else if (dup_detect_by_time
) {
2585 fprintf(stderr
, "%" PRIu64
" packet%s seen, %" PRIu64
" packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2586 count
- 1, plurality(count
- 1, "", "s"), duplicate_count
,
2587 plurality(duplicate_count
, "", "s"),
2588 (long)relative_time_window
.secs
,
2589 (long int)relative_time_window
.nsecs
);
2599 if (frames_user_comments
) {
2600 g_tree_destroy(frames_user_comments
);
2602 if (dsb_filenames
) {
2603 g_array_free(dsb_types
, TRUE
);
2604 g_ptr_array_free(dsb_filenames
, TRUE
);
2606 if (idbs_seen
!= NULL
) {
2607 for (unsigned b
= 0; b
< idbs_seen
->len
; b
++) {
2608 wtap_block_t if_data
= g_array_index(idbs_seen
, wtap_block_t
, b
);
2609 wtap_block_unref(if_data
);
2611 g_array_free(idbs_seen
, TRUE
);
2613 g_free(params
.idb_inf
);
2614 wtap_dump_params_cleanup(¶ms
);
2617 wtap_rec_reset(&read_rec
);
2620 if (capture_comments
!= NULL
) {
2621 g_ptr_array_free(capture_comments
, TRUE
);
2622 capture_comments
= NULL
;
2627 /* Skip meta-information read from file to return offset of real
2630 find_dct2000_real_data(const uint8_t *buf
)
2634 for (n
= 0; buf
[n
] != '\0'; n
++); /* Context name */
2636 n
++; /* Context port number */
2637 for (; buf
[n
] != '\0'; n
++); /* Timestamp */
2639 for (; buf
[n
] != '\0'; n
++); /* Protocol name */
2641 for (; buf
[n
] != '\0'; n
++); /* Variant number (as string) */
2643 for (; buf
[n
] != '\0'; n
++); /* Outhdr (as string) */
2645 n
+= 2; /* Direction & encap */
2651 * We support up to 2 chopping regions in a single pass: one specified by the
2652 * positive chop length, and one by the negative chop length.
2655 handle_chopping(chop_t chop
, wtap_packet_header
*phdr
, uint8_t **buf
,
2658 /* If we're not chopping anything from one side, then the offset for that
2659 * side is meaningless. */
2660 if (chop
.len_begin
== 0)
2661 chop
.off_begin_pos
= chop
.off_begin_neg
= 0;
2662 if (chop
.len_end
== 0)
2663 chop
.off_end_pos
= chop
.off_end_neg
= 0;
2665 if (chop
.off_begin_neg
< 0) {
2666 chop
.off_begin_pos
+= phdr
->caplen
+ chop
.off_begin_neg
;
2667 chop
.off_begin_neg
= 0;
2669 if (chop
.off_end_pos
> 0) {
2670 chop
.off_end_neg
+= chop
.off_end_pos
- phdr
->caplen
;
2671 chop
.off_end_pos
= 0;
2674 /* If we've crossed chopping regions, swap them */
2675 if (chop
.len_begin
&& chop
.len_end
) {
2676 if (chop
.off_begin_pos
> ((int)phdr
->caplen
+ chop
.off_end_neg
)) {
2677 int tmp_len
, tmp_off
;
2679 tmp_off
= phdr
->caplen
+ chop
.off_end_neg
+ chop
.len_end
;
2680 tmp_len
= -chop
.len_end
;
2682 chop
.off_end_neg
= chop
.len_begin
+ chop
.off_begin_pos
- phdr
->caplen
;
2683 chop
.len_end
= -chop
.len_begin
;
2685 chop
.len_begin
= tmp_len
;
2686 chop
.off_begin_pos
= tmp_off
;
2690 /* Make sure we don't chop off more than we have available */
2691 if (phdr
->caplen
< (uint32_t)(chop
.off_begin_pos
- chop
.off_end_neg
)) {
2695 if ((uint32_t)(chop
.len_begin
- chop
.len_end
) >
2696 (phdr
->caplen
- (uint32_t)(chop
.off_begin_pos
- chop
.off_end_neg
))) {
2697 chop
.len_begin
= phdr
->caplen
- (chop
.off_begin_pos
- chop
.off_end_neg
);
2701 /* Handle chopping from the beginning. Note that if a beginning offset
2702 * was specified, we need to keep that piece */
2703 if (chop
.len_begin
> 0) {
2704 if (chop
.off_begin_pos
> 0) {
2705 memmove(*buf
+ chop
.off_begin_pos
,
2706 *buf
+ chop
.off_begin_pos
+ chop
.len_begin
,
2707 phdr
->caplen
- (chop
.off_begin_pos
+ chop
.len_begin
));
2709 *buf
+= chop
.len_begin
;
2711 phdr
->caplen
-= chop
.len_begin
;
2714 if (phdr
->len
> (uint32_t)chop
.len_begin
)
2715 phdr
->len
-= chop
.len_begin
;
2721 /* Handle chopping from the end. Note that if an ending offset was
2722 * specified, we need to keep that piece */
2723 if (chop
.len_end
< 0) {
2724 if (chop
.off_end_neg
< 0) {
2725 memmove(*buf
+ (int)phdr
->caplen
+ (chop
.len_end
+ chop
.off_end_neg
),
2726 *buf
+ (int)phdr
->caplen
+ chop
.off_end_neg
,
2729 phdr
->caplen
+= chop
.len_end
;
2732 if (((signed int) phdr
->len
+ chop
.len_end
) > 0)
2733 phdr
->len
+= chop
.len_end
;
2741 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2746 * indent-tabs-mode: nil
2749 * vi: set shiftwidth=4 tabstop=8 expandtab:
2750 * :indentSize=4:tabSize=8:noTabs=true: