dcerpc-netlogon: maintain netlogon_auth_vars for NetrServerAuthenticateKerberos
[wireshark-sm.git] / editcap.c
blob0550e162615233b83e69d129a63ee3272c5345fe
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 int find_dct2000_real_data(uint8_t *buf);
178 static void handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
179 const wtap_packet_header *in_phdr, uint8_t **buf,
180 bool adjlen);
182 static char *
183 abs_time_to_str_with_sec_resolution(const nstime_t *abs_time)
185 struct tm *tmp;
186 char *buf = (char *)g_malloc(16);
188 tmp = localtime(&abs_time->secs);
190 if (tmp) {
191 snprintf(buf, 16, "%d%02d%02d%02d%02d%02d",
192 tmp->tm_year + 1900,
193 tmp->tm_mon+1,
194 tmp->tm_mday,
195 tmp->tm_hour,
196 tmp->tm_min,
197 tmp->tm_sec);
198 } else {
199 buf[0] = '\0';
202 return buf;
205 static char *
206 fileset_get_filename_by_pattern(unsigned idx, const wtap_rec *rec,
207 char *fprefix, char *fsuffix)
209 char filenum[5+1];
210 char *timestr;
211 char *abs_str;
213 snprintf(filenum, sizeof(filenum), "%05u", idx % RINGBUFFER_MAX_NUM_FILES);
214 if (rec && rec->presence_flags & WTAP_HAS_TS) {
215 timestr = abs_time_to_str_with_sec_resolution(&rec->ts);
216 abs_str = g_strconcat(fprefix, "_", filenum, "_", timestr, fsuffix, NULL);
217 g_free(timestr);
218 } else
219 abs_str = g_strconcat(fprefix, "_", filenum, fsuffix, NULL);
221 return abs_str;
224 static bool
225 fileset_extract_prefix_suffix(const char *fname, char **fprefix, char **fsuffix, wtap_compression_type *compression_typep)
227 char *pfx, *last_pathsep;
228 char *save_file;
229 wtap_compression_type compression_type;
231 save_file = g_strdup(fname);
232 if (save_file == NULL) {
233 fprintf(stderr, "editcap: Out of memory\n");
234 return false;
237 last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
238 if (last_pathsep == NULL) {
239 last_pathsep = save_file;
241 pfx = strrchr(last_pathsep, '.');
242 if (pfx != NULL) {
243 /* The pathname has a "." in it, and it's in the last component
244 * of the pathname (because there is either only one component,
245 * i.e. last_pathsep is null as there are no path separators,
246 * or the "." is after the path separator before the last
247 * component.
249 * Treat it as a separator between the rest of the file name and
250 * the file name suffix, and arrange that the names given to the
251 * ring buffer files have the specified suffix, i.e. put the
252 * changing part of the name *before* the suffix. */
253 pfx[0] = '\0';
254 compression_type = wtap_extension_to_compression_type(pfx + 1);
255 if (compression_type != WTAP_UNKNOWN_COMPRESSION) {
256 char *pfx2 = strrchr(last_pathsep, '.');
257 if (pfx2 != NULL) {
258 pfx[0] = '.';
259 pfx = pfx2;
260 pfx[0] = '\0';
262 if (compression_typep && *compression_typep == WTAP_UNKNOWN_COMPRESSION) {
263 *compression_typep = compression_type;
265 /* XXX - What if there's an extension matching a compression type
266 * and the passed in compression type is known but something else?
269 *fprefix = g_strdup(save_file);
270 pfx[0] = '.'; /* restore capfile_name */
271 *fsuffix = g_strdup(pfx);
272 } else {
273 /* Either there's no "." in the pathname, or it's in a directory
274 * component, so the last component has no suffix. */
275 *fprefix = g_strdup(save_file);
276 *fsuffix = NULL;
278 g_free(save_file);
279 return true;
282 /* Add a selection item, a simple parser for now */
283 static bool
284 add_selection(char *sel, uint64_t* max_selection)
286 char *locn;
287 char *next;
289 if (max_selected >= MAX_SELECTIONS) {
290 /* Let the user know we stopped selecting */
291 fprintf(stderr, "Out of room for packet selections.\n");
292 return false;
295 if (verbose)
296 fprintf(stderr, "Add_Selected: %s\n", sel);
298 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
299 if (verbose)
300 fprintf(stderr, "Not inclusive ...");
302 selectfrm[max_selected].inclusive = false;
303 selectfrm[max_selected].first = get_uint64(sel, "packet number");
304 if (selectfrm[max_selected].first > *max_selection)
305 *max_selection = selectfrm[max_selected].first;
307 if (verbose)
308 fprintf(stderr, " %" PRIu64 "\n", selectfrm[max_selected].first);
309 } else {
310 if (verbose)
311 fprintf(stderr, "Inclusive ...");
313 *locn = '\0'; /* split the range */
314 next = locn + 1;
315 selectfrm[max_selected].inclusive = true;
316 selectfrm[max_selected].first = get_uint64(sel, "beginning of packet range");
317 selectfrm[max_selected].second = get_uint64(next, "end of packet range");
319 if (selectfrm[max_selected].second == 0)
321 /* Not a valid number, presume all */
322 selectfrm[max_selected].second = *max_selection = UINT64_MAX;
324 else if (selectfrm[max_selected].second > *max_selection)
325 *max_selection = selectfrm[max_selected].second;
327 if (verbose)
328 fprintf(stderr, " %" PRIu64 ", %" PRIu64 "\n", selectfrm[max_selected].first,
329 selectfrm[max_selected].second);
332 max_selected++;
333 return true;
336 /* Was the packet selected? */
338 static bool
339 selected(uint64_t recno)
341 unsigned i;
343 for (i = 0; i < max_selected; i++) {
344 if (selectfrm[i].inclusive) {
345 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
346 return true;
347 } else {
348 if (recno == selectfrm[i].first)
349 return true;
353 return false;
356 static bool
357 set_time_adjustment(char *optarg_str_p)
359 char *frac, *end;
360 long val;
361 size_t frac_digits;
363 if (!optarg_str_p)
364 return true;
366 /* skip leading whitespace */
367 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
368 optarg_str_p++;
370 /* check for a negative adjustment */
371 if (*optarg_str_p == '-') {
372 time_adj.is_negative = 1;
373 optarg_str_p++;
376 /* collect whole number of seconds, if any */
377 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
378 val = 0;
379 frac = optarg_str_p;
380 } else {
381 val = strtol(optarg_str_p, &frac, 10);
382 if (frac == NULL || frac == optarg_str_p
383 || val == LONG_MIN || val == LONG_MAX) {
384 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
385 optarg_str_p);
386 return false;
388 if (val < 0) { /* implies '--' since we caught '-' above */
389 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
390 optarg_str_p);
391 return false;
394 time_adj.tv.secs = val;
396 /* now collect the partial seconds, if any */
397 if (*frac != '\0') { /* chars left, so get fractional part */
398 val = strtol(&(frac[1]), &end, 10);
399 /* if more than 9 fractional digits truncate to 9 */
400 if ((end - &(frac[1])) > 9) {
401 frac[10] = 't'; /* 't' for truncate */
402 val = strtol(&(frac[1]), &end, 10);
404 if (*frac != '.' || end == NULL || end == frac || val < 0
405 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
406 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
407 optarg_str_p);
408 return false;
410 } else {
411 return true; /* no fractional digits */
414 /* adjust fractional portion from fractional to numerator
415 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
416 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
417 while(frac_digits < 9) { /* this is frac of 10^9 */
418 val *= 10;
419 frac_digits++;
422 time_adj.tv.nsecs = (int)val;
423 return true;
426 static bool
427 set_strict_time_adj(char *optarg_str_p)
429 char *frac, *end;
430 long val;
431 size_t frac_digits;
433 if (!optarg_str_p)
434 return true;
436 /* skip leading whitespace */
437 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
438 optarg_str_p++;
441 * check for a negative adjustment
442 * A negative strict adjustment value is a flag
443 * to adjust all frames by the specified delta time.
445 if (*optarg_str_p == '-') {
446 strict_time_adj.is_negative = 1;
447 optarg_str_p++;
450 /* collect whole number of seconds, if any */
451 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
452 val = 0;
453 frac = optarg_str_p;
454 } else {
455 val = strtol(optarg_str_p, &frac, 10);
456 if (frac == NULL || frac == optarg_str_p
457 || val == LONG_MIN || val == LONG_MAX) {
458 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
459 optarg_str_p);
460 return false;
462 if (val < 0) { /* implies '--' since we caught '-' above */
463 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
464 optarg_str_p);
465 return false;
468 strict_time_adj.tv.secs = val;
470 /* now collect the partial seconds, if any */
471 if (*frac != '\0') { /* chars left, so get fractional part */
472 val = strtol(&(frac[1]), &end, 10);
473 /* if more than 9 fractional digits truncate to 9 */
474 if ((end - &(frac[1])) > 9) {
475 frac[10] = 't'; /* 't' for truncate */
476 val = strtol(&(frac[1]), &end, 10);
478 if (*frac != '.' || end == NULL || end == frac || val < 0
479 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
480 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
481 optarg_str_p);
482 return false;
484 } else {
485 return true; /* no fractional digits */
488 /* adjust fractional portion from fractional to numerator
489 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
490 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
491 while(frac_digits < 9) { /* this is frac of 10^9 */
492 val *= 10;
493 frac_digits++;
496 strict_time_adj.tv.nsecs = (int)val;
497 return true;
500 static bool
501 set_rel_time(char *optarg_str_p)
503 char *frac, *end;
504 long val;
505 size_t frac_digits;
507 if (!optarg_str_p)
508 return true;
510 /* skip leading whitespace */
511 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
512 optarg_str_p++;
514 /* ignore negative adjustment */
515 if (*optarg_str_p == '-')
516 optarg_str_p++;
518 /* collect whole number of seconds, if any */
519 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
520 val = 0;
521 frac = optarg_str_p;
522 } else {
523 val = strtol(optarg_str_p, &frac, 10);
524 if (frac == NULL || frac == optarg_str_p
525 || val == LONG_MIN || val == LONG_MAX) {
526 fprintf(stderr, "1: editcap: \"%s\" isn't a valid rel time value\n",
527 optarg_str_p);
528 return false;
530 if (val < 0) { /* implies '--' since we caught '-' above */
531 fprintf(stderr, "2: editcap: \"%s\" isn't a valid rel time value\n",
532 optarg_str_p);
533 return false;
536 relative_time_window.secs = val;
538 /* now collect the partial seconds, if any */
539 if (*frac != '\0') { /* chars left, so get fractional part */
540 val = strtol(&(frac[1]), &end, 10);
541 /* if more than 9 fractional digits truncate to 9 */
542 if ((end - &(frac[1])) > 9) {
543 frac[10] = 't'; /* 't' for truncate */
544 val = strtol(&(frac[1]), &end, 10);
546 if (*frac != '.' || end == NULL || end == frac || val < 0
547 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
548 fprintf(stderr, "3: editcap: \"%s\" isn't a valid rel time value\n",
549 optarg_str_p);
550 return false;
552 } else {
553 return true; /* no fractional digits */
556 /* adjust fractional portion from fractional to numerator
557 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
558 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
559 while(frac_digits < 9) { /* this is frac of 10^9 */
560 val *= 10;
561 frac_digits++;
564 relative_time_window.nsecs = (int)val;
565 return true;
568 #define SLL_ADDRLEN 8 /* length of address field */
569 struct sll_header {
570 uint16_t sll_pkttype; /* packet type */
571 uint16_t sll_hatype; /* link-layer address type */
572 uint16_t sll_halen; /* link-layer address length */
573 uint8_t sll_addr[SLL_ADDRLEN]; /* link-layer address */
574 uint16_t sll_protocol; /* protocol */
577 struct sll2_header {
578 uint16_t sll2_protocol; /* protocol */
579 uint16_t sll2_reserved_mbz; /* reserved - must be zero */
580 uint32_t sll2_if_index; /* 1-based interface index */
581 uint16_t sll2_hatype; /* link-layer address type */
582 uint8_t sll2_pkttype; /* packet type */
583 uint8_t sll2_halen; /* link-layer address length */
584 uint8_t sll2_addr[SLL_ADDRLEN]; /* link-layer address */
587 #define VLAN_SIZE 4
588 static void
589 sll_remove_vlan_info(uint8_t* fd, uint32_t* len) {
590 if (pntoh16(fd + offsetof(struct sll_header, sll_protocol)) == ETHERTYPE_VLAN) {
591 int rest_len;
592 /* point to start of vlan */
593 fd = fd + offsetof(struct sll_header, sll_protocol);
594 /* bytes to read after vlan info */
595 rest_len = *len - (offsetof(struct sll_header, sll_protocol) + VLAN_SIZE);
596 /* remove vlan info from packet */
597 memmove(fd, fd + VLAN_SIZE, rest_len);
598 *len -= 4;
604 static void
605 sll_set_unused_info(uint8_t* fd) {
606 uint32_t ha_len;
607 ha_len = pntoh16(fd + offsetof(struct sll_header, sll_halen));
609 if (ha_len < SLL_ADDRLEN) {
610 int unused;
611 unused = SLL_ADDRLEN - ha_len;
612 /* point to end of sll_ddr */
613 fd = fd + offsetof(struct sll_header, sll_addr) + ha_len;
614 /* set zeros in the unused data */
615 memset(fd, 0, unused);
619 static void
620 sll2_set_unused_info(uint8_t* fd) {
621 uint32_t ha_len;
622 ha_len = *(fd + offsetof(struct sll2_header, sll2_halen));
624 if (ha_len < SLL_ADDRLEN) {
625 int unused;
626 unused = SLL_ADDRLEN - ha_len;
627 /* point to end of sll2_addr */
628 fd = fd + offsetof(struct sll2_header, sll2_addr) + ha_len;
629 /* set zeros in the unused data */
630 memset(fd, 0, unused);
634 static void
635 remove_vlan_info(const wtap_packet_header *phdr, uint8_t* fd, uint32_t* len) {
636 switch (phdr->pkt_encap) {
637 case WTAP_ENCAP_SLL:
638 sll_remove_vlan_info(fd, len);
639 break;
640 default:
641 /* no support for current pkt_encap */
642 break;
646 static void
647 set_unused_info(const wtap_packet_header *phdr, uint8_t* fd) {
648 switch (phdr->pkt_encap) {
649 case WTAP_ENCAP_SLL:
650 sll_set_unused_info(fd);
651 break;
652 case WTAP_ENCAP_SLL2:
653 sll2_set_unused_info(fd);
654 break;
655 default:
656 /* no support for current pkt_encap */
657 break;
661 static bool
662 is_duplicate(uint8_t* fd, uint32_t len) {
663 int i;
664 const struct ieee80211_radiotap_header* tap_header;
666 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
667 uint32_t offset = ignored_bytes;
668 uint32_t new_len;
669 uint8_t *new_fd;
671 if (len <= ignored_bytes) {
672 offset = 0;
675 /* Get the size of radiotap header and use that as offset (-p option) */
676 if (skip_radiotap == true) {
677 tap_header = (const struct ieee80211_radiotap_header*)fd;
678 offset = pletoh16(&tap_header->it_len);
679 if (offset >= len)
680 offset = 0;
683 new_fd = &fd[offset];
684 new_len = len - (offset);
686 cur_dup_entry++;
687 if (cur_dup_entry >= dup_window)
688 cur_dup_entry = 0;
690 /* Calculate our digest */
691 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
693 fd_hash[cur_dup_entry].len = len;
695 /* Look for duplicates */
696 for (i = 0; i < dup_window; i++) {
697 if (i == cur_dup_entry)
698 continue;
700 if (fd_hash[i].len == fd_hash[cur_dup_entry].len
701 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
702 return true;
706 return false;
709 static bool
710 is_duplicate_rel_time(uint8_t* fd, uint32_t len, const nstime_t *current) {
711 int i;
713 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
714 uint32_t offset = ignored_bytes;
715 uint32_t new_len;
716 uint8_t *new_fd;
718 if (len <= ignored_bytes) {
719 offset = 0;
722 new_fd = &fd[offset];
723 new_len = len - (offset);
725 cur_dup_entry++;
726 if (cur_dup_entry >= dup_window)
727 cur_dup_entry = 0;
729 /* Calculate our digest */
730 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
732 fd_hash[cur_dup_entry].len = len;
733 fd_hash[cur_dup_entry].frame_time.secs = current->secs;
734 fd_hash[cur_dup_entry].frame_time.nsecs = current->nsecs;
737 * Look for relative time related duplicates.
738 * This is hopefully a reasonably efficient mechanism for
739 * finding duplicates by rel time in the fd_hash[] cache.
740 * We check starting from the most recently added hash
741 * entries and work backwards towards older packets.
742 * This approach allows the dup test to be terminated
743 * when the relative time of a cached entry is found to
744 * be beyond the dup time window.
746 * Of course this assumes that the input trace file is
747 * "well-formed" in the sense that the packet timestamps are
748 * in strict chronologically increasing order (which is NOT
749 * always the case!!).
751 * The fd_hash[] table was deliberately created large (1,000,000).
752 * Looking for time related duplicates in large trace files with
753 * non-fractional dup time window values can potentially take
754 * a long time to complete.
757 for (i = cur_dup_entry - 1;; i--) {
758 nstime_t delta;
759 int cmp;
761 if (i < 0)
762 i = dup_window - 1;
764 if (i == cur_dup_entry) {
766 * We've decremented back to where we started.
767 * Check no more!
769 break;
772 if (nstime_is_unset(&(fd_hash[i].frame_time))) {
774 * We've decremented to an unused fd_hash[] entry.
775 * Check no more!
777 break;
780 nstime_delta(&delta, current, &fd_hash[i].frame_time);
782 if (delta.secs < 0 || delta.nsecs < 0) {
784 * A negative delta implies that the current packet
785 * has an absolute timestamp less than the cached packet
786 * that it is being compared to. This is NOT a normal
787 * situation since trace files usually have packets in
788 * chronological order (oldest to newest).
790 * There are several possible ways to deal with this:
791 * 1. 'continue' dup checking with the next cached frame.
792 * 2. 'break' from looking for a duplicate of the current frame.
793 * 3. Take the absolute value of the delta and see if that
794 * falls within the specified dup time window.
796 * Currently this code does option 1. But it would pretty
797 * easy to add yet-another-editcap-option to select one of
798 * the other behaviors for dealing with out-of-sequence
799 * packets.
801 continue;
804 cmp = nstime_cmp(&delta, &relative_time_window);
806 if (cmp > 0) {
808 * The delta time indicates that we are now looking at
809 * cached packets beyond the specified dup time window.
810 * Check no more!
812 break;
813 } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len
814 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
815 return true;
819 return false;
822 static void
823 print_usage(FILE *output)
825 fprintf(output, "\n");
826 fprintf(output, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
827 fprintf(output, "\n");
828 fprintf(output, "<infile> and <outfile> must both be present; use '-' for stdin or stdout.\n");
829 fprintf(output, "A single packet or a range of packets can be selected.\n");
830 fprintf(output, "\n");
831 fprintf(output, "Packet selection:\n");
832 fprintf(output, " -r keep the selected packets; default is to delete them.\n");
833 fprintf(output, " -A <start time> only read packets whose timestamp is after (or equal\n");
834 fprintf(output, " to) the given time.\n");
835 fprintf(output, " -B <stop time> only read packets whose timestamp is before the\n");
836 fprintf(output, " given time.\n");
837 fprintf(output, " Time format for -A/-B options is\n");
838 fprintf(output, " YYYY-MM-DDThh:mm:ss[.nnnnnnnnn][Z|+-hh:mm]\n");
839 fprintf(output, " Unix epoch timestamps are also supported.\n");
840 fprintf(output, "\n");
841 fprintf(output, "Duplicate packet removal:\n");
842 fprintf(output, " --novlan remove vlan info from packets before checking for duplicates.\n");
843 fprintf(output, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH);
844 fprintf(output, " -D <dup window> remove packet if duplicate; configurable <dup window>.\n");
845 fprintf(output, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH);
846 fprintf(output, " NOTE: A <dup window> of 0 with -V (verbose option) is\n");
847 fprintf(output, " useful to print MD5 hashes.\n");
848 fprintf(output, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
849 fprintf(output, " LESS THAN <dup time window> prior to current packet.\n");
850 fprintf(output, " A <dup time window> is specified in relative seconds\n");
851 fprintf(output, " (e.g. 0.000001).\n");
852 fprintf(output, " NOTE: The use of the 'Duplicate packet removal' options with\n");
853 fprintf(output, " other editcap options except -V may not always work as expected.\n");
854 fprintf(output, " Specifically the -r, -t or -S options will very likely NOT have the\n");
855 fprintf(output, " desired effect if combined with the -d, -D or -w.\n");
856 fprintf(output, " --skip-radiotap-header skip radiotap header when checking for packet duplicates.\n");
857 fprintf(output, " Useful when processing packets captured by multiple radios\n");
858 fprintf(output, " on the same channel in the vicinity of each other.\n");
859 fprintf(output, " --set-unused set unused byts to zero in sll link addr.\n");
860 fprintf(output, "\n");
861 fprintf(output, "Packet manipulation:\n");
862 fprintf(output, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
863 fprintf(output, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
864 fprintf(output, " chop at the packet beginning, negative values at the\n");
865 fprintf(output, " packet end. If an optional offset precedes the length,\n");
866 fprintf(output, " then the bytes chopped will be offset from that value.\n");
867 fprintf(output, " Positive offsets are from the packet beginning,\n");
868 fprintf(output, " negative offsets are from the packet end. You can use\n");
869 fprintf(output, " this option more than once, allowing up to 2 chopping\n");
870 fprintf(output, " regions within a packet provided that at least 1\n");
871 fprintf(output, " choplen is positive and at least 1 is negative.\n");
872 fprintf(output, " -L adjust the frame (i.e. reported) length when chopping\n");
873 fprintf(output, " and/or snapping.\n");
874 fprintf(output, " -t <time adjustment> adjust the timestamp of each packet.\n");
875 fprintf(output, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
876 fprintf(output, " -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
877 fprintf(output, " strict chronological increasing order. The <strict\n");
878 fprintf(output, " adjustment> is specified in relative seconds with\n");
879 fprintf(output, " values of 0 or 0.000001 being the most reasonable.\n");
880 fprintf(output, " A negative adjustment value will modify timestamps so\n");
881 fprintf(output, " that each packet's delta time is the absolute value\n");
882 fprintf(output, " of the adjustment specified. A value of -0 will set\n");
883 fprintf(output, " all packets to the timestamp of the first packet.\n");
884 fprintf(output, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
885 fprintf(output, " a particular packet byte will be randomly changed.\n");
886 fprintf(output, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
887 fprintf(output, " beginning of the packet. This allows one to preserve some\n");
888 fprintf(output, " bytes, in order to have some headers untouched.\n");
889 fprintf(output, " --seed <seed> When used in conjunction with -E, set the seed to use for\n");
890 fprintf(output, " the pseudo-random number generator. This allows one to\n");
891 fprintf(output, " repeat a particular sequence of errors.\n");
892 fprintf(output, " -I <bytes to ignore> ignore the specified number of bytes at the beginning\n");
893 fprintf(output, " of the frame during MD5 hash calculation, unless the\n");
894 fprintf(output, " frame is too short, then the full frame is used.\n");
895 fprintf(output, " Useful to remove duplicated packets taken on\n");
896 fprintf(output, " several routers (different mac addresses for\n");
897 fprintf(output, " example).\n");
898 fprintf(output, " e.g. -I 26 in case of Ether/IP will ignore\n");
899 fprintf(output, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
900 fprintf(output, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
901 fprintf(output, "\n");
902 fprintf(output, "Output File(s):\n");
903 fprintf(output, " if the output file(s) have the .gz extension, then\n");
904 fprintf(output, " gzip compression will be used\n");
905 fprintf(output, " -c <packets per file> split the packet output to different files based on\n");
906 fprintf(output, " uniform packet counts with a maximum of\n");
907 fprintf(output, " <packets per file> each.\n");
908 fprintf(output, " -i <seconds per file> split the packet output to different files based on\n");
909 fprintf(output, " uniform time intervals with a maximum of\n");
910 fprintf(output, " <seconds per file> each.\n");
911 fprintf(output, " -F <capture type> set the output file type; default is pcapng.\n");
912 fprintf(output, " An empty \"-F\" option will list the file types.\n");
913 fprintf(output, " -T <encap type> set the output file encapsulation type; default is the\n");
914 fprintf(output, " same as the input file. An empty \"-T\" option will\n");
915 fprintf(output, " list the encapsulation types.\n");
916 fprintf(output, " --inject-secrets <type>,<file> Insert decryption secrets from <file>. List\n");
917 fprintf(output, " supported secret types with \"--inject-secrets help\".\n");
918 fprintf(output, " --extract-secrets Extract decryption secrets into the output file instead.\n");
919 fprintf(output, " Incompatible with other options besides -V.\n");
920 fprintf(output, " --discard-all-secrets Discard all decryption secrets from the input file\n");
921 fprintf(output, " when writing the output file. Does not discard\n");
922 fprintf(output, " secrets added by \"--inject-secrets\" in the same\n");
923 fprintf(output, " command line.\n");
924 fprintf(output, " --capture-comment <comment>\n");
925 fprintf(output, " Add a capture file comment, if supported.\n");
926 fprintf(output, " --discard-capture-comment\n");
927 fprintf(output, " Discard capture file comments from the input file\n");
928 fprintf(output, " when writing the output file. Does not discard\n");
929 fprintf(output, " comments added by \"--capture-comment\" in the same\n");
930 fprintf(output, " command line.\n");
931 fprintf(output, " --discard-packet-comments\n");
932 fprintf(output, " Discard all packet comments from the input file\n");
933 fprintf(output, " when writing the output file. Does not discard\n");
934 fprintf(output, " comments added by \"-a\" in the same command line.\n");
935 fprintf(output, " --compress <type> Compress the output file using the type compression format.\n");
936 fprintf(output, "\n");
937 fprintf(output, "Miscellaneous:\n");
938 fprintf(output, " -h, --help display this help and exit.\n");
939 fprintf(output, " -V verbose output.\n");
940 fprintf(output, " If -V is used with any of the 'Duplicate Packet\n");
941 fprintf(output, " Removal' options (-d, -D or -w) then Packet lengths\n");
942 fprintf(output, " and MD5 hashes are printed to standard-error.\n");
943 fprintf(output, " -v, --version print version information and exit.\n");
946 struct string_elem {
947 const char *sstr; /* The short string */
948 const char *lstr; /* The long string */
951 static int
952 string_nat_compare(const void *a, const void *b)
954 return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
955 ((const struct string_elem *)b)->sstr);
958 static void
959 string_elem_print(void *data, void *stream_ptr)
961 fprintf((FILE *) stream_ptr, " %s - %s\n",
962 ((struct string_elem *)data)->sstr,
963 ((struct string_elem *)data)->lstr);
966 static void
967 list_capture_types(FILE *stream) {
968 GArray *writable_type_subtypes;
970 fprintf(stream, "editcap: The available capture file types for the \"-F\" flag are:\n");
971 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
972 for (unsigned i = 0; i < writable_type_subtypes->len; i++) {
973 int ft = g_array_index(writable_type_subtypes, int, i);
974 fprintf(stream, " %s - %s\n", wtap_file_type_subtype_name(ft),
975 wtap_file_type_subtype_description(ft));
977 g_array_free(writable_type_subtypes, TRUE);
980 static void
981 list_encap_types(FILE *stream) {
982 int i;
983 struct string_elem *encaps;
984 GSList *list = NULL;
986 encaps = g_new(struct string_elem, WTAP_NUM_ENCAP_TYPES);
987 fprintf(stream, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
988 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
989 encaps[i].sstr = wtap_encap_name(i);
990 if (encaps[i].sstr != NULL) {
991 encaps[i].lstr = wtap_encap_description(i);
992 list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
995 g_slist_foreach(list, string_elem_print, stream);
996 g_slist_free(list);
997 g_free(encaps);
1000 static void
1001 list_output_compression_types(void) {
1002 GSList *output_compression_types;
1004 fprintf(stderr, "editcap: The available output compress type(s) for the \"--compress\" flag are:\n");
1005 output_compression_types = wtap_get_all_output_compression_type_names_list();
1006 for (GSList *compression_type = output_compression_types;
1007 compression_type != NULL;
1008 compression_type = g_slist_next(compression_type)) {
1009 fprintf(stderr, " %s\n", (const char *)compression_type->data);
1012 g_slist_free(output_compression_types);
1015 static void
1016 list_secrets_types(FILE *stream)
1018 for (unsigned i = 0; i < G_N_ELEMENTS(secrets_types); i++) {
1019 fprintf(stream, " %s\n", secrets_types[i].str);
1023 static uint32_t
1024 lookup_secrets_type(const char *type)
1026 for (unsigned i = 0; i < G_N_ELEMENTS(secrets_types); i++) {
1027 if (!strcmp(secrets_types[i].str, type)) {
1028 return secrets_types[i].id;
1031 return 0;
1034 static void
1035 validate_secrets_file(const char *filename, uint32_t secrets_type, const char *data)
1037 if (secrets_type == SECRETS_TYPE_TLS) {
1039 * A key log file is unlikely going to look like either:
1040 * - a PEM-encoded private key file.
1041 * - a BER-encoded PKCS #12 file ("PFX file"). (Look for a Constructed
1042 * SEQUENCE tag, e.g. bytes 0x30 which happens to be ASCII '0'.)
1044 if (g_str_has_prefix(data, "-----BEGIN ") || data[0] == 0x30) {
1045 fprintf(stderr,
1046 "editcap: Warning: \"%s\" is not a key log file, but an unsupported private key file. Decryption will not work.\n",
1047 filename);
1052 static int
1053 framenum_compare(const void *a, const void *b, void *user_data _U_)
1055 uint64_t *frame_a = (uint64_t*)a;
1056 uint64_t *frame_b = (uint64_t*)b;
1057 if (*frame_a < *frame_b)
1058 return -1;
1060 if (*frame_a > *frame_b)
1061 return 1;
1063 return 0;
1067 * Report an error in command-line arguments.
1069 static void
1070 editcap_cmdarg_err(const char *msg_format, va_list ap)
1072 fprintf(stderr, "editcap: ");
1073 vfprintf(stderr, msg_format, ap);
1074 fprintf(stderr, "\n");
1078 * Report additional information for an error in command-line arguments.
1080 static void
1081 editcap_cmdarg_err_cont(const char *msg_format, va_list ap)
1083 vfprintf(stderr, msg_format, ap);
1084 fprintf(stderr, "\n");
1087 static wtap_dumper *
1088 editcap_dump_open(const char *filename, const wtap_dump_params *params,
1089 GArray *idbs_seen, int *err, char **err_info,
1090 wtap_compression_type compression_type)
1092 wtap_dumper *pdh;
1094 if (strcmp(filename, "-") == 0) {
1095 /* Write to the standard output. */
1096 pdh = wtap_dump_open_stdout(out_file_type_subtype, compression_type,
1097 params, err, err_info);
1098 } else {
1099 pdh = wtap_dump_open(filename, out_file_type_subtype, compression_type,
1100 params, err, err_info);
1102 if (pdh == NULL)
1103 return NULL;
1106 * If the output file supports identifying the interfaces on which
1107 * packets arrive, add all the IDBs we've seen so far.
1109 * That mean that the abstract interface provided by libwiretap
1110 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1112 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh),
1113 WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
1114 for (unsigned i = 0; i < idbs_seen->len; i++) {
1115 wtap_block_t if_data = g_array_index(idbs_seen, wtap_block_t, i);
1116 wtap_block_t if_data_copy;
1119 * Make a copy of this IDB, so that we can change the
1120 * encapsulation type without trashing the original.
1122 if_data_copy = wtap_block_make_copy(if_data);
1125 * If an encapsulation type was specified, override the
1126 * encapsulation type of the interface.
1128 if (out_frame_type != -2) {
1129 wtapng_if_descr_mandatory_t *if_mand;
1131 if_mand = (wtapng_if_descr_mandatory_t *)wtap_block_get_mandatory_data(if_data_copy);
1132 if_mand->wtap_encap = out_frame_type;
1136 * Add this possibly-modified IDB to the file to which
1137 * we're currently writing.
1139 if (!wtap_dump_add_idb(pdh, if_data_copy, err, err_info)) {
1140 int close_err;
1141 char *close_err_info;
1143 wtap_dump_close(pdh, NULL, &close_err, &close_err_info);
1144 g_free(close_err_info);
1145 wtap_block_unref(if_data_copy);
1146 return NULL;
1150 * Release the copy - wtap_dump_add_idb() makes its own copy.
1152 wtap_block_unref(if_data_copy);
1156 return pdh;
1159 static bool
1160 process_new_idbs(wtap *wth, wtap_dumper *pdh, GArray *idbs_seen,
1161 int *err, char **err_info)
1163 wtap_block_t if_data;
1165 while ((if_data = wtap_get_next_interface_description(wth)) != NULL) {
1167 * Only add interface blocks if the output file supports (meaning
1168 * *requires*) them.
1170 * That mean that the abstract interface provided by libwiretap
1171 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1173 if (pdh != NULL && wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh),
1174 WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
1175 wtap_block_t if_data_copy;
1178 * Make a copy of this IDB, so that we can change the
1179 * encapsulation type without trashing the original.
1181 if_data_copy = wtap_block_make_copy(if_data);
1184 * If an encapsulation type was specified, override the
1185 * encapsulation type of the interface.
1187 if (out_frame_type != -2) {
1188 wtapng_if_descr_mandatory_t *if_mand;
1190 if_mand = (wtapng_if_descr_mandatory_t *)wtap_block_get_mandatory_data(if_data_copy);
1191 if_mand->wtap_encap = out_frame_type;
1195 * Add this possibly-modified IDB to the file to which
1196 * we're currently writing.
1198 if (!wtap_dump_add_idb(pdh, if_data_copy, err, err_info))
1199 return false;
1202 * Release the copy - wtap_dump_add_idb() makes its own copy.
1204 wtap_block_unref(if_data_copy);
1207 * Also add an unmodified copy to the set of IDBs we've seen,
1208 * in case we start writing to another file (which would be
1209 * of the same type as the current file, and thus will also
1210 * require interface IDs).
1212 if_data_copy = wtap_block_make_copy(if_data);
1213 g_array_append_val(idbs_seen, if_data_copy);
1216 return true;
1219 static int
1220 extract_secrets(wtap *wth, char* filename, int *err, char **err_info)
1222 wtap_rec read_rec;
1223 Buffer read_buf;
1224 int64_t offset;
1225 char *fprefix = NULL;
1226 char *fsuffix = NULL;
1228 /* Read all of the packets in turn */
1229 wtap_rec_init(&read_rec);
1230 ws_buffer_init(&read_buf, 1514);
1231 while (wtap_read(wth, &read_rec, &read_buf, err, err_info, &offset)) {
1232 /* Do we want to respect the max packet number on the command line?
1233 * Probably more confusing than it's worth, because a user might
1234 * not know if a DSB is at the end of the file.
1236 wtap_rec_reset(&read_rec);
1238 wtap_rec_cleanup(&read_rec);
1239 ws_buffer_free(&read_buf);
1241 wtapng_dsb_mandatory_t *dsb;
1242 if (strcmp(filename, "-") == 0) {
1243 /* Sure. Why not. */
1244 for (unsigned dsb_num = 0; dsb_num < wtap_file_get_num_dsbs(wth); ++dsb_num) {
1245 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth, dsb_num));
1246 if (verbose) {
1247 fprintf(stderr, "Writing secrets type \"%s\" (0x%08x) to standard out.\n",
1248 secrets_type_description(dsb->secrets_type), dsb->secrets_type);
1250 if (fwrite(dsb->secrets_data, 1, dsb->secrets_len, stdout) != dsb->secrets_len) {
1251 return WRITE_ERROR;
1254 } else if (wtap_file_get_num_dsbs(wth) == 1) {
1255 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth, 0));
1256 if (verbose) {
1257 fprintf(stderr, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1258 secrets_type_description(dsb->secrets_type), dsb->secrets_type,
1259 filename);
1261 if (!write_file_binary_mode(filename, dsb->secrets_data, dsb->secrets_len)) {
1262 return WRITE_ERROR;
1264 } else {
1265 /* We have more than one DSB, so write multiple files. While for some
1266 * types, we could combine the information from different DSBs togther
1267 * (and most of those are text-based, so we'd want to write in text
1268 * mode so that the line endings are uniform (which makes testing
1269 * harder), we don't know that for every type.
1271 if (!fileset_extract_prefix_suffix(filename, &fprefix, &fsuffix, NULL)) {
1272 return CANT_EXTRACT_PREFIX;
1274 char *extract_filename;
1275 for (unsigned dsb_num = 0; dsb_num < wtap_file_get_num_dsbs(wth); ++dsb_num) {
1276 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth, dsb_num));
1277 extract_filename = fileset_get_filename_by_pattern(dsb_num, NULL, fprefix, fsuffix);
1278 if (verbose) {
1279 fprintf(stderr, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1280 secrets_type_description(dsb->secrets_type), dsb->secrets_type,
1281 extract_filename);
1283 if (!write_file_binary_mode(extract_filename, dsb->secrets_data, dsb->secrets_len)) {
1284 /* write_file_binary_mode already reports failures */
1285 g_free(extract_filename);
1286 g_free(fprefix);
1287 g_free(fsuffix);
1289 return WRITE_ERROR;
1291 g_free(extract_filename);
1293 g_free(fprefix);
1294 g_free(fsuffix);
1296 return EXIT_SUCCESS;
1300 main(int argc, char *argv[])
1302 char *configuration_init_error;
1303 wtap *wth = NULL;
1304 int i, j, read_err, write_err;
1305 char *read_err_info, *write_err_info;
1306 int opt;
1308 #define LONGOPT_NO_VLAN LONGOPT_BASE_APPLICATION+1
1309 #define LONGOPT_SKIP_RADIOTAP_HEADER LONGOPT_BASE_APPLICATION+2
1310 #define LONGOPT_SEED LONGOPT_BASE_APPLICATION+3
1311 #define LONGOPT_INJECT_SECRETS LONGOPT_BASE_APPLICATION+4
1312 #define LONGOPT_DISCARD_ALL_SECRETS LONGOPT_BASE_APPLICATION+5
1313 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
1314 #define LONGOPT_DISCARD_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+7
1315 #define LONGOPT_SET_UNUSED LONGOPT_BASE_APPLICATION+8
1316 #define LONGOPT_DISCARD_PACKET_COMMENTS LONGOPT_BASE_APPLICATION+9
1317 #define LONGOPT_EXTRACT_SECRETS LONGOPT_BASE_APPLICATION+10
1318 #define LONGOPT_COMPRESS LONGOPT_BASE_APPLICATION+11
1320 static const struct ws_option long_options[] = {
1321 {"novlan", ws_no_argument, NULL, LONGOPT_NO_VLAN},
1322 {"skip-radiotap-header", ws_no_argument, NULL, LONGOPT_SKIP_RADIOTAP_HEADER},
1323 {"seed", ws_required_argument, NULL, LONGOPT_SEED},
1324 {"inject-secrets", ws_required_argument, NULL, LONGOPT_INJECT_SECRETS},
1325 {"discard-all-secrets", ws_no_argument, NULL, LONGOPT_DISCARD_ALL_SECRETS},
1326 {"help", ws_no_argument, NULL, 'h'},
1327 {"version", ws_no_argument, NULL, 'v'},
1328 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
1329 {"discard-capture-comment", ws_no_argument, NULL, LONGOPT_DISCARD_CAPTURE_COMMENT},
1330 {"set-unused", ws_no_argument, NULL, LONGOPT_SET_UNUSED},
1331 {"discard-packet-comments", ws_no_argument, NULL, LONGOPT_DISCARD_PACKET_COMMENTS},
1332 {"extract-secrets", ws_no_argument, NULL, LONGOPT_EXTRACT_SECRETS},
1333 {"compress", ws_required_argument, NULL, LONGOPT_COMPRESS},
1334 {0, 0, 0, 0 }
1337 char *p;
1338 uint32_t snaplen = 0; /* No limit */
1339 chop_t chop = {0, 0, 0, 0, 0, 0}; /* No chop */
1340 bool adjlen = false;
1341 wtap_dumper *pdh = NULL;
1342 GArray *idbs_seen = NULL;
1343 uint64_t count = 1;
1344 uint64_t duplicate_count = 0;
1345 int64_t data_offset;
1346 int err_type;
1347 uint8_t *buf;
1348 uint64_t read_count = 0;
1349 uint64_t split_packet_count = 0;
1350 uint64_t written_count = 0;
1351 char *filename = NULL;
1352 bool ts_okay;
1353 nstime_t secs_per_block = NSTIME_INIT_UNSET;
1354 int block_cnt = 0;
1355 nstime_t block_next = NSTIME_INIT_UNSET;
1356 char *fprefix = NULL;
1357 char *fsuffix = NULL;
1358 uint32_t change_offset = 0;
1359 uint64_t max_packet_number = 0;
1360 GArray *dsb_types = NULL;
1361 GPtrArray *dsb_filenames = NULL;
1362 wtap_rec read_rec;
1363 Buffer read_buf;
1364 const wtap_rec *rec;
1365 wtap_rec temp_rec;
1366 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
1367 char *shb_user_appl;
1368 bool do_mutation;
1369 uint32_t caplen;
1370 int ret = EXIT_SUCCESS;
1371 bool valid_seed = false;
1372 unsigned int seed = 0;
1373 bool edit_option_specified = false;
1374 wtap_compression_type compression_type = WTAP_UNKNOWN_COMPRESSION;
1376 cmdarg_err_init(editcap_cmdarg_err, editcap_cmdarg_err_cont);
1377 memset(&read_rec, 0, sizeof *rec);
1379 /* Initialize log handler early so we can have proper logging during startup. */
1380 ws_log_init("editcap", vcmdarg_err);
1382 /* Early logging command-line initialization. */
1383 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
1385 ws_noisy("Finished log init and parsing command line log arguments");
1387 #ifdef _WIN32
1388 create_app_running_mutex();
1389 #endif /* _WIN32 */
1391 /* Initialize the version information. */
1392 ws_init_version_info("Editcap", NULL, NULL);
1395 * Get credential information for later use.
1397 init_process_policies();
1400 * Attempt to get the pathname of the directory containing the
1401 * executable file.
1403 configuration_init_error = configuration_init(argv[0], NULL);
1404 if (configuration_init_error != NULL) {
1405 cmdarg_err("Can't get pathname of directory containing the editcap program: %s.",
1406 configuration_init_error);
1407 g_free(configuration_init_error);
1410 init_report_failure_message("editcap");
1412 wtap_init(true);
1414 /* Process the options */
1415 while ((opt = ws_getopt_long(argc, argv, "a:A:B:c:C:dD:E:F:hi:I:Lo:rs:S:t:T:vVw:", long_options, NULL)) != -1) {
1416 if (opt != LONGOPT_EXTRACT_SECRETS && opt != 'V') {
1417 edit_option_specified = true;
1419 switch (opt) {
1420 case LONGOPT_NO_VLAN:
1422 rem_vlan = true;
1423 break;
1426 case LONGOPT_SKIP_RADIOTAP_HEADER:
1428 skip_radiotap = true;
1429 break;
1432 case LONGOPT_SEED:
1434 if (sscanf(ws_optarg, "%u", &seed) != 1) {
1435 cmdarg_err("\"%s\" isn't a valid seed", ws_optarg);
1436 ret = WS_EXIT_INVALID_OPTION;
1437 goto clean_exit;
1439 valid_seed = true;
1440 break;
1443 case LONGOPT_INJECT_SECRETS:
1445 uint32_t secrets_type_id = 0;
1446 const char *secrets_filename = NULL;
1447 if (strcmp("help", ws_optarg) == 0) {
1448 list_secrets_types(stdout);
1449 goto clean_exit;
1451 char **splitted = g_strsplit(ws_optarg, ",", 2);
1452 if (splitted[0] && splitted[0][0] != '\0') {
1453 secrets_type_id = lookup_secrets_type(splitted[0]);
1454 if (secrets_type_id == 0) {
1455 cmdarg_err("\"%s\" isn't a valid secrets type", splitted[0]);
1456 g_strfreev(splitted);
1457 ret = WS_EXIT_INVALID_OPTION;
1458 goto clean_exit;
1460 secrets_filename = splitted[1];
1461 } else {
1462 cmdarg_err("no secrets type was specified for --inject-secrets");
1463 g_strfreev(splitted);
1464 ret = WS_EXIT_INVALID_OPTION;
1465 goto clean_exit;
1467 if (!dsb_filenames) {
1468 dsb_types = g_array_new(FALSE, FALSE, sizeof(uint32_t));
1469 dsb_filenames = g_ptr_array_new_with_free_func(g_free);
1471 g_array_append_val(dsb_types, secrets_type_id);
1472 g_ptr_array_add(dsb_filenames, g_strdup(secrets_filename));
1473 g_strfreev(splitted);
1474 break;
1477 case LONGOPT_DISCARD_ALL_SECRETS:
1479 discard_all_secrets = true;
1480 break;
1483 case LONGOPT_CAPTURE_COMMENT:
1486 * Make sure this would fit in a pcapng option.
1488 * XXX - 65535 is the maximum size for an option in pcapng;
1489 * what if another capture file format supports larger
1490 * comments?
1492 if (strlen(ws_optarg) > 65535) {
1493 /* It doesn't fit. Tell the user and give up. */
1494 cmdarg_err("Capture comment %u is too large to save in a capture file.",
1495 capture_comments->len + 1);
1496 ret = WS_EXIT_INVALID_OPTION;
1497 goto clean_exit;
1500 /* pcapng supports multiple comments, so support them here too.
1502 if (!capture_comments) {
1503 capture_comments = g_ptr_array_new_with_free_func(g_free);
1505 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
1506 break;
1509 case LONGOPT_DISCARD_CAPTURE_COMMENT:
1511 discard_cap_comments = true;
1512 break;
1515 case LONGOPT_SET_UNUSED:
1517 set_unused = true;
1518 break;
1521 case LONGOPT_DISCARD_PACKET_COMMENTS:
1523 discard_pkt_comments = true;
1524 break;
1527 case LONGOPT_EXTRACT_SECRETS:
1529 do_extract_secrets = true;
1530 /* XXX - Would it make sense to specify what types of secrets
1531 * to extract (or any)?
1533 break;
1536 case LONGOPT_COMPRESS:
1538 compression_type = wtap_name_to_compression_type(ws_optarg);
1539 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
1540 cmdarg_err("\"%s\" isn't a valid output compression mode",
1541 ws_optarg);
1542 list_output_compression_types();
1543 goto clean_exit;
1545 break;
1548 case 'a':
1550 uint64_t frame_number;
1551 int string_start_index = 0;
1553 if ((sscanf(ws_optarg, "%" SCNu64 ":%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1554 cmdarg_err("\"%s\" isn't a valid <frame>:<comment>", ws_optarg);
1555 ret = WS_EXIT_INVALID_OPTION;
1556 goto clean_exit;
1560 * Make sure this would fit in a pcapng option.
1562 * XXX - 65535 is the maximum size for an option in pcapng;
1563 * what if another capture file format supports larger
1564 * comments?
1566 if (strlen(ws_optarg+string_start_index) > 65535) {
1567 /* It doesn't fit. Tell the user and give up. */
1568 cmdarg_err("A comment for frame %" PRIu64 " is too large to save in a capture file.",
1569 frame_number);
1570 ret = WS_EXIT_INVALID_OPTION;
1571 goto clean_exit;
1574 /* Lazily create the table */
1575 if (!frames_user_comments) {
1576 frames_user_comments = g_tree_new_full(framenum_compare, NULL, g_free, g_free);
1579 /* Insert this entry (framenum -> comment) */
1580 uint64_t *frame_p = g_new(uint64_t, 1);
1581 *frame_p = frame_number;
1582 g_tree_replace(frames_user_comments, frame_p, g_strdup(ws_optarg+string_start_index));
1583 break;
1586 case 'A':
1587 case 'B':
1589 nstime_t in_time;
1591 check_startstop = true;
1592 if ((NULL != iso8601_to_nstime(&in_time, ws_optarg, ISO8601_DATETIME)) || (NULL != unix_epoch_to_nstime(&in_time, ws_optarg))) {
1593 if (opt == 'A') {
1594 nstime_copy(&starttime, &in_time);
1595 have_starttime = true;
1596 } else {
1597 nstime_copy(&stoptime, &in_time);
1598 have_stoptime = true;
1600 break;
1602 else {
1603 cmdarg_err("\"%s\" isn't a valid date and time", ws_optarg);
1604 ret = WS_EXIT_INVALID_OPTION;
1605 goto clean_exit;
1609 case 'c':
1610 split_packet_count = get_nonzero_uint64(ws_optarg, "packet count");
1611 break;
1613 case 'C':
1615 int choplen = 0, chopoff = 0;
1617 switch (sscanf(ws_optarg, "%d:%d", &chopoff, &choplen)) {
1618 case 1: /* only the chop length was specified */
1619 choplen = chopoff;
1620 chopoff = 0;
1621 break;
1623 case 2: /* both an offset and chop length was specified */
1624 break;
1626 default:
1627 cmdarg_err("\"%s\" isn't a valid chop length or offset:length", ws_optarg);
1628 ret = WS_EXIT_INVALID_OPTION;
1629 goto clean_exit;
1630 break;
1633 if (choplen > 0) {
1634 chop.len_begin += choplen;
1635 if (chopoff > 0)
1636 chop.off_begin_pos += chopoff;
1637 else
1638 chop.off_begin_neg += chopoff;
1639 } else if (choplen < 0) {
1640 chop.len_end += choplen;
1641 if (chopoff > 0)
1642 chop.off_end_pos += chopoff;
1643 else
1644 chop.off_end_neg += chopoff;
1646 break;
1649 case 'd':
1650 dup_detect = true;
1651 dup_detect_by_time = false;
1652 dup_window = DEFAULT_DUP_DEPTH;
1653 break;
1655 case 'D':
1656 dup_detect = true;
1657 dup_detect_by_time = false;
1658 dup_window = get_uint32(ws_optarg, "duplicate window");
1659 if (dup_window > MAX_DUP_DEPTH) {
1660 cmdarg_err("\"%d\" duplicate window value must be between 0 and %d inclusive.",
1661 dup_window, MAX_DUP_DEPTH);
1662 ret = WS_EXIT_INVALID_OPTION;
1663 goto clean_exit;
1665 break;
1667 case 'E':
1668 err_prob = g_ascii_strtod(ws_optarg, &p);
1669 if (p == ws_optarg || err_prob < 0.0 || err_prob > 1.0) {
1670 cmdarg_err("probability \"%s\" must be between 0.0 and 1.0", ws_optarg);
1671 ret = WS_EXIT_INVALID_OPTION;
1672 goto clean_exit;
1674 break;
1676 case 'F':
1677 out_file_type_subtype = wtap_name_to_file_type_subtype(ws_optarg);
1678 if (out_file_type_subtype < 0) {
1679 cmdarg_err("\"%s\" isn't a valid capture file type\n", ws_optarg);
1680 list_capture_types(stderr);
1681 ret = WS_EXIT_INVALID_OPTION;
1682 goto clean_exit;
1684 break;
1686 case 'h':
1687 show_help_header("Edit and/or translate the format of capture files.");
1688 print_usage(stdout);
1689 goto clean_exit;
1690 break;
1692 case 'i': /* break capture file based on time interval */
1694 double spb = get_positive_double(ws_optarg, "time interval");
1695 if (spb == 0.0) {
1696 cmdarg_err("The specified interval is zero");
1697 ret = WS_EXIT_INVALID_OPTION;
1698 goto clean_exit;
1701 double spb_int, spb_frac;
1702 spb_frac = modf(spb, &spb_int);
1703 secs_per_block.secs = (time_t) spb_int;
1704 secs_per_block.nsecs = (int) (NANOSECS_PER_SEC * spb_frac);
1706 break;
1708 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1709 ignored_bytes = get_uint32(ws_optarg, "number of bytes to ignore");
1710 break;
1712 case 'L':
1713 adjlen = true;
1714 break;
1716 case 'o':
1717 change_offset = get_uint32(ws_optarg, "change offset");
1718 break;
1720 case 'r':
1721 if (keep_em) {
1722 cmdarg_err("-r was specified twice");
1723 ret = WS_EXIT_INVALID_OPTION;
1724 goto clean_exit;
1726 keep_em = true;
1727 break;
1729 case 's':
1730 snaplen = get_nonzero_uint32(ws_optarg, "snapshot length");
1731 break;
1733 case 'S':
1734 if (!set_strict_time_adj(ws_optarg)) {
1735 ret = WS_EXIT_INVALID_OPTION;
1736 goto clean_exit;
1738 do_strict_time_adjustment = true;
1739 break;
1741 case 't':
1742 if (!set_time_adjustment(ws_optarg)) {
1743 ret = WS_EXIT_INVALID_OPTION;
1744 goto clean_exit;
1746 break;
1748 case 'T':
1749 out_frame_type = wtap_name_to_encap(ws_optarg);
1750 if (out_frame_type < 0) {
1751 cmdarg_err("\"%s\" isn't a valid encapsulation type\n", ws_optarg);
1752 list_encap_types(stderr);
1753 ret = WS_EXIT_INVALID_OPTION;
1754 goto clean_exit;
1756 break;
1758 case 'V':
1759 if (verbose) {
1760 cmdarg_err("-V was specified twice");
1761 ret = WS_EXIT_INVALID_OPTION;
1762 goto clean_exit;
1764 verbose = true;
1765 break;
1767 case 'v':
1768 show_version();
1769 goto clean_exit;
1770 break;
1772 case 'w':
1773 dup_detect = false;
1774 dup_detect_by_time = true;
1775 dup_window = MAX_DUP_DEPTH;
1776 if (!set_rel_time(ws_optarg)) {
1777 ret = WS_EXIT_INVALID_OPTION;
1778 goto clean_exit;
1780 break;
1782 case '?': /* Bad options - print usage */
1783 default:
1784 switch(ws_optopt) {
1785 case'F':
1786 list_capture_types(stdout);
1787 break;
1788 case'T':
1789 list_encap_types(stdout);
1790 break;
1791 case LONGOPT_COMPRESS:
1792 list_output_compression_types();
1793 break;
1794 default:
1795 print_usage(stderr);
1796 ret = WS_EXIT_INVALID_OPTION;
1797 break;
1799 goto clean_exit;
1800 break;
1802 } /* processing command-line options */
1804 #ifdef DEBUG
1805 fprintf(stderr, "Optind = %i, argc = %i\n", ws_optind, argc);
1806 #endif
1808 if ((argc - ws_optind) < 2) {
1809 print_usage(stderr);
1810 ret = WS_EXIT_INVALID_OPTION;
1811 goto clean_exit;
1814 if (out_file_type_subtype == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN) {
1815 /* default to pcapng */
1816 out_file_type_subtype = wtap_pcapng_file_type_subtype();
1819 if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
1820 if (!fileset_extract_prefix_suffix(argv[ws_optind+1], &fprefix, &fsuffix, &compression_type)) {
1821 ret = CANT_EXTRACT_PREFIX;
1822 goto clean_exit;
1824 } else if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
1825 /* An explicitly specified compression type overrides filename
1826 * magic. (Should we allow specifying "no" compression with, e.g.
1827 * a ".gz" extension?) */
1828 const char *sfx = strrchr(argv[ws_optind+1], '.');
1829 if (sfx) {
1830 compression_type = wtap_extension_to_compression_type(sfx + 1);
1834 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
1835 compression_type = WTAP_UNCOMPRESSED;
1838 if (!wtap_can_write_compression_type(compression_type)) {
1839 cmdarg_err("Output files can't be written as %s",
1840 wtap_compression_type_description(compression_type));
1841 ret = WS_EXIT_INVALID_OPTION;
1842 goto clean_exit;
1845 if (compression_type != WTAP_UNCOMPRESSED && !wtap_dump_can_compress(out_file_type_subtype)) {
1846 cmdarg_err("The file format %s can't be written to output compressed format",
1847 wtap_file_type_subtype_name(out_file_type_subtype));
1848 ret = WS_EXIT_INVALID_OPTION;
1849 goto clean_exit;
1852 if (err_prob >= 0.0) {
1853 if (!valid_seed) {
1854 seed = (unsigned int) (time(NULL) + ws_getpid());
1856 if (verbose) {
1857 fprintf(stderr, "Using seed %u\n", seed);
1859 srand(seed);
1862 if (have_starttime && have_stoptime &&
1863 nstime_cmp(&starttime, &stoptime) > 0) {
1864 cmdarg_err("start time is after the stop time");
1865 ret = WS_EXIT_INVALID_OPTION;
1866 goto clean_exit;
1869 if (split_packet_count != 0 && !nstime_is_unset(&secs_per_block)) {
1870 cmdarg_err("can't split on both packet count and time interval");
1871 cmdarg_err_cont("at the same time");
1872 ret = WS_EXIT_INVALID_OPTION;
1873 goto clean_exit;
1876 wth = wtap_open_offline(argv[ws_optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, false);
1878 if (!wth) {
1879 cfile_open_failure_message(argv[ws_optind], read_err, read_err_info);
1880 ret = WS_EXIT_INVALID_FILE;
1881 goto clean_exit;
1884 if (verbose) {
1885 fprintf(stderr, "File %s is a %s capture file.\n", argv[ws_optind],
1886 wtap_file_type_subtype_description(wtap_file_type_subtype(wth)));
1889 if (skip_radiotap) {
1890 if (ignored_bytes != 0) {
1891 cmdarg_err("can't skip radiotap headers and %d byte(s)", ignored_bytes);
1892 cmdarg_err_cont("at the start of packet at the same time");
1893 ret = WS_EXIT_INVALID_OPTION;
1894 goto clean_exit;
1897 if (wtap_file_encap(wth) != WTAP_ENCAP_IEEE_802_11_RADIOTAP) {
1898 cmdarg_err("can't skip radiotap header because input file has non-radiotap packets");
1899 if (wtap_file_encap(wth) == WTAP_ENCAP_PER_PACKET) {
1900 cmdarg_err_cont("expected '%s', not all packets are necessarily that type",
1901 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP));
1902 } else {
1903 cmdarg_err_cont("expected '%s', packets are '%s'",
1904 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP),
1905 wtap_encap_description(wtap_file_encap(wth)));
1907 ret = WS_EXIT_INVALID_OPTION;
1908 goto clean_exit;
1912 if (do_extract_secrets) {
1913 if (edit_option_specified) {
1914 cmdarg_err("can't extract secrets and use other options at the same time");
1915 ret = WS_EXIT_INVALID_OPTION;
1916 goto clean_exit;
1918 if (compression_type != WTAP_UNCOMPRESSED) {
1919 cmdarg_err("compression isn't supported for extracting secrets");
1920 ret = WS_EXIT_INVALID_OPTION;
1921 goto clean_exit;
1923 ret = extract_secrets(wth, argv[ws_optind+1], &read_err, &read_err_info);
1925 if (read_err != 0) {
1926 /* Print a message noting that the read failed somewhere along the
1927 * line. */
1928 cfile_read_failure_message(argv[ws_optind], read_err, read_err_info);
1930 goto clean_exit;
1933 wtap_dump_params_init_no_idbs(&params, wth);
1936 * Discard any secrets we read in while opening the file.
1938 if (discard_all_secrets) {
1939 wtap_dump_params_discard_decryption_secrets(&params);
1943 * Discard capture file comments.
1945 if (discard_cap_comments) {
1946 for (unsigned b = 0; b < params.shb_hdrs->len; b++) {
1947 wtap_block_t shb = g_array_index(params.shb_hdrs, wtap_block_t, b);
1948 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(shb, OPT_COMMENT, 0)) {
1949 continue;
1955 * Add new capture file comments.
1957 if (capture_comments != NULL) {
1958 for (unsigned b = 0; b < params.shb_hdrs->len; b++) {
1959 wtap_block_t shb = g_array_index(params.shb_hdrs, wtap_block_t, b);
1960 for (unsigned c = 0; c < capture_comments->len; c++) {
1961 char *comment = (char *)g_ptr_array_index(capture_comments, c);
1962 wtap_block_add_string_option(shb, OPT_COMMENT, comment, strlen(comment));
1967 if (dsb_filenames) {
1968 for (unsigned k = 0; k < dsb_filenames->len; k++) {
1969 uint32_t secrets_type_id = g_array_index(dsb_types, uint32_t, k);
1970 const char *secrets_filename = (const char *)g_ptr_array_index(dsb_filenames, k);
1971 char *data;
1972 size_t data_len;
1973 wtap_block_t block;
1974 wtapng_dsb_mandatory_t *dsb;
1975 GError *err = NULL;
1977 if (!g_file_get_contents(secrets_filename, &data, &data_len, &err)) {
1978 cmdarg_err("\"%s\" could not be read: %s", secrets_filename, err->message);
1979 g_clear_error(&err);
1980 ret = WS_EXIT_INVALID_OPTION;
1981 goto clean_exit;
1983 if (data_len == 0) {
1984 cmdarg_err("\"%s\" is an empty file, ignoring", secrets_filename);
1985 g_free(data);
1986 continue;
1988 if (data_len >= INT_MAX) {
1989 cmdarg_err("\"%s\" is too large, ignoring", secrets_filename);
1990 g_free(data);
1991 continue;
1994 /* Warn for badly formatted files, but proceed anyway. */
1995 validate_secrets_file(secrets_filename, secrets_type_id, data);
1997 block = wtap_block_create(WTAP_BLOCK_DECRYPTION_SECRETS);
1998 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(block);
1999 dsb->secrets_type = secrets_type_id;
2000 dsb->secrets_len = (unsigned)data_len;
2001 dsb->secrets_data = data;
2002 if (params.dsbs_initial == NULL) {
2003 params.dsbs_initial = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
2005 g_array_append_val(params.dsbs_initial, block);
2010 * If an encapsulation type was specified, override the encapsulation
2011 * type of the input file.
2013 if (out_frame_type != -2)
2014 params.encap = out_frame_type;
2017 * If a snapshot length was specified, and it's less than the snapshot
2018 * length of the input file, override the snapshot length of the input
2019 * file.
2021 if (snaplen != 0 && snaplen < wtap_snapshot_length(wth))
2022 params.snaplen = snaplen;
2025 * Now process the arguments following the input and output file
2026 * names, if any; they specify packets to include/exclude.
2028 for (i = ws_optind + 2; i < argc; i++)
2029 if (add_selection(argv[i], &max_packet_number) == false)
2030 break;
2032 if (keep_em && max_selected == 0) {
2033 cmdarg_err("must specify packets to keep when using -r");
2034 ret = WS_EXIT_INVALID_OPTION;
2035 goto clean_exit;
2038 if (!keep_em)
2039 max_packet_number = UINT64_MAX;
2041 if (dup_detect || dup_detect_by_time) {
2042 for (i = 0; i < dup_window; i++) {
2043 memset(&fd_hash[i].digest, 0, 16);
2044 fd_hash[i].len = 0;
2045 nstime_set_unset(&fd_hash[i].frame_time);
2049 /* Set up an array of all IDBs seen */
2050 idbs_seen = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
2052 /* Read all of the packets in turn */
2053 wtap_rec_init(&read_rec);
2054 ws_buffer_init(&read_buf, 1514);
2055 while (wtap_read(wth, &read_rec, &read_buf, &read_err, &read_err_info, &data_offset)) {
2057 * XXX - what about non-packet records in the file after this?
2058 * NRBs, DSBs, and ISBs are now written when wtap_dump_close() calls
2059 * pcapng_dump_finish(), and we handle IDBs below, but what about
2060 * custom blocks?
2062 if (max_packet_number <= read_count)
2063 break;
2065 read_count++;
2067 rec = &read_rec;
2069 /* Extra actions for the first packet */
2070 if (read_count == 1) {
2071 if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
2072 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
2073 } else {
2074 filename = g_strdup(argv[ws_optind+1]);
2076 ws_assert(filename);
2078 /* If we don't have an application name add one */
2079 if (wtap_block_get_string_option_value(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, &shb_user_appl) != WTAP_OPTTYPE_SUCCESS) {
2080 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
2083 pdh = editcap_dump_open(filename, &params, idbs_seen, &write_err,
2084 &write_err_info, compression_type);
2086 if (pdh == NULL) {
2087 cfile_dump_open_failure_message(filename,
2088 write_err, write_err_info,
2089 out_file_type_subtype);
2090 ret = WS_EXIT_INVALID_FILE;
2091 goto clean_exit;
2093 } /* first packet only handling */
2096 * Process whatever IDBs we haven't seen yet.
2098 if (!process_new_idbs(wth, pdh, idbs_seen, &write_err, &write_err_info)) {
2099 cfile_write_failure_message(argv[ws_optind], filename,
2100 write_err, write_err_info,
2101 read_count,
2102 out_file_type_subtype);
2103 ret = DUMP_ERROR;
2106 * Close the dump file, but don't report an error
2107 * or set the exit code, as we've already reported
2108 * an error.
2110 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2111 goto clean_exit;
2114 buf = ws_buffer_start_ptr(&read_buf);
2117 * Not all packets have time stamps. Only process the time
2118 * stamp if we have one.
2120 if (rec->presence_flags & WTAP_HAS_TS) {
2121 if (!nstime_is_unset(&secs_per_block)) {
2122 if (nstime_is_unset(&block_next)) {
2123 block_next = rec->ts;
2124 nstime_add(&block_next, &secs_per_block);
2126 while (nstime_cmp(&rec->ts, &block_next) > 0) { /* time for the next file */
2128 /* We presumably want to write the DSBs from files given
2129 * on the command line to every file.
2131 wtap_block_array_ref(params.dsbs_initial);
2132 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2133 cfile_close_failure_message(filename, write_err,
2134 write_err_info);
2135 ret = WRITE_ERROR;
2136 goto clean_exit;
2138 g_free(filename);
2139 /* Use the interval start time for the filename. */
2140 temp_rec = *rec;
2141 temp_rec.ts = block_next;
2142 filename = fileset_get_filename_by_pattern(block_cnt++, &temp_rec, fprefix, fsuffix);
2143 ws_assert(filename);
2144 nstime_add(&block_next, &secs_per_block); /* reset for next interval */
2146 if (verbose)
2147 fprintf(stderr, "Continuing writing in file %s\n", filename);
2149 pdh = editcap_dump_open(filename, &params, idbs_seen,
2150 &write_err, &write_err_info, compression_type);
2152 if (pdh == NULL) {
2153 cfile_dump_open_failure_message(filename,
2154 write_err,
2155 write_err_info,
2156 out_file_type_subtype);
2157 ret = WS_EXIT_INVALID_FILE;
2158 goto clean_exit;
2162 } /* time stamp handling */
2164 if (split_packet_count != 0) {
2165 /* time for the next file? */
2166 if (written_count > 0 && (written_count % split_packet_count) == 0) {
2168 /* We presumably want to write the DSBs from files given
2169 * on the command line to every file.
2171 wtap_block_array_ref(params.dsbs_initial);
2172 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2173 cfile_close_failure_message(filename, write_err,
2174 write_err_info);
2175 ret = WRITE_ERROR;
2176 goto clean_exit;
2179 g_free(filename);
2180 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
2181 ws_assert(filename);
2183 if (verbose)
2184 fprintf(stderr, "Continuing writing in file %s\n", filename);
2186 pdh = editcap_dump_open(filename, &params, idbs_seen,
2187 &write_err, &write_err_info, compression_type);
2188 if (pdh == NULL) {
2189 cfile_dump_open_failure_message(filename,
2190 write_err, write_err_info,
2191 out_file_type_subtype);
2192 ret = WS_EXIT_INVALID_FILE;
2193 goto clean_exit;
2196 } /* split packet handling */
2198 if (check_startstop) {
2199 ts_okay = false;
2201 * Is the packet in the selected timeframe?
2202 * If the packet has no time stamp, the answer is "no".
2204 if (rec->presence_flags & WTAP_HAS_TS) {
2205 if (have_starttime && have_stoptime) {
2206 ts_okay = nstime_cmp(&rec->ts, &starttime) >= 0 &&
2207 nstime_cmp(&rec->ts, &stoptime) < 0;
2208 } else if (have_starttime) {
2209 ts_okay = nstime_cmp(&rec->ts, &starttime) >= 0;
2210 } else if (have_stoptime) {
2211 ts_okay = nstime_cmp(&rec->ts, &stoptime) < 0;
2214 } else {
2216 * No selected timeframe, so all packets are "in the
2217 * selected timeframe".
2219 ts_okay = true;
2222 if (ts_okay && ((!selected(count) && !keep_em)
2223 || (selected(count) && keep_em))) {
2225 if (verbose && !dup_detect && !dup_detect_by_time)
2226 fprintf(stderr, "Packet: %" PRIu64 "\n", count);
2228 /* We simply write it, perhaps after truncating it; we could
2229 * do other things, like modify it. */
2231 rec = &read_rec;
2233 if (rec->presence_flags & WTAP_HAS_TS) {
2234 /* Do we adjust timestamps to ensure strict chronological
2235 * order? */
2236 if (do_strict_time_adjustment) {
2237 if (previous_time.secs || previous_time.nsecs) {
2238 if (!strict_time_adj.is_negative) {
2239 nstime_t current;
2240 nstime_t delta;
2242 current = rec->ts;
2244 nstime_delta(&delta, &current, &previous_time);
2246 if (delta.secs < 0 || delta.nsecs < 0) {
2248 * A negative delta indicates that the current packet
2249 * has an absolute timestamp less than the previous packet
2250 * that it is being compared to. This is NOT a normal
2251 * situation since trace files usually have packets in
2252 * chronological order (oldest to newest).
2253 * Copy and change rather than modify
2254 * returned rec.
2256 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
2257 temp_rec = *rec;
2258 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
2259 temp_rec.ts.nsecs = previous_time.nsecs;
2260 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
2261 /* carry */
2262 temp_rec.ts.secs++;
2263 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2264 } else {
2265 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
2267 rec = &temp_rec;
2269 } else {
2271 * A negative strict time adjustment is requested.
2272 * Unconditionally set each timestamp to previous
2273 * packet's timestamp plus delta.
2274 * Copy and change rather than modify returned
2275 * rec.
2277 temp_rec = *rec;
2278 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
2279 temp_rec.ts.nsecs = previous_time.nsecs;
2280 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
2281 /* carry */
2282 temp_rec.ts.secs++;
2283 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2284 } else {
2285 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
2287 rec = &temp_rec;
2290 previous_time = rec->ts;
2293 if (time_adj.tv.secs != 0) {
2294 /* Copy and change rather than modify returned rec */
2295 temp_rec = *rec;
2296 if (time_adj.is_negative)
2297 temp_rec.ts.secs -= time_adj.tv.secs;
2298 else
2299 temp_rec.ts.secs += time_adj.tv.secs;
2300 rec = &temp_rec;
2303 if (time_adj.tv.nsecs != 0) {
2304 /* Copy and change rather than modify returned rec */
2305 temp_rec = *rec;
2306 if (time_adj.is_negative) { /* subtract */
2307 if (temp_rec.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
2308 temp_rec.ts.secs--;
2309 temp_rec.ts.nsecs += ONE_BILLION;
2311 temp_rec.ts.nsecs -= time_adj.tv.nsecs;
2312 } else { /* add */
2313 if (temp_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
2314 /* carry */
2315 temp_rec.ts.secs++;
2316 temp_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
2317 } else {
2318 temp_rec.ts.nsecs += time_adj.tv.nsecs;
2321 rec = &temp_rec;
2323 } /* time stamp adjustment */
2325 if (rec->rec_type == REC_TYPE_PACKET) {
2326 if (snaplen != 0) {
2327 /* Limit capture length to snaplen */
2328 if (rec->rec_header.packet_header.caplen > snaplen) {
2329 /* Copy and change rather than modify returned rec */
2330 temp_rec = *rec;
2331 temp_rec.rec_header.packet_header.caplen = snaplen;
2332 rec = &temp_rec;
2334 /* If -L, also set reported length to snaplen */
2335 if (adjlen && rec->rec_header.packet_header.len > snaplen) {
2336 /* Copy and change rather than modify returned rec */
2337 temp_rec = *rec;
2338 temp_rec.rec_header.packet_header.len = snaplen;
2339 rec = &temp_rec;
2344 * If an encapsulation type was specified, override the
2345 * encapsulation type of the packet.
2346 * Copy and change rather than modify returned rec.
2348 if (out_frame_type != -2) {
2349 temp_rec = *rec;
2350 temp_rec.rec_header.packet_header.pkt_encap = out_frame_type;
2351 rec = &temp_rec;
2355 * CHOP
2356 * Copy and change rather than modify returned rec.
2358 temp_rec = *rec;
2359 handle_chopping(chop, &temp_rec.rec_header.packet_header,
2360 &rec->rec_header.packet_header, &buf,
2361 adjlen);
2362 rec = &temp_rec;
2364 /* set unused info */
2365 if (set_unused) {
2366 /* set unused bytes to zero so that duplicates check ignores unused bytes */
2367 set_unused_info(&rec->rec_header.packet_header, buf);
2370 /* remove vlan info */
2371 if (rem_vlan) {
2372 /* Copy and change rather than modify returned rec */
2373 temp_rec = *rec;
2374 remove_vlan_info(&rec->rec_header.packet_header, buf,
2375 &temp_rec.rec_header.packet_header.caplen);
2376 rec = &temp_rec;
2379 /* suppress duplicates by packet window */
2380 if (dup_detect) {
2381 if (is_duplicate(buf, rec->rec_header.packet_header.caplen)) {
2382 if (verbose) {
2383 fprintf(stderr, "Skipped: %" PRIu64 ", Len: %u, MD5 Hash: ",
2384 count,
2385 rec->rec_header.packet_header.caplen);
2386 for (i = 0; i < 16; i++)
2387 fprintf(stderr, "%02x",
2388 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2389 fprintf(stderr, "\n");
2391 duplicate_count++;
2392 count++;
2393 continue;
2394 } else {
2395 if (verbose) {
2396 fprintf(stderr, "Packet: %" 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");
2405 } /* suppression of duplicates */
2407 if (rec->presence_flags & WTAP_HAS_TS) {
2408 /* suppress duplicates by time window */
2409 if (dup_detect_by_time) {
2410 nstime_t current;
2412 current.secs = rec->ts.secs;
2413 current.nsecs = rec->ts.nsecs;
2415 if (is_duplicate_rel_time(buf,
2416 rec->rec_header.packet_header.caplen,
2417 &current)) {
2418 if (verbose) {
2419 fprintf(stderr, "Skipped: %" PRIu64 ", Len: %u, MD5 Hash: ",
2420 count,
2421 rec->rec_header.packet_header.caplen);
2422 for (i = 0; i < 16; i++)
2423 fprintf(stderr, "%02x",
2424 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2425 fprintf(stderr, "\n");
2427 duplicate_count++;
2428 count++;
2429 continue;
2430 } else {
2431 if (verbose) {
2432 fprintf(stderr, "Packet: %" 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");
2442 } /* suppress duplicates by time window */
2445 /* Random error mutation */
2446 do_mutation = false;
2447 caplen = 0;
2448 if (err_prob > 0.0) {
2449 switch (rec->rec_type) {
2451 case REC_TYPE_PACKET:
2452 caplen = rec->rec_header.packet_header.caplen;
2453 do_mutation = true;
2454 break;
2456 case REC_TYPE_FT_SPECIFIC_EVENT:
2457 case REC_TYPE_FT_SPECIFIC_REPORT:
2458 caplen = rec->rec_header.ft_specific_header.record_len;
2459 do_mutation = true;
2460 break;
2462 case REC_TYPE_SYSCALL:
2463 caplen = rec->rec_header.syscall_header.event_filelen;
2464 do_mutation = true;
2465 break;
2467 case REC_TYPE_SYSTEMD_JOURNAL_EXPORT:
2468 caplen = rec->rec_header.systemd_journal_export_header.record_len;
2469 do_mutation = true;
2470 break;
2473 if (change_offset > caplen) {
2474 fprintf(stderr, "change offset %u is longer than caplen %u in packet %" PRIu64 "\n",
2475 change_offset, caplen, count);
2476 do_mutation = false;
2480 if (do_mutation) {
2481 int real_data_start = 0;
2483 /* Protect non-protocol data */
2484 switch (rec->rec_type) {
2486 case REC_TYPE_PACKET:
2488 * XXX - any reason not to fuzz this part?
2490 if (rec->rec_header.packet_header.pkt_encap == WTAP_ENCAP_CATAPULT_DCT2000)
2491 real_data_start = find_dct2000_real_data(buf);
2492 break;
2495 real_data_start += change_offset;
2497 for (i = real_data_start; i < (int) caplen; i++) {
2498 if (rand() <= err_prob * RAND_MAX) {
2499 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
2501 if (err_type < ERR_WT_BIT) {
2502 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
2503 err_type = ERR_WT_TOTAL;
2504 } else {
2505 err_type -= ERR_WT_BYTE;
2508 if (err_type < ERR_WT_BYTE) {
2509 buf[i] = rand() / (RAND_MAX / 255 + 1);
2510 err_type = ERR_WT_TOTAL;
2511 } else {
2512 err_type -= ERR_WT_BYTE;
2515 if (err_type < ERR_WT_ALNUM) {
2516 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
2517 err_type = ERR_WT_TOTAL;
2518 } else {
2519 err_type -= ERR_WT_ALNUM;
2522 if (err_type < ERR_WT_FMT) {
2523 if ((unsigned int)i < caplen - 2)
2524 (void) g_strlcpy((char*) &buf[i], "%s", 2);
2525 err_type = ERR_WT_TOTAL;
2526 } else {
2527 err_type -= ERR_WT_FMT;
2530 if (err_type < ERR_WT_AA) {
2531 for (j = i; j < (int) caplen; j++)
2532 buf[j] = 0xAA;
2533 i = caplen;
2537 } /* random error mutation */
2539 /* Discard all packet comments when writing */
2540 if (discard_pkt_comments) {
2541 temp_rec = *rec;
2542 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(rec->block, OPT_COMMENT, 0)) {
2543 temp_rec.block_was_modified = true;
2544 continue;
2546 rec = &temp_rec;
2549 /* Find a packet comment we may need to write */
2550 if (frames_user_comments) {
2551 const char *comment =
2552 (const char*)g_tree_lookup(frames_user_comments, &read_count);
2553 if (comment != NULL) {
2554 /* Copy and change rather than modify returned rec */
2555 temp_rec = *rec;
2557 /* Erase any existing comments before adding the new one */
2558 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(rec->block, OPT_COMMENT, 0)) {
2559 temp_rec.block_was_modified = true;
2560 continue;
2563 /* The comment is not modified by dumper, cast away. */
2564 wtap_block_add_string_option(rec->block, OPT_COMMENT, (char *)comment, strlen((char *)comment));
2565 temp_rec.block_was_modified = true;
2566 rec = &temp_rec;
2567 } else {
2568 /* Copy and change rather than modify returned rec */
2569 temp_rec = *rec;
2570 temp_rec.block_was_modified = false;
2571 rec = &temp_rec;
2575 if (discard_all_secrets) {
2577 * Discard any secrets we've read since the last packet
2578 * we wrote.
2580 wtap_dump_discard_decryption_secrets(pdh);
2583 /* Attempt to dump out current frame to the output file */
2584 if (!wtap_dump(pdh, rec, buf, &write_err, &write_err_info)) {
2585 cfile_write_failure_message(argv[ws_optind], filename,
2586 write_err, write_err_info,
2587 read_count,
2588 out_file_type_subtype);
2589 ret = DUMP_ERROR;
2592 * Close the dump file, but don't report an error
2593 * or set the exit code, as we've already reported
2594 * an error.
2596 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2597 goto clean_exit;
2599 written_count++;
2601 count++;
2602 wtap_rec_reset(&read_rec);
2604 wtap_rec_cleanup(&read_rec);
2605 ws_buffer_free(&read_buf);
2607 if (verbose)
2608 fprintf(stderr, "Total selected: %" PRIu64 "\n", written_count);
2610 if (read_err != 0) {
2611 /* Print a message noting that the read failed somewhere along the
2612 * line. */
2613 cfile_read_failure_message(argv[ws_optind], read_err, read_err_info);
2616 if (!pdh) {
2617 /* No valid packets found, open the outfile so we can write an
2618 * empty header */
2619 g_free (filename);
2620 filename = g_strdup(argv[ws_optind+1]);
2622 pdh = editcap_dump_open(filename, &params, idbs_seen, &write_err,
2623 &write_err_info, compression_type);
2624 if (pdh == NULL) {
2625 cfile_dump_open_failure_message(filename,
2626 write_err, write_err_info,
2627 out_file_type_subtype);
2628 ret = WS_EXIT_INVALID_FILE;
2629 goto clean_exit;
2634 * Process whatever IDBs we haven't seen yet.
2636 if (!process_new_idbs(wth, pdh, idbs_seen, &write_err, &write_err_info)) {
2637 cfile_write_failure_message(argv[ws_optind], filename,
2638 write_err, write_err_info,
2639 read_count,
2640 out_file_type_subtype);
2641 ret = DUMP_ERROR;
2644 * Close the dump file, but don't report an error
2645 * or set the exit code, as we've already reported
2646 * an error.
2648 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2649 goto clean_exit;
2652 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2653 cfile_close_failure_message(filename, write_err, write_err_info);
2654 ret = WRITE_ERROR;
2655 goto clean_exit;
2658 if (dup_detect) {
2659 fprintf(stderr, "%" PRIu64 " packet%s seen, %" PRIu64 " packet%s skipped with duplicate window of %i packets.\n",
2660 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2661 plurality(duplicate_count, "", "s"), dup_window);
2662 } else if (dup_detect_by_time) {
2663 fprintf(stderr, "%" PRIu64 " packet%s seen, %" PRIu64 " packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2664 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2665 plurality(duplicate_count, "", "s"),
2666 (long)relative_time_window.secs,
2667 (long int)relative_time_window.nsecs);
2670 clean_exit:
2671 g_free(fprefix);
2672 g_free(fsuffix);
2674 if (filename) {
2675 g_free(filename);
2677 if (frames_user_comments) {
2678 g_tree_destroy(frames_user_comments);
2680 if (dsb_filenames) {
2681 g_array_free(dsb_types, TRUE);
2682 g_ptr_array_free(dsb_filenames, TRUE);
2684 if (idbs_seen != NULL) {
2685 for (unsigned b = 0; b < idbs_seen->len; b++) {
2686 wtap_block_t if_data = g_array_index(idbs_seen, wtap_block_t, b);
2687 wtap_block_unref(if_data);
2689 g_array_free(idbs_seen, TRUE);
2691 g_free(params.idb_inf);
2692 wtap_dump_params_cleanup(&params);
2693 if (wth != NULL)
2694 wtap_close(wth);
2695 wtap_rec_reset(&read_rec);
2696 wtap_cleanup();
2697 free_progdirs();
2698 if (capture_comments != NULL) {
2699 g_ptr_array_free(capture_comments, TRUE);
2700 capture_comments = NULL;
2702 return ret;
2705 /* Skip meta-information read from file to return offset of real
2706 * protocol data */
2707 static int
2708 find_dct2000_real_data(uint8_t *buf)
2710 int n = 0;
2712 for (n = 0; buf[n] != '\0'; n++); /* Context name */
2713 n++;
2714 n++; /* Context port number */
2715 for (; buf[n] != '\0'; n++); /* Timestamp */
2716 n++;
2717 for (; buf[n] != '\0'; n++); /* Protocol name */
2718 n++;
2719 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
2720 n++;
2721 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
2722 n++;
2723 n += 2; /* Direction & encap */
2725 return n;
2729 * We support up to 2 chopping regions in a single pass: one specified by the
2730 * positive chop length, and one by the negative chop length.
2732 static void
2733 handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
2734 const wtap_packet_header *in_phdr, uint8_t **buf,
2735 bool adjlen)
2737 /* If we're not chopping anything from one side, then the offset for that
2738 * side is meaningless. */
2739 if (chop.len_begin == 0)
2740 chop.off_begin_pos = chop.off_begin_neg = 0;
2741 if (chop.len_end == 0)
2742 chop.off_end_pos = chop.off_end_neg = 0;
2744 if (chop.off_begin_neg < 0) {
2745 chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
2746 chop.off_begin_neg = 0;
2748 if (chop.off_end_pos > 0) {
2749 chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
2750 chop.off_end_pos = 0;
2753 /* If we've crossed chopping regions, swap them */
2754 if (chop.len_begin && chop.len_end) {
2755 if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
2756 int tmp_len, tmp_off;
2758 tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
2759 tmp_len = -chop.len_end;
2761 chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
2762 chop.len_end = -chop.len_begin;
2764 chop.len_begin = tmp_len;
2765 chop.off_begin_pos = tmp_off;
2769 /* Make sure we don't chop off more than we have available */
2770 if (in_phdr->caplen < (uint32_t)(chop.off_begin_pos - chop.off_end_neg)) {
2771 chop.len_begin = 0;
2772 chop.len_end = 0;
2774 if ((uint32_t)(chop.len_begin - chop.len_end) >
2775 (in_phdr->caplen - (uint32_t)(chop.off_begin_pos - chop.off_end_neg))) {
2776 chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
2777 chop.len_end = 0;
2780 /* Handle chopping from the beginning. Note that if a beginning offset
2781 * was specified, we need to keep that piece */
2782 if (chop.len_begin > 0) {
2783 *out_phdr = *in_phdr;
2785 if (chop.off_begin_pos > 0) {
2786 memmove(*buf + chop.off_begin_pos,
2787 *buf + chop.off_begin_pos + chop.len_begin,
2788 out_phdr->caplen - (chop.off_begin_pos + chop.len_begin));
2789 } else {
2790 *buf += chop.len_begin;
2792 out_phdr->caplen -= chop.len_begin;
2794 if (adjlen) {
2795 if (in_phdr->len > (uint32_t)chop.len_begin)
2796 out_phdr->len -= chop.len_begin;
2797 else
2798 out_phdr->len = 0;
2800 in_phdr = out_phdr;
2803 /* Handle chopping from the end. Note that if an ending offset was
2804 * specified, we need to keep that piece */
2805 if (chop.len_end < 0) {
2806 *out_phdr = *in_phdr;
2808 if (chop.off_end_neg < 0) {
2809 memmove(*buf + (int)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2810 *buf + (int)out_phdr->caplen + chop.off_end_neg,
2811 -chop.off_end_neg);
2813 out_phdr->caplen += chop.len_end;
2815 if (adjlen) {
2816 if (((signed int) in_phdr->len + chop.len_end) > 0)
2817 out_phdr->len += chop.len_end;
2818 else
2819 out_phdr->len = 0;
2821 /*in_phdr = out_phdr;*/
2826 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2828 * Local variables:
2829 * c-basic-offset: 4
2830 * tab-width: 8
2831 * indent-tabs-mode: nil
2832 * End:
2834 * vi: set shiftwidth=4 tabstop=8 expandtab:
2835 * :indentSize=4:tabSize=8:noTabs=true: