LATER packet-kerberos: ticket_checksum tmpvtb...
[wireshark-sm.git] / editcap.c
blobcb2b5004bf8e6931e7018109546271cdbe2dab9f
1 /* editcap.c
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
18 #include <config.h>
19 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdarg.h>
25 #include <math.h>
26 #include <stddef.h>
28 #include <time.h>
29 #include <glib.h>
30 #include <gcrypt.h>
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
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"
45 #ifdef _WIN32
46 #include <process.h> /* getpid */
47 #include <winsock2.h>
48 #endif
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>
58 #include <cli_main.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
72 #define WRITE_ERROR 2
73 #define DUMP_ERROR 2
75 #define NANOSECS_PER_SEC 1000000000
78 * Some globals so we can pass things to various routines
81 struct select_item {
82 bool inclusive;
83 uint64_t first, second;
87 * Duplicate frame detection
89 typedef struct _fd_hash_t {
90 uint8_t digest[16];
91 uint32_t len;
92 nstime_t frame_time;
93 } 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 {
120 nstime_t tv;
121 int is_negative;
124 typedef struct _chop_t {
125 int len_begin;
126 int off_begin_pos;
127 int off_begin_neg;
128 int len_end;
129 int off_end_pos;
130 int off_end_neg;
131 } 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;
141 static bool keep_em;
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 {
168 const char *str;
169 uint32_t id;
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);
181 static char *
182 abs_time_to_str_with_sec_resolution(const nstime_t *abs_time)
184 struct tm *tmp;
185 char *buf = (char *)g_malloc(16);
187 tmp = localtime(&abs_time->secs);
189 if (tmp) {
190 snprintf(buf, 16, "%d%02d%02d%02d%02d%02d",
191 tmp->tm_year + 1900,
192 tmp->tm_mon+1,
193 tmp->tm_mday,
194 tmp->tm_hour,
195 tmp->tm_min,
196 tmp->tm_sec);
197 } else {
198 buf[0] = '\0';
201 return buf;
204 static char *
205 fileset_get_filename_by_pattern(unsigned idx, const nstime_t *ts,
206 char *fprefix, char *fsuffix)
208 char filenum[5+1];
209 char *timestr;
210 char *abs_str;
212 snprintf(filenum, sizeof(filenum), "%05u", idx % RINGBUFFER_MAX_NUM_FILES);
213 if (ts) {
214 timestr = abs_time_to_str_with_sec_resolution(ts);
215 abs_str = g_strconcat(fprefix, "_", filenum, "_", timestr, fsuffix, NULL);
216 g_free(timestr);
217 } else
218 abs_str = g_strconcat(fprefix, "_", filenum, fsuffix, NULL);
220 return abs_str;
223 static bool
224 fileset_extract_prefix_suffix(const char *fname, char **fprefix, char **fsuffix, wtap_compression_type *compression_typep)
226 char *pfx, *last_pathsep;
227 char *save_file;
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");
233 return false;
236 last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
237 if (last_pathsep == NULL) {
238 last_pathsep = save_file;
240 pfx = strrchr(last_pathsep, '.');
241 if (pfx != NULL) {
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
246 * component.
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. */
252 pfx[0] = '\0';
253 compression_type = wtap_extension_to_compression_type(pfx + 1);
254 if (compression_type != WTAP_UNKNOWN_COMPRESSION) {
255 char *pfx2 = strrchr(last_pathsep, '.');
256 if (pfx2 != NULL) {
257 pfx[0] = '.';
258 pfx = pfx2;
259 pfx[0] = '\0';
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);
271 } else {
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);
275 *fsuffix = NULL;
277 g_free(save_file);
278 return true;
281 /* Add a selection item, a simple parser for now */
282 static bool
283 add_selection(char *sel, uint64_t* max_selection)
285 char *locn;
286 char *next;
288 if (max_selected >= MAX_SELECTIONS) {
289 /* Let the user know we stopped selecting */
290 fprintf(stderr, "Out of room for packet selections.\n");
291 return false;
294 if (verbose)
295 fprintf(stderr, "Add_Selected: %s\n", sel);
297 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
298 if (verbose)
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;
306 if (verbose)
307 fprintf(stderr, " %" PRIu64 "\n", selectfrm[max_selected].first);
308 } else {
309 if (verbose)
310 fprintf(stderr, "Inclusive ...");
312 *locn = '\0'; /* split the range */
313 next = locn + 1;
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;
326 if (verbose)
327 fprintf(stderr, " %" PRIu64 ", %" PRIu64 "\n", selectfrm[max_selected].first,
328 selectfrm[max_selected].second);
331 max_selected++;
332 return true;
335 /* Was the packet selected? */
337 static bool
338 selected(uint64_t recno)
340 unsigned i;
342 for (i = 0; i < max_selected; i++) {
343 if (selectfrm[i].inclusive) {
344 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
345 return true;
346 } else {
347 if (recno == selectfrm[i].first)
348 return true;
352 return false;
355 static bool
356 set_time_adjustment(char *optarg_str_p)
358 char *frac, *end;
359 long val;
360 size_t frac_digits;
362 if (!optarg_str_p)
363 return true;
365 /* skip leading whitespace */
366 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
367 optarg_str_p++;
369 /* check for a negative adjustment */
370 if (*optarg_str_p == '-') {
371 time_adj.is_negative = 1;
372 optarg_str_p++;
375 /* collect whole number of seconds, if any */
376 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
377 val = 0;
378 frac = optarg_str_p;
379 } else {
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",
384 optarg_str_p);
385 return false;
387 if (val < 0) { /* implies '--' since we caught '-' above */
388 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
389 optarg_str_p);
390 return false;
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",
406 optarg_str_p);
407 return false;
409 } else {
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 */
417 val *= 10;
418 frac_digits++;
421 time_adj.tv.nsecs = (int)val;
422 return true;
425 static bool
426 set_strict_time_adj(char *optarg_str_p)
428 char *frac, *end;
429 long val;
430 size_t frac_digits;
432 if (!optarg_str_p)
433 return true;
435 /* skip leading whitespace */
436 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
437 optarg_str_p++;
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;
446 optarg_str_p++;
449 /* collect whole number of seconds, if any */
450 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
451 val = 0;
452 frac = optarg_str_p;
453 } else {
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",
458 optarg_str_p);
459 return false;
461 if (val < 0) { /* implies '--' since we caught '-' above */
462 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
463 optarg_str_p);
464 return false;
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",
480 optarg_str_p);
481 return false;
483 } else {
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 */
491 val *= 10;
492 frac_digits++;
495 strict_time_adj.tv.nsecs = (int)val;
496 return true;
499 static bool
500 set_rel_time(char *optarg_str_p)
502 char *frac, *end;
503 long val;
504 size_t frac_digits;
506 if (!optarg_str_p)
507 return true;
509 /* skip leading whitespace */
510 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
511 optarg_str_p++;
513 /* ignore negative adjustment */
514 if (*optarg_str_p == '-')
515 optarg_str_p++;
517 /* collect whole number of seconds, if any */
518 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
519 val = 0;
520 frac = optarg_str_p;
521 } else {
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",
526 optarg_str_p);
527 return false;
529 if (val < 0) { /* implies '--' since we caught '-' above */
530 fprintf(stderr, "2: editcap: \"%s\" isn't a valid rel time value\n",
531 optarg_str_p);
532 return false;
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",
548 optarg_str_p);
549 return false;
551 } else {
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 */
559 val *= 10;
560 frac_digits++;
563 relative_time_window.nsecs = (int)val;
564 return true;
567 #define SLL_ADDRLEN 8 /* length of address field */
568 struct sll_header {
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 */
576 struct sll2_header {
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 */
586 #define VLAN_SIZE 4
587 static void
588 sll_remove_vlan_info(uint8_t* fd, uint32_t* len) {
589 if (pntoh16(fd + offsetof(struct sll_header, sll_protocol)) == ETHERTYPE_VLAN) {
590 int rest_len;
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);
597 *len -= 4;
603 static void
604 sll_set_unused_info(uint8_t* fd) {
605 uint32_t ha_len;
606 ha_len = pntoh16(fd + offsetof(struct sll_header, sll_halen));
608 if (ha_len < SLL_ADDRLEN) {
609 int unused;
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);
618 static void
619 sll2_set_unused_info(uint8_t* fd) {
620 uint32_t ha_len;
621 ha_len = *(fd + offsetof(struct sll2_header, sll2_halen));
623 if (ha_len < SLL_ADDRLEN) {
624 int unused;
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);
633 static void
634 remove_vlan_info(wtap_packet_header *phdr, uint8_t* fd) {
635 switch (phdr->pkt_encap) {
636 case WTAP_ENCAP_SLL:
637 sll_remove_vlan_info(fd, &phdr->caplen);
638 break;
639 default:
640 /* no support for current pkt_encap */
641 break;
645 static void
646 set_unused_info(const wtap_packet_header *phdr, uint8_t* fd) {
647 switch (phdr->pkt_encap) {
648 case WTAP_ENCAP_SLL:
649 sll_set_unused_info(fd);
650 break;
651 case WTAP_ENCAP_SLL2:
652 sll2_set_unused_info(fd);
653 break;
654 default:
655 /* no support for current pkt_encap */
656 break;
660 static bool
661 is_duplicate(uint8_t* fd, uint32_t len) {
662 int i;
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;
667 uint32_t new_len;
668 uint8_t *new_fd;
670 if (len <= ignored_bytes) {
671 offset = 0;
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);
678 if (offset >= len)
679 offset = 0;
682 new_fd = &fd[offset];
683 new_len = len - (offset);
685 cur_dup_entry++;
686 if (cur_dup_entry >= dup_window)
687 cur_dup_entry = 0;
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)
697 continue;
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) {
701 return true;
705 return false;
708 static bool
709 is_duplicate_rel_time(uint8_t* fd, uint32_t len, const nstime_t *current) {
710 int i;
712 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
713 uint32_t offset = ignored_bytes;
714 uint32_t new_len;
715 uint8_t *new_fd;
717 if (len <= ignored_bytes) {
718 offset = 0;
721 new_fd = &fd[offset];
722 new_len = len - (offset);
724 cur_dup_entry++;
725 if (cur_dup_entry >= dup_window)
726 cur_dup_entry = 0;
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--) {
757 nstime_t delta;
758 int cmp;
760 if (i < 0)
761 i = dup_window - 1;
763 if (i == cur_dup_entry) {
765 * We've decremented back to where we started.
766 * Check no more!
768 break;
771 if (nstime_is_unset(&(fd_hash[i].frame_time))) {
773 * We've decremented to an unused fd_hash[] entry.
774 * Check no more!
776 break;
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
798 * packets.
800 continue;
803 cmp = nstime_cmp(&delta, &relative_time_window);
805 if (cmp > 0) {
807 * The delta time indicates that we are now looking at
808 * cached packets beyond the specified dup time window.
809 * Check no more!
811 break;
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) {
814 return true;
818 return false;
821 static void
822 mutate_packet_data(wtap_rec *rec, uint8_t *buf, uint32_t change_offset, uint64_t count)
824 uint32_t caplen;
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);
838 break;
840 case REC_TYPE_FT_SPECIFIC_EVENT:
841 case REC_TYPE_FT_SPECIFIC_REPORT:
842 caplen = rec->rec_header.ft_specific_header.record_len;
843 break;
845 case REC_TYPE_SYSCALL:
846 caplen = rec->rec_header.syscall_header.event_filelen;
847 break;
849 case REC_TYPE_SYSTEMD_JOURNAL_EXPORT:
850 caplen = rec->rec_header.systemd_journal_export_header.record_len;
851 break;
853 default:
854 /* We don't mutate anything else. */
855 return;
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);
861 return;
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;
873 } else {
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;
880 } else {
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;
887 } else {
888 err_type -= ERR_WT_ALNUM;
891 if (err_type < ERR_WT_FMT) {
892 if (i < caplen - 2)
893 (void) g_strlcpy((char*) &buf[i], "%s", 2);
894 err_type = ERR_WT_TOTAL;
895 } else {
896 err_type -= ERR_WT_FMT;
899 if (err_type < ERR_WT_AA) {
900 for (unsigned j = i; j < caplen; j++)
901 buf[j] = 0xAA;
902 i = caplen;
908 static void
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 */
1037 static int
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);
1044 static void
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);
1052 static void
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);
1066 static void
1067 list_encap_types(FILE *stream) {
1068 int i;
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);
1082 g_slist_free(list);
1083 g_free(encaps);
1086 static void
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);
1101 static void
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);
1109 static uint32_t
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;
1117 return 0;
1120 static void
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) {
1131 fprintf(stderr,
1132 "editcap: Warning: \"%s\" is not a key log file, but an unsupported private key file. Decryption will not work.\n",
1133 filename);
1138 static int
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)
1144 return -1;
1146 if (*frame_a > *frame_b)
1147 return 1;
1149 return 0;
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)
1157 wtap_dumper *pdh;
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);
1163 } else {
1164 pdh = wtap_dump_open(filename, out_file_type_subtype, compression_type,
1165 params, err, err_info);
1167 if (pdh == NULL)
1168 return NULL;
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)) {
1205 int close_err;
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);
1211 return NULL;
1215 * Release the copy - wtap_dump_add_idb() makes its own copy.
1217 wtap_block_unref(if_data_copy);
1221 return pdh;
1224 static bool
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
1233 * *requires*) them.
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))
1264 return false;
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);
1281 return true;
1284 static int
1285 extract_secrets(wtap *wth, char* filename, int *err, char **err_info)
1287 wtap_rec read_rec;
1288 int64_t offset;
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));
1308 if (verbose) {
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) {
1313 return WRITE_ERROR;
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));
1318 if (verbose) {
1319 fprintf(stderr, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1320 secrets_type_description(dsb->secrets_type), dsb->secrets_type,
1321 filename);
1323 if (!write_file_binary_mode(filename, dsb->secrets_data, dsb->secrets_len)) {
1324 return WRITE_ERROR;
1326 } else {
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);
1340 if (verbose) {
1341 fprintf(stderr, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1342 secrets_type_description(dsb->secrets_type), dsb->secrets_type,
1343 extract_filename);
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);
1348 g_free(fprefix);
1349 g_free(fsuffix);
1351 return WRITE_ERROR;
1353 g_free(extract_filename);
1355 g_free(fprefix);
1356 g_free(fsuffix);
1358 return EXIT_SUCCESS;
1362 main(int argc, char *argv[])
1364 char *configuration_init_error;
1365 wtap *wth = NULL;
1366 int i, read_err, write_err;
1367 char *read_err_info, *write_err_info;
1368 int opt;
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},
1396 {0, 0, 0, 0 }
1399 char *p;
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;
1405 uint64_t count = 1;
1406 uint64_t duplicate_count = 0;
1407 int64_t data_offset;
1408 uint8_t *buf;
1409 uint64_t read_count = 0;
1410 uint64_t split_packet_count = 0;
1411 uint64_t written_count = 0;
1412 char *filename = NULL;
1413 bool ts_okay;
1414 nstime_t secs_per_block = NSTIME_INIT_UNSET;
1415 int block_cnt = 0;
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;
1423 wtap_rec read_rec;
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");
1446 #ifdef _WIN32
1447 create_app_running_mutex();
1448 #endif /* _WIN32 */
1451 * Get credential information for later use.
1453 init_process_policies();
1456 * Attempt to get the pathname of the directory containing the
1457 * executable file.
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");
1471 wtap_init(true);
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;
1478 switch (opt) {
1479 case LONGOPT_NO_VLAN:
1481 rem_vlan = true;
1482 break;
1485 case LONGOPT_SKIP_RADIOTAP_HEADER:
1487 skip_radiotap = true;
1488 break;
1491 case LONGOPT_SEED:
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;
1496 goto clean_exit;
1498 valid_seed = true;
1499 break;
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);
1508 goto clean_exit;
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;
1517 goto clean_exit;
1519 secrets_filename = splitted[1];
1520 } else {
1521 cmdarg_err("no secrets type was specified for --inject-secrets");
1522 g_strfreev(splitted);
1523 ret = WS_EXIT_INVALID_OPTION;
1524 goto clean_exit;
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);
1533 break;
1536 case LONGOPT_DISCARD_ALL_SECRETS:
1538 discard_all_secrets = true;
1539 break;
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
1549 * comments?
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;
1556 goto clean_exit;
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));
1565 break;
1568 case LONGOPT_DISCARD_CAPTURE_COMMENT:
1570 discard_cap_comments = true;
1571 break;
1574 case LONGOPT_SET_UNUSED:
1576 set_unused = true;
1577 break;
1580 case LONGOPT_DISCARD_PACKET_COMMENTS:
1582 discard_pkt_comments = true;
1583 break;
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)?
1592 break;
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",
1600 ws_optarg);
1601 list_output_compression_types();
1602 goto clean_exit;
1604 break;
1607 case 'a':
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;
1615 goto clean_exit;
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
1623 * comments?
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.",
1628 frame_number);
1629 ret = WS_EXIT_INVALID_OPTION;
1630 goto clean_exit;
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));
1642 break;
1645 case 'A':
1646 case 'B':
1648 nstime_t in_time;
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))) {
1652 if (opt == 'A') {
1653 nstime_copy(&starttime, &in_time);
1654 have_starttime = true;
1655 } else {
1656 nstime_copy(&stoptime, &in_time);
1657 have_stoptime = true;
1659 break;
1661 else {
1662 cmdarg_err("\"%s\" isn't a valid date and time", ws_optarg);
1663 ret = WS_EXIT_INVALID_OPTION;
1664 goto clean_exit;
1668 case 'c':
1669 split_packet_count = get_nonzero_uint64(ws_optarg, "packet count");
1670 break;
1672 case 'C':
1674 int choplen = 0, chopoff = 0;
1676 switch (sscanf(ws_optarg, "%d:%d", &chopoff, &choplen)) {
1677 case 1: /* only the chop length was specified */
1678 choplen = chopoff;
1679 chopoff = 0;
1680 break;
1682 case 2: /* both an offset and chop length was specified */
1683 break;
1685 default:
1686 cmdarg_err("\"%s\" isn't a valid chop length or offset:length", ws_optarg);
1687 ret = WS_EXIT_INVALID_OPTION;
1688 goto clean_exit;
1689 break;
1692 if (choplen > 0) {
1693 chop.len_begin += choplen;
1694 if (chopoff > 0)
1695 chop.off_begin_pos += chopoff;
1696 else
1697 chop.off_begin_neg += chopoff;
1698 } else if (choplen < 0) {
1699 chop.len_end += choplen;
1700 if (chopoff > 0)
1701 chop.off_end_pos += chopoff;
1702 else
1703 chop.off_end_neg += chopoff;
1705 break;
1708 case 'd':
1709 dup_detect = true;
1710 dup_detect_by_time = false;
1711 dup_window = DEFAULT_DUP_DEPTH;
1712 break;
1714 case 'D':
1715 dup_detect = true;
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;
1722 goto clean_exit;
1724 break;
1726 case 'E':
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;
1731 goto clean_exit;
1733 break;
1735 case 'F':
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;
1741 goto clean_exit;
1743 break;
1745 case 'h':
1746 show_help_header("Edit and/or translate the format of capture files.");
1747 print_usage(stdout);
1748 goto clean_exit;
1749 break;
1751 case 'i': /* break capture file based on time interval */
1753 double spb = get_positive_double(ws_optarg, "time interval");
1754 if (spb == 0.0) {
1755 cmdarg_err("The specified interval is zero");
1756 ret = WS_EXIT_INVALID_OPTION;
1757 goto clean_exit;
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);
1765 break;
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");
1769 break;
1771 case 'L':
1772 adjlen = true;
1773 break;
1775 case 'o':
1776 change_offset = get_uint32(ws_optarg, "change offset");
1777 break;
1779 case 'r':
1780 if (keep_em) {
1781 cmdarg_err("-r was specified twice");
1782 ret = WS_EXIT_INVALID_OPTION;
1783 goto clean_exit;
1785 keep_em = true;
1786 break;
1788 case 's':
1789 snaplen = get_nonzero_uint32(ws_optarg, "snapshot length");
1790 break;
1792 case 'S':
1793 if (!set_strict_time_adj(ws_optarg)) {
1794 ret = WS_EXIT_INVALID_OPTION;
1795 goto clean_exit;
1797 do_strict_time_adjustment = true;
1798 break;
1800 case 't':
1801 if (!set_time_adjustment(ws_optarg)) {
1802 ret = WS_EXIT_INVALID_OPTION;
1803 goto clean_exit;
1805 break;
1807 case 'T':
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;
1813 goto clean_exit;
1815 break;
1817 case 'V':
1818 if (verbose) {
1819 cmdarg_err("-V was specified twice");
1820 ret = WS_EXIT_INVALID_OPTION;
1821 goto clean_exit;
1823 verbose = true;
1824 break;
1826 case 'v':
1827 show_version();
1828 goto clean_exit;
1829 break;
1831 case 'w':
1832 dup_detect = false;
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;
1837 goto clean_exit;
1839 break;
1841 case '?': /* Bad options - print usage */
1842 default:
1843 switch(ws_optopt) {
1844 case'F':
1845 list_capture_types(stdout);
1846 break;
1847 case'T':
1848 list_encap_types(stdout);
1849 break;
1850 case LONGOPT_COMPRESS:
1851 list_output_compression_types();
1852 break;
1853 default:
1854 print_usage(stderr);
1855 ret = WS_EXIT_INVALID_OPTION;
1856 break;
1858 goto clean_exit;
1859 break;
1861 } /* processing command-line options */
1863 #ifdef DEBUG
1864 fprintf(stderr, "Optind = %i, argc = %i\n", ws_optind, argc);
1865 #endif
1867 if ((argc - ws_optind) < 2) {
1868 print_usage(stderr);
1869 ret = WS_EXIT_INVALID_OPTION;
1870 goto clean_exit;
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;
1881 goto clean_exit;
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], '.');
1888 if (sfx) {
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;
1901 goto clean_exit;
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;
1908 goto clean_exit;
1911 if (err_prob >= 0.0) {
1912 if (!valid_seed) {
1913 seed = (unsigned int) (time(NULL) + ws_getpid());
1915 if (verbose) {
1916 fprintf(stderr, "Using seed %u\n", seed);
1918 srand(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;
1925 goto clean_exit;
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;
1932 goto clean_exit;
1935 wth = wtap_open_offline(argv[ws_optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, false);
1937 if (!wth) {
1938 cfile_open_failure_message(argv[ws_optind], read_err, read_err_info);
1939 ret = WS_EXIT_INVALID_FILE;
1940 goto clean_exit;
1943 if (verbose) {
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;
1953 goto clean_exit;
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));
1961 } else {
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;
1967 goto clean_exit;
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;
1975 goto clean_exit;
1977 if (compression_type != WTAP_UNCOMPRESSED) {
1978 cmdarg_err("compression isn't supported for extracting secrets");
1979 ret = WS_EXIT_INVALID_OPTION;
1980 goto clean_exit;
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
1986 * line. */
1987 cfile_read_failure_message(argv[ws_optind], read_err, read_err_info);
1989 goto clean_exit;
1992 wtap_dump_params_init_no_idbs(&params, wth);
1995 * Discard any secrets we read in while opening the file.
1997 if (discard_all_secrets) {
1998 wtap_dump_params_discard_decryption_secrets(&params);
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);
2030 char *data;
2031 size_t data_len;
2032 wtap_block_t block;
2033 wtapng_dsb_mandatory_t *dsb;
2034 GError *err = NULL;
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;
2040 goto clean_exit;
2042 if (data_len == 0) {
2043 cmdarg_err("\"%s\" is an empty file, ignoring", secrets_filename);
2044 g_free(data);
2045 continue;
2047 if (data_len >= INT_MAX) {
2048 cmdarg_err("\"%s\" is too large, ignoring", secrets_filename);
2049 g_free(data);
2050 continue;
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
2078 * file.
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)
2089 break;
2091 if (keep_em && max_selected == 0) {
2092 cmdarg_err("must specify packets to keep when using -r");
2093 ret = WS_EXIT_INVALID_OPTION;
2094 goto clean_exit;
2097 if (!keep_em)
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);
2103 fd_hash[i].len = 0;
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
2118 * custom blocks?
2120 if (max_packet_number <= read_count)
2121 break;
2123 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,
2130 fprefix, fsuffix);
2131 } else {
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, &params, idbs_seen, &write_err,
2142 &write_err_info, compression_type);
2144 if (pdh == NULL) {
2145 cfile_dump_open_failure_message(filename,
2146 write_err, write_err_info,
2147 out_file_type_subtype);
2148 ret = WS_EXIT_INVALID_FILE;
2149 goto clean_exit;
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,
2159 read_count,
2160 out_file_type_subtype);
2161 ret = DUMP_ERROR;
2164 * Close the dump file, but don't report an error
2165 * or set the exit code, as we've already reported
2166 * an error.
2168 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2169 goto clean_exit;
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,
2192 write_err_info);
2193 ret = WRITE_ERROR;
2194 goto clean_exit;
2196 g_free(filename);
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 */
2202 if (verbose)
2203 fprintf(stderr, "Continuing writing in file %s\n", filename);
2205 pdh = editcap_dump_open(filename, &params, idbs_seen,
2206 &write_err, &write_err_info, compression_type);
2208 if (pdh == NULL) {
2209 cfile_dump_open_failure_message(filename,
2210 write_err,
2211 write_err_info,
2212 out_file_type_subtype);
2213 ret = WS_EXIT_INVALID_FILE;
2214 goto clean_exit;
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,
2230 write_err_info);
2231 ret = WRITE_ERROR;
2232 goto clean_exit;
2235 g_free(filename);
2236 filename = fileset_get_filename_by_pattern(block_cnt++,
2237 (read_rec.presence_flags & WTAP_HAS_TS) ? &read_rec.ts : NULL,
2238 fprefix, fsuffix);
2239 ws_assert(filename);
2241 if (verbose)
2242 fprintf(stderr, "Continuing writing in file %s\n", filename);
2244 pdh = editcap_dump_open(filename, &params, idbs_seen,
2245 &write_err, &write_err_info, compression_type);
2246 if (pdh == NULL) {
2247 cfile_dump_open_failure_message(filename,
2248 write_err, write_err_info,
2249 out_file_type_subtype);
2250 ret = WS_EXIT_INVALID_FILE;
2251 goto clean_exit;
2254 } /* split packet handling */
2256 if (check_startstop) {
2257 ts_okay = false;
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;
2272 } else {
2274 * No selected timeframe, so all packets are "in the
2275 * selected timeframe".
2277 ts_okay = true;
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
2289 * order? */
2290 if (do_strict_time_adjustment) {
2291 if (previous_time.secs || previous_time.nsecs) {
2292 if (!strict_time_adj.is_negative) {
2293 nstime_t current;
2294 nstime_t delta;
2296 current = read_rec.ts;
2298 nstime_delta(&delta, &current, &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) {
2312 /* carry */
2313 read_rec.ts.secs++;
2314 read_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2315 } else {
2316 read_rec.ts.nsecs += strict_time_adj.tv.nsecs;
2319 } else {
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) {
2328 /* carry */
2329 read_rec.ts.secs++;
2330 read_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2331 } else {
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;
2342 else
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 */
2349 read_rec.ts.secs--;
2350 read_rec.ts.nsecs += ONE_BILLION;
2352 read_rec.ts.nsecs -= time_adj.tv.nsecs;
2353 } else { /* add */
2354 if (read_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
2355 /* carry */
2356 read_rec.ts.secs++;
2357 read_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
2358 } else {
2359 read_rec.ts.nsecs += time_adj.tv.nsecs;
2363 } /* time stamp adjustment */
2365 if (read_rec.rec_type == REC_TYPE_PACKET) {
2366 if (snaplen != 0) {
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;
2386 * CHOP
2388 handle_chopping(chop, &read_rec.rec_header.packet_header,
2389 &buf, adjlen);
2391 /* set unused info */
2392 if (set_unused) {
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 */
2398 if (rem_vlan) {
2399 remove_vlan_info(&read_rec.rec_header.packet_header, buf);
2402 /* suppress duplicates by packet window */
2403 if (dup_detect) {
2404 if (is_duplicate(buf, read_rec.rec_header.packet_header.caplen)) {
2405 if (verbose) {
2406 fprintf(stderr, "Skipped: %" PRIu64 ", Len: %u, MD5 Hash: ",
2407 count,
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");
2414 duplicate_count++;
2415 count++;
2416 continue;
2417 } else {
2418 if (verbose) {
2419 fprintf(stderr, "Packet: %" PRIu64 ", Len: %u, MD5 Hash: ",
2420 count,
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) {
2433 nstime_t current;
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,
2440 &current)) {
2441 if (verbose) {
2442 fprintf(stderr, "Skipped: %" PRIu64 ", Len: %u, MD5 Hash: ",
2443 count,
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");
2450 duplicate_count++;
2451 count++;
2452 continue;
2453 } else {
2454 if (verbose) {
2455 fprintf(stderr, "Packet: %" PRIu64 ", Len: %u, MD5 Hash: ",
2456 count,
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;
2493 } else {
2494 read_rec.block_was_modified = false;
2498 if (discard_all_secrets) {
2500 * Discard any secrets we've read since the last packet
2501 * we wrote.
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,
2510 read_count,
2511 out_file_type_subtype);
2512 ret = DUMP_ERROR;
2515 * Close the dump file, but don't report an error
2516 * or set the exit code, as we've already reported
2517 * an error.
2519 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2520 goto clean_exit;
2522 written_count++;
2524 count++;
2525 wtap_rec_reset(&read_rec);
2527 wtap_rec_cleanup(&read_rec);
2529 if (verbose)
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
2534 * line. */
2535 cfile_read_failure_message(argv[ws_optind], read_err, read_err_info);
2538 if (!pdh) {
2539 /* No valid packets found, open the outfile so we can write an
2540 * empty header */
2541 g_free (filename);
2542 filename = g_strdup(argv[ws_optind+1]);
2544 pdh = editcap_dump_open(filename, &params, idbs_seen, &write_err,
2545 &write_err_info, compression_type);
2546 if (pdh == NULL) {
2547 cfile_dump_open_failure_message(filename,
2548 write_err, write_err_info,
2549 out_file_type_subtype);
2550 ret = WS_EXIT_INVALID_FILE;
2551 goto clean_exit;
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,
2561 read_count,
2562 out_file_type_subtype);
2563 ret = DUMP_ERROR;
2566 * Close the dump file, but don't report an error
2567 * or set the exit code, as we've already reported
2568 * an error.
2570 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2571 goto clean_exit;
2574 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2575 cfile_close_failure_message(filename, write_err, write_err_info);
2576 ret = WRITE_ERROR;
2577 goto clean_exit;
2580 if (dup_detect) {
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);
2592 clean_exit:
2593 g_free(fprefix);
2594 g_free(fsuffix);
2596 if (filename) {
2597 g_free(filename);
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(&params);
2615 if (wth != NULL)
2616 wtap_close(wth);
2617 wtap_rec_reset(&read_rec);
2618 wtap_cleanup();
2619 free_progdirs();
2620 if (capture_comments != NULL) {
2621 g_ptr_array_free(capture_comments, TRUE);
2622 capture_comments = NULL;
2624 return ret;
2627 /* Skip meta-information read from file to return offset of real
2628 * protocol data */
2629 static unsigned
2630 find_dct2000_real_data(const uint8_t *buf)
2632 unsigned n = 0;
2634 for (n = 0; buf[n] != '\0'; n++); /* Context name */
2635 n++;
2636 n++; /* Context port number */
2637 for (; buf[n] != '\0'; n++); /* Timestamp */
2638 n++;
2639 for (; buf[n] != '\0'; n++); /* Protocol name */
2640 n++;
2641 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
2642 n++;
2643 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
2644 n++;
2645 n += 2; /* Direction & encap */
2647 return n;
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.
2654 static void
2655 handle_chopping(chop_t chop, wtap_packet_header *phdr, uint8_t **buf,
2656 bool adjlen)
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)) {
2692 chop.len_begin = 0;
2693 chop.len_end = 0;
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);
2698 chop.len_end = 0;
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));
2708 } else {
2709 *buf += chop.len_begin;
2711 phdr->caplen -= chop.len_begin;
2713 if (adjlen) {
2714 if (phdr->len > (uint32_t)chop.len_begin)
2715 phdr->len -= chop.len_begin;
2716 else
2717 phdr->len = 0;
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,
2727 -chop.off_end_neg);
2729 phdr->caplen += chop.len_end;
2731 if (adjlen) {
2732 if (((signed int) phdr->len + chop.len_end) > 0)
2733 phdr->len += chop.len_end;
2734 else
2735 phdr->len = 0;
2741 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2743 * Local variables:
2744 * c-basic-offset: 4
2745 * tab-width: 8
2746 * indent-tabs-mode: nil
2747 * End:
2749 * vi: set shiftwidth=4 tabstop=8 expandtab:
2750 * :indentSize=4:tabSize=8:noTabs=true: