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