TODO epan/dissectors/asn1/kerberos/packet-kerberos-template.c new GSS flags
[wireshark-sm.git] / editcap.c
blob5a5f7150d57821714573387434deded49658b3cb
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;
1066 static wtap_dumper *
1067 editcap_dump_open(const char *filename, const wtap_dump_params *params,
1068 GArray *idbs_seen, int *err, char **err_info,
1069 wtap_compression_type compression_type)
1071 wtap_dumper *pdh;
1073 if (strcmp(filename, "-") == 0) {
1074 /* Write to the standard output. */
1075 pdh = wtap_dump_open_stdout(out_file_type_subtype, compression_type,
1076 params, err, err_info);
1077 } else {
1078 pdh = wtap_dump_open(filename, out_file_type_subtype, compression_type,
1079 params, err, err_info);
1081 if (pdh == NULL)
1082 return NULL;
1085 * If the output file supports identifying the interfaces on which
1086 * packets arrive, add all the IDBs we've seen so far.
1088 * That mean that the abstract interface provided by libwiretap
1089 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1091 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh),
1092 WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
1093 for (unsigned i = 0; i < idbs_seen->len; i++) {
1094 wtap_block_t if_data = g_array_index(idbs_seen, wtap_block_t, i);
1095 wtap_block_t if_data_copy;
1098 * Make a copy of this IDB, so that we can change the
1099 * encapsulation type without trashing the original.
1101 if_data_copy = wtap_block_make_copy(if_data);
1104 * If an encapsulation type was specified, override the
1105 * encapsulation type of the interface.
1107 if (out_frame_type != -2) {
1108 wtapng_if_descr_mandatory_t *if_mand;
1110 if_mand = (wtapng_if_descr_mandatory_t *)wtap_block_get_mandatory_data(if_data_copy);
1111 if_mand->wtap_encap = out_frame_type;
1115 * Add this possibly-modified IDB to the file to which
1116 * we're currently writing.
1118 if (!wtap_dump_add_idb(pdh, if_data_copy, err, err_info)) {
1119 int close_err;
1120 char *close_err_info;
1122 wtap_dump_close(pdh, NULL, &close_err, &close_err_info);
1123 g_free(close_err_info);
1124 wtap_block_unref(if_data_copy);
1125 return NULL;
1129 * Release the copy - wtap_dump_add_idb() makes its own copy.
1131 wtap_block_unref(if_data_copy);
1135 return pdh;
1138 static bool
1139 process_new_idbs(wtap *wth, wtap_dumper *pdh, GArray *idbs_seen,
1140 int *err, char **err_info)
1142 wtap_block_t if_data;
1144 while ((if_data = wtap_get_next_interface_description(wth)) != NULL) {
1146 * Only add interface blocks if the output file supports (meaning
1147 * *requires*) them.
1149 * That mean that the abstract interface provided by libwiretap
1150 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1152 if (pdh != NULL && wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh),
1153 WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
1154 wtap_block_t if_data_copy;
1157 * Make a copy of this IDB, so that we can change the
1158 * encapsulation type without trashing the original.
1160 if_data_copy = wtap_block_make_copy(if_data);
1163 * If an encapsulation type was specified, override the
1164 * encapsulation type of the interface.
1166 if (out_frame_type != -2) {
1167 wtapng_if_descr_mandatory_t *if_mand;
1169 if_mand = (wtapng_if_descr_mandatory_t *)wtap_block_get_mandatory_data(if_data_copy);
1170 if_mand->wtap_encap = out_frame_type;
1174 * Add this possibly-modified IDB to the file to which
1175 * we're currently writing.
1177 if (!wtap_dump_add_idb(pdh, if_data_copy, err, err_info))
1178 return false;
1181 * Release the copy - wtap_dump_add_idb() makes its own copy.
1183 wtap_block_unref(if_data_copy);
1186 * Also add an unmodified copy to the set of IDBs we've seen,
1187 * in case we start writing to another file (which would be
1188 * of the same type as the current file, and thus will also
1189 * require interface IDs).
1191 if_data_copy = wtap_block_make_copy(if_data);
1192 g_array_append_val(idbs_seen, if_data_copy);
1195 return true;
1198 static int
1199 extract_secrets(wtap *wth, char* filename, int *err, char **err_info)
1201 wtap_rec read_rec;
1202 Buffer read_buf;
1203 int64_t offset;
1204 char *fprefix = NULL;
1205 char *fsuffix = NULL;
1207 /* Read all of the packets in turn */
1208 wtap_rec_init(&read_rec);
1209 ws_buffer_init(&read_buf, 1514);
1210 while (wtap_read(wth, &read_rec, &read_buf, err, err_info, &offset)) {
1211 /* Do we want to respect the max packet number on the command line?
1212 * Probably more confusing than it's worth, because a user might
1213 * not know if a DSB is at the end of the file.
1215 wtap_rec_reset(&read_rec);
1217 wtap_rec_cleanup(&read_rec);
1218 ws_buffer_free(&read_buf);
1220 wtapng_dsb_mandatory_t *dsb;
1221 if (strcmp(filename, "-") == 0) {
1222 /* Sure. Why not. */
1223 for (unsigned dsb_num = 0; dsb_num < wtap_file_get_num_dsbs(wth); ++dsb_num) {
1224 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth, dsb_num));
1225 if (verbose) {
1226 fprintf(stderr, "Writing secrets type \"%s\" (0x%08x) to standard out.\n",
1227 secrets_type_description(dsb->secrets_type), dsb->secrets_type);
1229 if (fwrite(dsb->secrets_data, 1, dsb->secrets_len, stdout) != dsb->secrets_len) {
1230 return WRITE_ERROR;
1233 } else if (wtap_file_get_num_dsbs(wth) == 1) {
1234 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth, 0));
1235 if (verbose) {
1236 fprintf(stderr, "Writing secrets type \"%s\" (0x%08x) to \"%s\".\n",
1237 secrets_type_description(dsb->secrets_type), dsb->secrets_type,
1238 filename);
1240 if (!write_file_binary_mode(filename, dsb->secrets_data, dsb->secrets_len)) {
1241 return WRITE_ERROR;
1243 } else {
1244 /* We have more than one DSB, so write multiple files. While for some
1245 * types, we could combine the information from different DSBs togther
1246 * (and most of those are text-based, so we'd want to write in text
1247 * mode so that the line endings are uniform (which makes testing
1248 * harder), we don't know that for every type.
1250 if (!fileset_extract_prefix_suffix(filename, &fprefix, &fsuffix, NULL)) {
1251 return CANT_EXTRACT_PREFIX;
1253 char *extract_filename;
1254 for (unsigned dsb_num = 0; dsb_num < wtap_file_get_num_dsbs(wth); ++dsb_num) {
1255 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(wtap_file_get_dsb(wth, dsb_num));
1256 extract_filename = fileset_get_filename_by_pattern(dsb_num, NULL, fprefix, fsuffix);
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 extract_filename);
1262 if (!write_file_binary_mode(extract_filename, dsb->secrets_data, dsb->secrets_len)) {
1263 /* write_file_binary_mode already reports failures */
1264 g_free(extract_filename);
1265 g_free(fprefix);
1266 g_free(fsuffix);
1268 return WRITE_ERROR;
1270 g_free(extract_filename);
1272 g_free(fprefix);
1273 g_free(fsuffix);
1275 return EXIT_SUCCESS;
1279 main(int argc, char *argv[])
1281 char *configuration_init_error;
1282 wtap *wth = NULL;
1283 int i, j, read_err, write_err;
1284 char *read_err_info, *write_err_info;
1285 int opt;
1287 #define LONGOPT_NO_VLAN LONGOPT_BASE_APPLICATION+1
1288 #define LONGOPT_SKIP_RADIOTAP_HEADER LONGOPT_BASE_APPLICATION+2
1289 #define LONGOPT_SEED LONGOPT_BASE_APPLICATION+3
1290 #define LONGOPT_INJECT_SECRETS LONGOPT_BASE_APPLICATION+4
1291 #define LONGOPT_DISCARD_ALL_SECRETS LONGOPT_BASE_APPLICATION+5
1292 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
1293 #define LONGOPT_DISCARD_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+7
1294 #define LONGOPT_SET_UNUSED LONGOPT_BASE_APPLICATION+8
1295 #define LONGOPT_DISCARD_PACKET_COMMENTS LONGOPT_BASE_APPLICATION+9
1296 #define LONGOPT_EXTRACT_SECRETS LONGOPT_BASE_APPLICATION+10
1297 #define LONGOPT_COMPRESS LONGOPT_BASE_APPLICATION+11
1299 static const struct ws_option long_options[] = {
1300 {"novlan", ws_no_argument, NULL, LONGOPT_NO_VLAN},
1301 {"skip-radiotap-header", ws_no_argument, NULL, LONGOPT_SKIP_RADIOTAP_HEADER},
1302 {"seed", ws_required_argument, NULL, LONGOPT_SEED},
1303 {"inject-secrets", ws_required_argument, NULL, LONGOPT_INJECT_SECRETS},
1304 {"discard-all-secrets", ws_no_argument, NULL, LONGOPT_DISCARD_ALL_SECRETS},
1305 {"help", ws_no_argument, NULL, 'h'},
1306 {"version", ws_no_argument, NULL, 'v'},
1307 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
1308 {"discard-capture-comment", ws_no_argument, NULL, LONGOPT_DISCARD_CAPTURE_COMMENT},
1309 {"set-unused", ws_no_argument, NULL, LONGOPT_SET_UNUSED},
1310 {"discard-packet-comments", ws_no_argument, NULL, LONGOPT_DISCARD_PACKET_COMMENTS},
1311 {"extract-secrets", ws_no_argument, NULL, LONGOPT_EXTRACT_SECRETS},
1312 {"compress", ws_required_argument, NULL, LONGOPT_COMPRESS},
1313 {0, 0, 0, 0 }
1316 char *p;
1317 uint32_t snaplen = 0; /* No limit */
1318 chop_t chop = {0, 0, 0, 0, 0, 0}; /* No chop */
1319 bool adjlen = false;
1320 wtap_dumper *pdh = NULL;
1321 GArray *idbs_seen = NULL;
1322 uint64_t count = 1;
1323 uint64_t duplicate_count = 0;
1324 int64_t data_offset;
1325 int err_type;
1326 uint8_t *buf;
1327 uint64_t read_count = 0;
1328 uint64_t split_packet_count = 0;
1329 uint64_t written_count = 0;
1330 char *filename = NULL;
1331 bool ts_okay;
1332 nstime_t secs_per_block = NSTIME_INIT_UNSET;
1333 int block_cnt = 0;
1334 nstime_t block_next = NSTIME_INIT_UNSET;
1335 char *fprefix = NULL;
1336 char *fsuffix = NULL;
1337 uint32_t change_offset = 0;
1338 uint64_t max_packet_number = 0;
1339 GArray *dsb_types = NULL;
1340 GPtrArray *dsb_filenames = NULL;
1341 wtap_rec read_rec;
1342 Buffer read_buf;
1343 const wtap_rec *rec;
1344 wtap_rec temp_rec;
1345 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
1346 char *shb_user_appl;
1347 bool do_mutation;
1348 uint32_t caplen;
1349 int ret = EXIT_SUCCESS;
1350 bool valid_seed = false;
1351 unsigned int seed = 0;
1352 bool edit_option_specified = false;
1353 wtap_compression_type compression_type = WTAP_UNKNOWN_COMPRESSION;
1355 /* Set the program name. */
1356 g_set_prgname("editcap");
1358 cmdarg_err_init(stderr_cmdarg_err, stderr_cmdarg_err_cont);
1359 memset(&read_rec, 0, sizeof *rec);
1361 /* Initialize log handler early so we can have proper logging during startup. */
1362 ws_log_init(vcmdarg_err);
1364 /* Early logging command-line initialization. */
1365 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
1367 ws_noisy("Finished log init and parsing command line log arguments");
1369 #ifdef _WIN32
1370 create_app_running_mutex();
1371 #endif /* _WIN32 */
1374 * Get credential information for later use.
1376 init_process_policies();
1379 * Attempt to get the pathname of the directory containing the
1380 * executable file.
1382 configuration_init_error = configuration_init(argv[0]);
1383 if (configuration_init_error != NULL) {
1384 cmdarg_err("Can't get pathname of directory containing the editcap program: %s.",
1385 configuration_init_error);
1386 g_free(configuration_init_error);
1389 /* Initialize the version information. */
1390 ws_init_version_info("Editcap", NULL, NULL);
1392 init_report_failure_message("editcap");
1394 wtap_init(true);
1396 /* Process the options */
1397 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) {
1398 if (opt != LONGOPT_EXTRACT_SECRETS && opt != 'V') {
1399 edit_option_specified = true;
1401 switch (opt) {
1402 case LONGOPT_NO_VLAN:
1404 rem_vlan = true;
1405 break;
1408 case LONGOPT_SKIP_RADIOTAP_HEADER:
1410 skip_radiotap = true;
1411 break;
1414 case LONGOPT_SEED:
1416 if (sscanf(ws_optarg, "%u", &seed) != 1) {
1417 cmdarg_err("\"%s\" isn't a valid seed", ws_optarg);
1418 ret = WS_EXIT_INVALID_OPTION;
1419 goto clean_exit;
1421 valid_seed = true;
1422 break;
1425 case LONGOPT_INJECT_SECRETS:
1427 uint32_t secrets_type_id = 0;
1428 const char *secrets_filename = NULL;
1429 if (strcmp("help", ws_optarg) == 0) {
1430 list_secrets_types(stdout);
1431 goto clean_exit;
1433 char **splitted = g_strsplit(ws_optarg, ",", 2);
1434 if (splitted[0] && splitted[0][0] != '\0') {
1435 secrets_type_id = lookup_secrets_type(splitted[0]);
1436 if (secrets_type_id == 0) {
1437 cmdarg_err("\"%s\" isn't a valid secrets type", splitted[0]);
1438 g_strfreev(splitted);
1439 ret = WS_EXIT_INVALID_OPTION;
1440 goto clean_exit;
1442 secrets_filename = splitted[1];
1443 } else {
1444 cmdarg_err("no secrets type was specified for --inject-secrets");
1445 g_strfreev(splitted);
1446 ret = WS_EXIT_INVALID_OPTION;
1447 goto clean_exit;
1449 if (!dsb_filenames) {
1450 dsb_types = g_array_new(FALSE, FALSE, sizeof(uint32_t));
1451 dsb_filenames = g_ptr_array_new_with_free_func(g_free);
1453 g_array_append_val(dsb_types, secrets_type_id);
1454 g_ptr_array_add(dsb_filenames, g_strdup(secrets_filename));
1455 g_strfreev(splitted);
1456 break;
1459 case LONGOPT_DISCARD_ALL_SECRETS:
1461 discard_all_secrets = true;
1462 break;
1465 case LONGOPT_CAPTURE_COMMENT:
1468 * Make sure this would fit in a pcapng option.
1470 * XXX - 65535 is the maximum size for an option in pcapng;
1471 * what if another capture file format supports larger
1472 * comments?
1474 if (strlen(ws_optarg) > 65535) {
1475 /* It doesn't fit. Tell the user and give up. */
1476 cmdarg_err("Capture comment %u is too large to save in a capture file.",
1477 capture_comments->len + 1);
1478 ret = WS_EXIT_INVALID_OPTION;
1479 goto clean_exit;
1482 /* pcapng supports multiple comments, so support them here too.
1484 if (!capture_comments) {
1485 capture_comments = g_ptr_array_new_with_free_func(g_free);
1487 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
1488 break;
1491 case LONGOPT_DISCARD_CAPTURE_COMMENT:
1493 discard_cap_comments = true;
1494 break;
1497 case LONGOPT_SET_UNUSED:
1499 set_unused = true;
1500 break;
1503 case LONGOPT_DISCARD_PACKET_COMMENTS:
1505 discard_pkt_comments = true;
1506 break;
1509 case LONGOPT_EXTRACT_SECRETS:
1511 do_extract_secrets = true;
1512 /* XXX - Would it make sense to specify what types of secrets
1513 * to extract (or any)?
1515 break;
1518 case LONGOPT_COMPRESS:
1520 compression_type = wtap_name_to_compression_type(ws_optarg);
1521 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
1522 cmdarg_err("\"%s\" isn't a valid output compression mode",
1523 ws_optarg);
1524 list_output_compression_types();
1525 goto clean_exit;
1527 break;
1530 case 'a':
1532 uint64_t frame_number;
1533 int string_start_index = 0;
1535 if ((sscanf(ws_optarg, "%" SCNu64 ":%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1536 cmdarg_err("\"%s\" isn't a valid <frame>:<comment>", ws_optarg);
1537 ret = WS_EXIT_INVALID_OPTION;
1538 goto clean_exit;
1542 * Make sure this would fit in a pcapng option.
1544 * XXX - 65535 is the maximum size for an option in pcapng;
1545 * what if another capture file format supports larger
1546 * comments?
1548 if (strlen(ws_optarg+string_start_index) > 65535) {
1549 /* It doesn't fit. Tell the user and give up. */
1550 cmdarg_err("A comment for frame %" PRIu64 " is too large to save in a capture file.",
1551 frame_number);
1552 ret = WS_EXIT_INVALID_OPTION;
1553 goto clean_exit;
1556 /* Lazily create the table */
1557 if (!frames_user_comments) {
1558 frames_user_comments = g_tree_new_full(framenum_compare, NULL, g_free, g_free);
1561 /* Insert this entry (framenum -> comment) */
1562 uint64_t *frame_p = g_new(uint64_t, 1);
1563 *frame_p = frame_number;
1564 g_tree_replace(frames_user_comments, frame_p, g_strdup(ws_optarg+string_start_index));
1565 break;
1568 case 'A':
1569 case 'B':
1571 nstime_t in_time;
1573 check_startstop = true;
1574 if ((NULL != iso8601_to_nstime(&in_time, ws_optarg, ISO8601_DATETIME)) || (NULL != unix_epoch_to_nstime(&in_time, ws_optarg))) {
1575 if (opt == 'A') {
1576 nstime_copy(&starttime, &in_time);
1577 have_starttime = true;
1578 } else {
1579 nstime_copy(&stoptime, &in_time);
1580 have_stoptime = true;
1582 break;
1584 else {
1585 cmdarg_err("\"%s\" isn't a valid date and time", ws_optarg);
1586 ret = WS_EXIT_INVALID_OPTION;
1587 goto clean_exit;
1591 case 'c':
1592 split_packet_count = get_nonzero_uint64(ws_optarg, "packet count");
1593 break;
1595 case 'C':
1597 int choplen = 0, chopoff = 0;
1599 switch (sscanf(ws_optarg, "%d:%d", &chopoff, &choplen)) {
1600 case 1: /* only the chop length was specified */
1601 choplen = chopoff;
1602 chopoff = 0;
1603 break;
1605 case 2: /* both an offset and chop length was specified */
1606 break;
1608 default:
1609 cmdarg_err("\"%s\" isn't a valid chop length or offset:length", ws_optarg);
1610 ret = WS_EXIT_INVALID_OPTION;
1611 goto clean_exit;
1612 break;
1615 if (choplen > 0) {
1616 chop.len_begin += choplen;
1617 if (chopoff > 0)
1618 chop.off_begin_pos += chopoff;
1619 else
1620 chop.off_begin_neg += chopoff;
1621 } else if (choplen < 0) {
1622 chop.len_end += choplen;
1623 if (chopoff > 0)
1624 chop.off_end_pos += chopoff;
1625 else
1626 chop.off_end_neg += chopoff;
1628 break;
1631 case 'd':
1632 dup_detect = true;
1633 dup_detect_by_time = false;
1634 dup_window = DEFAULT_DUP_DEPTH;
1635 break;
1637 case 'D':
1638 dup_detect = true;
1639 dup_detect_by_time = false;
1640 dup_window = get_uint32(ws_optarg, "duplicate window");
1641 if (dup_window > MAX_DUP_DEPTH) {
1642 cmdarg_err("\"%d\" duplicate window value must be between 0 and %d inclusive.",
1643 dup_window, MAX_DUP_DEPTH);
1644 ret = WS_EXIT_INVALID_OPTION;
1645 goto clean_exit;
1647 break;
1649 case 'E':
1650 err_prob = g_ascii_strtod(ws_optarg, &p);
1651 if (p == ws_optarg || err_prob < 0.0 || err_prob > 1.0) {
1652 cmdarg_err("probability \"%s\" must be between 0.0 and 1.0", ws_optarg);
1653 ret = WS_EXIT_INVALID_OPTION;
1654 goto clean_exit;
1656 break;
1658 case 'F':
1659 out_file_type_subtype = wtap_name_to_file_type_subtype(ws_optarg);
1660 if (out_file_type_subtype < 0) {
1661 cmdarg_err("\"%s\" isn't a valid capture file type\n", ws_optarg);
1662 list_capture_types(stderr);
1663 ret = WS_EXIT_INVALID_OPTION;
1664 goto clean_exit;
1666 break;
1668 case 'h':
1669 show_help_header("Edit and/or translate the format of capture files.");
1670 print_usage(stdout);
1671 goto clean_exit;
1672 break;
1674 case 'i': /* break capture file based on time interval */
1676 double spb = get_positive_double(ws_optarg, "time interval");
1677 if (spb == 0.0) {
1678 cmdarg_err("The specified interval is zero");
1679 ret = WS_EXIT_INVALID_OPTION;
1680 goto clean_exit;
1683 double spb_int, spb_frac;
1684 spb_frac = modf(spb, &spb_int);
1685 secs_per_block.secs = (time_t) spb_int;
1686 secs_per_block.nsecs = (int) (NANOSECS_PER_SEC * spb_frac);
1688 break;
1690 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1691 ignored_bytes = get_uint32(ws_optarg, "number of bytes to ignore");
1692 break;
1694 case 'L':
1695 adjlen = true;
1696 break;
1698 case 'o':
1699 change_offset = get_uint32(ws_optarg, "change offset");
1700 break;
1702 case 'r':
1703 if (keep_em) {
1704 cmdarg_err("-r was specified twice");
1705 ret = WS_EXIT_INVALID_OPTION;
1706 goto clean_exit;
1708 keep_em = true;
1709 break;
1711 case 's':
1712 snaplen = get_nonzero_uint32(ws_optarg, "snapshot length");
1713 break;
1715 case 'S':
1716 if (!set_strict_time_adj(ws_optarg)) {
1717 ret = WS_EXIT_INVALID_OPTION;
1718 goto clean_exit;
1720 do_strict_time_adjustment = true;
1721 break;
1723 case 't':
1724 if (!set_time_adjustment(ws_optarg)) {
1725 ret = WS_EXIT_INVALID_OPTION;
1726 goto clean_exit;
1728 break;
1730 case 'T':
1731 out_frame_type = wtap_name_to_encap(ws_optarg);
1732 if (out_frame_type < 0) {
1733 cmdarg_err("\"%s\" isn't a valid encapsulation type\n", ws_optarg);
1734 list_encap_types(stderr);
1735 ret = WS_EXIT_INVALID_OPTION;
1736 goto clean_exit;
1738 break;
1740 case 'V':
1741 if (verbose) {
1742 cmdarg_err("-V was specified twice");
1743 ret = WS_EXIT_INVALID_OPTION;
1744 goto clean_exit;
1746 verbose = true;
1747 break;
1749 case 'v':
1750 show_version();
1751 goto clean_exit;
1752 break;
1754 case 'w':
1755 dup_detect = false;
1756 dup_detect_by_time = true;
1757 dup_window = MAX_DUP_DEPTH;
1758 if (!set_rel_time(ws_optarg)) {
1759 ret = WS_EXIT_INVALID_OPTION;
1760 goto clean_exit;
1762 break;
1764 case '?': /* Bad options - print usage */
1765 default:
1766 switch(ws_optopt) {
1767 case'F':
1768 list_capture_types(stdout);
1769 break;
1770 case'T':
1771 list_encap_types(stdout);
1772 break;
1773 case LONGOPT_COMPRESS:
1774 list_output_compression_types();
1775 break;
1776 default:
1777 print_usage(stderr);
1778 ret = WS_EXIT_INVALID_OPTION;
1779 break;
1781 goto clean_exit;
1782 break;
1784 } /* processing command-line options */
1786 #ifdef DEBUG
1787 fprintf(stderr, "Optind = %i, argc = %i\n", ws_optind, argc);
1788 #endif
1790 if ((argc - ws_optind) < 2) {
1791 print_usage(stderr);
1792 ret = WS_EXIT_INVALID_OPTION;
1793 goto clean_exit;
1796 if (out_file_type_subtype == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN) {
1797 /* default to pcapng */
1798 out_file_type_subtype = wtap_pcapng_file_type_subtype();
1801 if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
1802 if (!fileset_extract_prefix_suffix(argv[ws_optind+1], &fprefix, &fsuffix, &compression_type)) {
1803 ret = CANT_EXTRACT_PREFIX;
1804 goto clean_exit;
1806 } else if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
1807 /* An explicitly specified compression type overrides filename
1808 * magic. (Should we allow specifying "no" compression with, e.g.
1809 * a ".gz" extension?) */
1810 const char *sfx = strrchr(argv[ws_optind+1], '.');
1811 if (sfx) {
1812 compression_type = wtap_extension_to_compression_type(sfx + 1);
1816 if (compression_type == WTAP_UNKNOWN_COMPRESSION) {
1817 compression_type = WTAP_UNCOMPRESSED;
1820 if (!wtap_can_write_compression_type(compression_type)) {
1821 cmdarg_err("Output files can't be written as %s",
1822 wtap_compression_type_description(compression_type));
1823 ret = WS_EXIT_INVALID_OPTION;
1824 goto clean_exit;
1827 if (compression_type != WTAP_UNCOMPRESSED && !wtap_dump_can_compress(out_file_type_subtype)) {
1828 cmdarg_err("The file format %s can't be written to output compressed format",
1829 wtap_file_type_subtype_name(out_file_type_subtype));
1830 ret = WS_EXIT_INVALID_OPTION;
1831 goto clean_exit;
1834 if (err_prob >= 0.0) {
1835 if (!valid_seed) {
1836 seed = (unsigned int) (time(NULL) + ws_getpid());
1838 if (verbose) {
1839 fprintf(stderr, "Using seed %u\n", seed);
1841 srand(seed);
1844 if (have_starttime && have_stoptime &&
1845 nstime_cmp(&starttime, &stoptime) > 0) {
1846 cmdarg_err("start time is after the stop time");
1847 ret = WS_EXIT_INVALID_OPTION;
1848 goto clean_exit;
1851 if (split_packet_count != 0 && !nstime_is_unset(&secs_per_block)) {
1852 cmdarg_err("can't split on both packet count and time interval");
1853 cmdarg_err_cont("at the same time");
1854 ret = WS_EXIT_INVALID_OPTION;
1855 goto clean_exit;
1858 wth = wtap_open_offline(argv[ws_optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, false);
1860 if (!wth) {
1861 cfile_open_failure_message(argv[ws_optind], read_err, read_err_info);
1862 ret = WS_EXIT_INVALID_FILE;
1863 goto clean_exit;
1866 if (verbose) {
1867 fprintf(stderr, "File %s is a %s capture file.\n", argv[ws_optind],
1868 wtap_file_type_subtype_description(wtap_file_type_subtype(wth)));
1871 if (skip_radiotap) {
1872 if (ignored_bytes != 0) {
1873 cmdarg_err("can't skip radiotap headers and %d byte(s)", ignored_bytes);
1874 cmdarg_err_cont("at the start of packet at the same time");
1875 ret = WS_EXIT_INVALID_OPTION;
1876 goto clean_exit;
1879 if (wtap_file_encap(wth) != WTAP_ENCAP_IEEE_802_11_RADIOTAP) {
1880 cmdarg_err("can't skip radiotap header because input file has non-radiotap packets");
1881 if (wtap_file_encap(wth) == WTAP_ENCAP_PER_PACKET) {
1882 cmdarg_err_cont("expected '%s', not all packets are necessarily that type",
1883 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP));
1884 } else {
1885 cmdarg_err_cont("expected '%s', packets are '%s'",
1886 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP),
1887 wtap_encap_description(wtap_file_encap(wth)));
1889 ret = WS_EXIT_INVALID_OPTION;
1890 goto clean_exit;
1894 if (do_extract_secrets) {
1895 if (edit_option_specified) {
1896 cmdarg_err("can't extract secrets and use other options at the same time");
1897 ret = WS_EXIT_INVALID_OPTION;
1898 goto clean_exit;
1900 if (compression_type != WTAP_UNCOMPRESSED) {
1901 cmdarg_err("compression isn't supported for extracting secrets");
1902 ret = WS_EXIT_INVALID_OPTION;
1903 goto clean_exit;
1905 ret = extract_secrets(wth, argv[ws_optind+1], &read_err, &read_err_info);
1907 if (read_err != 0) {
1908 /* Print a message noting that the read failed somewhere along the
1909 * line. */
1910 cfile_read_failure_message(argv[ws_optind], read_err, read_err_info);
1912 goto clean_exit;
1915 wtap_dump_params_init_no_idbs(&params, wth);
1918 * Discard any secrets we read in while opening the file.
1920 if (discard_all_secrets) {
1921 wtap_dump_params_discard_decryption_secrets(&params);
1925 * Discard capture file comments.
1927 if (discard_cap_comments) {
1928 for (unsigned b = 0; b < params.shb_hdrs->len; b++) {
1929 wtap_block_t shb = g_array_index(params.shb_hdrs, wtap_block_t, b);
1930 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(shb, OPT_COMMENT, 0)) {
1931 continue;
1937 * Add new capture file comments.
1939 if (capture_comments != NULL) {
1940 for (unsigned b = 0; b < params.shb_hdrs->len; b++) {
1941 wtap_block_t shb = g_array_index(params.shb_hdrs, wtap_block_t, b);
1942 for (unsigned c = 0; c < capture_comments->len; c++) {
1943 char *comment = (char *)g_ptr_array_index(capture_comments, c);
1944 wtap_block_add_string_option(shb, OPT_COMMENT, comment, strlen(comment));
1949 if (dsb_filenames) {
1950 for (unsigned k = 0; k < dsb_filenames->len; k++) {
1951 uint32_t secrets_type_id = g_array_index(dsb_types, uint32_t, k);
1952 const char *secrets_filename = (const char *)g_ptr_array_index(dsb_filenames, k);
1953 char *data;
1954 size_t data_len;
1955 wtap_block_t block;
1956 wtapng_dsb_mandatory_t *dsb;
1957 GError *err = NULL;
1959 if (!g_file_get_contents(secrets_filename, &data, &data_len, &err)) {
1960 cmdarg_err("\"%s\" could not be read: %s", secrets_filename, err->message);
1961 g_clear_error(&err);
1962 ret = WS_EXIT_INVALID_OPTION;
1963 goto clean_exit;
1965 if (data_len == 0) {
1966 cmdarg_err("\"%s\" is an empty file, ignoring", secrets_filename);
1967 g_free(data);
1968 continue;
1970 if (data_len >= INT_MAX) {
1971 cmdarg_err("\"%s\" is too large, ignoring", secrets_filename);
1972 g_free(data);
1973 continue;
1976 /* Warn for badly formatted files, but proceed anyway. */
1977 validate_secrets_file(secrets_filename, secrets_type_id, data);
1979 block = wtap_block_create(WTAP_BLOCK_DECRYPTION_SECRETS);
1980 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(block);
1981 dsb->secrets_type = secrets_type_id;
1982 dsb->secrets_len = (unsigned)data_len;
1983 dsb->secrets_data = data;
1984 if (params.dsbs_initial == NULL) {
1985 params.dsbs_initial = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
1987 g_array_append_val(params.dsbs_initial, block);
1992 * If an encapsulation type was specified, override the encapsulation
1993 * type of the input file.
1995 if (out_frame_type != -2)
1996 params.encap = out_frame_type;
1999 * If a snapshot length was specified, and it's less than the snapshot
2000 * length of the input file, override the snapshot length of the input
2001 * file.
2003 if (snaplen != 0 && snaplen < wtap_snapshot_length(wth))
2004 params.snaplen = snaplen;
2007 * Now process the arguments following the input and output file
2008 * names, if any; they specify packets to include/exclude.
2010 for (i = ws_optind + 2; i < argc; i++)
2011 if (add_selection(argv[i], &max_packet_number) == false)
2012 break;
2014 if (keep_em && max_selected == 0) {
2015 cmdarg_err("must specify packets to keep when using -r");
2016 ret = WS_EXIT_INVALID_OPTION;
2017 goto clean_exit;
2020 if (!keep_em)
2021 max_packet_number = UINT64_MAX;
2023 if (dup_detect || dup_detect_by_time) {
2024 for (i = 0; i < dup_window; i++) {
2025 memset(&fd_hash[i].digest, 0, 16);
2026 fd_hash[i].len = 0;
2027 nstime_set_unset(&fd_hash[i].frame_time);
2031 /* Set up an array of all IDBs seen */
2032 idbs_seen = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
2034 /* Read all of the packets in turn */
2035 wtap_rec_init(&read_rec);
2036 ws_buffer_init(&read_buf, 1514);
2037 while (wtap_read(wth, &read_rec, &read_buf, &read_err, &read_err_info, &data_offset)) {
2039 * XXX - what about non-packet records in the file after this?
2040 * NRBs, DSBs, and ISBs are now written when wtap_dump_close() calls
2041 * pcapng_dump_finish(), and we handle IDBs below, but what about
2042 * custom blocks?
2044 if (max_packet_number <= read_count)
2045 break;
2047 read_count++;
2049 rec = &read_rec;
2051 /* Extra actions for the first packet */
2052 if (read_count == 1) {
2053 if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
2054 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
2055 } else {
2056 filename = g_strdup(argv[ws_optind+1]);
2058 ws_assert(filename);
2060 /* If we don't have an application name add one */
2061 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) {
2062 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
2065 pdh = editcap_dump_open(filename, &params, idbs_seen, &write_err,
2066 &write_err_info, compression_type);
2068 if (pdh == NULL) {
2069 cfile_dump_open_failure_message(filename,
2070 write_err, write_err_info,
2071 out_file_type_subtype);
2072 ret = WS_EXIT_INVALID_FILE;
2073 goto clean_exit;
2075 } /* first packet only handling */
2078 * Process whatever IDBs we haven't seen yet.
2080 if (!process_new_idbs(wth, pdh, idbs_seen, &write_err, &write_err_info)) {
2081 cfile_write_failure_message(argv[ws_optind], filename,
2082 write_err, write_err_info,
2083 read_count,
2084 out_file_type_subtype);
2085 ret = DUMP_ERROR;
2088 * Close the dump file, but don't report an error
2089 * or set the exit code, as we've already reported
2090 * an error.
2092 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2093 goto clean_exit;
2096 buf = ws_buffer_start_ptr(&read_buf);
2099 * Not all packets have time stamps. Only process the time
2100 * stamp if we have one.
2102 if (rec->presence_flags & WTAP_HAS_TS) {
2103 if (!nstime_is_unset(&secs_per_block)) {
2104 if (nstime_is_unset(&block_next)) {
2105 block_next = rec->ts;
2106 nstime_add(&block_next, &secs_per_block);
2108 while (nstime_cmp(&rec->ts, &block_next) > 0) { /* time for the next file */
2110 /* We presumably want to write the DSBs from files given
2111 * on the command line to every file.
2113 wtap_block_array_ref(params.dsbs_initial);
2114 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2115 cfile_close_failure_message(filename, write_err,
2116 write_err_info);
2117 ret = WRITE_ERROR;
2118 goto clean_exit;
2120 g_free(filename);
2121 /* Use the interval start time for the filename. */
2122 temp_rec = *rec;
2123 temp_rec.ts = block_next;
2124 filename = fileset_get_filename_by_pattern(block_cnt++, &temp_rec, fprefix, fsuffix);
2125 ws_assert(filename);
2126 nstime_add(&block_next, &secs_per_block); /* reset for next interval */
2128 if (verbose)
2129 fprintf(stderr, "Continuing writing in file %s\n", filename);
2131 pdh = editcap_dump_open(filename, &params, idbs_seen,
2132 &write_err, &write_err_info, compression_type);
2134 if (pdh == NULL) {
2135 cfile_dump_open_failure_message(filename,
2136 write_err,
2137 write_err_info,
2138 out_file_type_subtype);
2139 ret = WS_EXIT_INVALID_FILE;
2140 goto clean_exit;
2144 } /* time stamp handling */
2146 if (split_packet_count != 0) {
2147 /* time for the next file? */
2148 if (written_count > 0 && (written_count % split_packet_count) == 0) {
2150 /* We presumably want to write the DSBs from files given
2151 * on the command line to every file.
2153 wtap_block_array_ref(params.dsbs_initial);
2154 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2155 cfile_close_failure_message(filename, write_err,
2156 write_err_info);
2157 ret = WRITE_ERROR;
2158 goto clean_exit;
2161 g_free(filename);
2162 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
2163 ws_assert(filename);
2165 if (verbose)
2166 fprintf(stderr, "Continuing writing in file %s\n", filename);
2168 pdh = editcap_dump_open(filename, &params, idbs_seen,
2169 &write_err, &write_err_info, compression_type);
2170 if (pdh == NULL) {
2171 cfile_dump_open_failure_message(filename,
2172 write_err, write_err_info,
2173 out_file_type_subtype);
2174 ret = WS_EXIT_INVALID_FILE;
2175 goto clean_exit;
2178 } /* split packet handling */
2180 if (check_startstop) {
2181 ts_okay = false;
2183 * Is the packet in the selected timeframe?
2184 * If the packet has no time stamp, the answer is "no".
2186 if (rec->presence_flags & WTAP_HAS_TS) {
2187 if (have_starttime && have_stoptime) {
2188 ts_okay = nstime_cmp(&rec->ts, &starttime) >= 0 &&
2189 nstime_cmp(&rec->ts, &stoptime) < 0;
2190 } else if (have_starttime) {
2191 ts_okay = nstime_cmp(&rec->ts, &starttime) >= 0;
2192 } else if (have_stoptime) {
2193 ts_okay = nstime_cmp(&rec->ts, &stoptime) < 0;
2196 } else {
2198 * No selected timeframe, so all packets are "in the
2199 * selected timeframe".
2201 ts_okay = true;
2204 if (ts_okay && ((!selected(count) && !keep_em)
2205 || (selected(count) && keep_em))) {
2207 if (verbose && !dup_detect && !dup_detect_by_time)
2208 fprintf(stderr, "Packet: %" PRIu64 "\n", count);
2210 /* We simply write it, perhaps after truncating it; we could
2211 * do other things, like modify it. */
2213 rec = &read_rec;
2215 if (rec->presence_flags & WTAP_HAS_TS) {
2216 /* Do we adjust timestamps to ensure strict chronological
2217 * order? */
2218 if (do_strict_time_adjustment) {
2219 if (previous_time.secs || previous_time.nsecs) {
2220 if (!strict_time_adj.is_negative) {
2221 nstime_t current;
2222 nstime_t delta;
2224 current = rec->ts;
2226 nstime_delta(&delta, &current, &previous_time);
2228 if (delta.secs < 0 || delta.nsecs < 0) {
2230 * A negative delta indicates that the current packet
2231 * has an absolute timestamp less than the previous packet
2232 * that it is being compared to. This is NOT a normal
2233 * situation since trace files usually have packets in
2234 * chronological order (oldest to newest).
2235 * Copy and change rather than modify
2236 * returned rec.
2238 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
2239 temp_rec = *rec;
2240 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
2241 temp_rec.ts.nsecs = previous_time.nsecs;
2242 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
2243 /* carry */
2244 temp_rec.ts.secs++;
2245 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2246 } else {
2247 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
2249 rec = &temp_rec;
2251 } else {
2253 * A negative strict time adjustment is requested.
2254 * Unconditionally set each timestamp to previous
2255 * packet's timestamp plus delta.
2256 * Copy and change rather than modify returned
2257 * rec.
2259 temp_rec = *rec;
2260 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
2261 temp_rec.ts.nsecs = previous_time.nsecs;
2262 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
2263 /* carry */
2264 temp_rec.ts.secs++;
2265 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2266 } else {
2267 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
2269 rec = &temp_rec;
2272 previous_time = rec->ts;
2275 if (time_adj.tv.secs != 0) {
2276 /* Copy and change rather than modify returned rec */
2277 temp_rec = *rec;
2278 if (time_adj.is_negative)
2279 temp_rec.ts.secs -= time_adj.tv.secs;
2280 else
2281 temp_rec.ts.secs += time_adj.tv.secs;
2282 rec = &temp_rec;
2285 if (time_adj.tv.nsecs != 0) {
2286 /* Copy and change rather than modify returned rec */
2287 temp_rec = *rec;
2288 if (time_adj.is_negative) { /* subtract */
2289 if (temp_rec.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
2290 temp_rec.ts.secs--;
2291 temp_rec.ts.nsecs += ONE_BILLION;
2293 temp_rec.ts.nsecs -= time_adj.tv.nsecs;
2294 } else { /* add */
2295 if (temp_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
2296 /* carry */
2297 temp_rec.ts.secs++;
2298 temp_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
2299 } else {
2300 temp_rec.ts.nsecs += time_adj.tv.nsecs;
2303 rec = &temp_rec;
2305 } /* time stamp adjustment */
2307 if (rec->rec_type == REC_TYPE_PACKET) {
2308 if (snaplen != 0) {
2309 /* Limit capture length to snaplen */
2310 if (rec->rec_header.packet_header.caplen > snaplen) {
2311 /* Copy and change rather than modify returned rec */
2312 temp_rec = *rec;
2313 temp_rec.rec_header.packet_header.caplen = snaplen;
2314 rec = &temp_rec;
2316 /* If -L, also set reported length to snaplen */
2317 if (adjlen && rec->rec_header.packet_header.len > snaplen) {
2318 /* Copy and change rather than modify returned rec */
2319 temp_rec = *rec;
2320 temp_rec.rec_header.packet_header.len = snaplen;
2321 rec = &temp_rec;
2326 * If an encapsulation type was specified, override the
2327 * encapsulation type of the packet.
2328 * Copy and change rather than modify returned rec.
2330 if (out_frame_type != -2) {
2331 temp_rec = *rec;
2332 temp_rec.rec_header.packet_header.pkt_encap = out_frame_type;
2333 rec = &temp_rec;
2337 * CHOP
2338 * Copy and change rather than modify returned rec.
2340 temp_rec = *rec;
2341 handle_chopping(chop, &temp_rec.rec_header.packet_header,
2342 &rec->rec_header.packet_header, &buf,
2343 adjlen);
2344 rec = &temp_rec;
2346 /* set unused info */
2347 if (set_unused) {
2348 /* set unused bytes to zero so that duplicates check ignores unused bytes */
2349 set_unused_info(&rec->rec_header.packet_header, buf);
2352 /* remove vlan info */
2353 if (rem_vlan) {
2354 /* Copy and change rather than modify returned rec */
2355 temp_rec = *rec;
2356 remove_vlan_info(&rec->rec_header.packet_header, buf,
2357 &temp_rec.rec_header.packet_header.caplen);
2358 rec = &temp_rec;
2361 /* suppress duplicates by packet window */
2362 if (dup_detect) {
2363 if (is_duplicate(buf, rec->rec_header.packet_header.caplen)) {
2364 if (verbose) {
2365 fprintf(stderr, "Skipped: %" PRIu64 ", Len: %u, MD5 Hash: ",
2366 count,
2367 rec->rec_header.packet_header.caplen);
2368 for (i = 0; i < 16; i++)
2369 fprintf(stderr, "%02x",
2370 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2371 fprintf(stderr, "\n");
2373 duplicate_count++;
2374 count++;
2375 continue;
2376 } else {
2377 if (verbose) {
2378 fprintf(stderr, "Packet: %" PRIu64 ", Len: %u, MD5 Hash: ",
2379 count,
2380 rec->rec_header.packet_header.caplen);
2381 for (i = 0; i < 16; i++)
2382 fprintf(stderr, "%02x",
2383 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2384 fprintf(stderr, "\n");
2387 } /* suppression of duplicates */
2389 if (rec->presence_flags & WTAP_HAS_TS) {
2390 /* suppress duplicates by time window */
2391 if (dup_detect_by_time) {
2392 nstime_t current;
2394 current.secs = rec->ts.secs;
2395 current.nsecs = rec->ts.nsecs;
2397 if (is_duplicate_rel_time(buf,
2398 rec->rec_header.packet_header.caplen,
2399 &current)) {
2400 if (verbose) {
2401 fprintf(stderr, "Skipped: %" PRIu64 ", Len: %u, MD5 Hash: ",
2402 count,
2403 rec->rec_header.packet_header.caplen);
2404 for (i = 0; i < 16; i++)
2405 fprintf(stderr, "%02x",
2406 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2407 fprintf(stderr, "\n");
2409 duplicate_count++;
2410 count++;
2411 continue;
2412 } else {
2413 if (verbose) {
2414 fprintf(stderr, "Packet: %" PRIu64 ", Len: %u, MD5 Hash: ",
2415 count,
2416 rec->rec_header.packet_header.caplen);
2417 for (i = 0; i < 16; i++)
2418 fprintf(stderr, "%02x",
2419 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2420 fprintf(stderr, "\n");
2424 } /* suppress duplicates by time window */
2427 /* Random error mutation */
2428 do_mutation = false;
2429 caplen = 0;
2430 if (err_prob > 0.0) {
2431 switch (rec->rec_type) {
2433 case REC_TYPE_PACKET:
2434 caplen = rec->rec_header.packet_header.caplen;
2435 do_mutation = true;
2436 break;
2438 case REC_TYPE_FT_SPECIFIC_EVENT:
2439 case REC_TYPE_FT_SPECIFIC_REPORT:
2440 caplen = rec->rec_header.ft_specific_header.record_len;
2441 do_mutation = true;
2442 break;
2444 case REC_TYPE_SYSCALL:
2445 caplen = rec->rec_header.syscall_header.event_filelen;
2446 do_mutation = true;
2447 break;
2449 case REC_TYPE_SYSTEMD_JOURNAL_EXPORT:
2450 caplen = rec->rec_header.systemd_journal_export_header.record_len;
2451 do_mutation = true;
2452 break;
2455 if (change_offset > caplen) {
2456 fprintf(stderr, "change offset %u is longer than caplen %u in packet %" PRIu64 "\n",
2457 change_offset, caplen, count);
2458 do_mutation = false;
2462 if (do_mutation) {
2463 int real_data_start = 0;
2465 /* Protect non-protocol data */
2466 switch (rec->rec_type) {
2468 case REC_TYPE_PACKET:
2470 * XXX - any reason not to fuzz this part?
2472 if (rec->rec_header.packet_header.pkt_encap == WTAP_ENCAP_CATAPULT_DCT2000)
2473 real_data_start = find_dct2000_real_data(buf);
2474 break;
2477 real_data_start += change_offset;
2479 for (i = real_data_start; i < (int) caplen; i++) {
2480 if (rand() <= err_prob * RAND_MAX) {
2481 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
2483 if (err_type < ERR_WT_BIT) {
2484 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
2485 err_type = ERR_WT_TOTAL;
2486 } else {
2487 err_type -= ERR_WT_BYTE;
2490 if (err_type < ERR_WT_BYTE) {
2491 buf[i] = rand() / (RAND_MAX / 255 + 1);
2492 err_type = ERR_WT_TOTAL;
2493 } else {
2494 err_type -= ERR_WT_BYTE;
2497 if (err_type < ERR_WT_ALNUM) {
2498 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
2499 err_type = ERR_WT_TOTAL;
2500 } else {
2501 err_type -= ERR_WT_ALNUM;
2504 if (err_type < ERR_WT_FMT) {
2505 if ((unsigned int)i < caplen - 2)
2506 (void) g_strlcpy((char*) &buf[i], "%s", 2);
2507 err_type = ERR_WT_TOTAL;
2508 } else {
2509 err_type -= ERR_WT_FMT;
2512 if (err_type < ERR_WT_AA) {
2513 for (j = i; j < (int) caplen; j++)
2514 buf[j] = 0xAA;
2515 i = caplen;
2519 } /* random error mutation */
2521 /* Discard all packet comments when writing */
2522 if (discard_pkt_comments) {
2523 temp_rec = *rec;
2524 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(rec->block, OPT_COMMENT, 0)) {
2525 temp_rec.block_was_modified = true;
2526 continue;
2528 rec = &temp_rec;
2531 /* Find a packet comment we may need to write */
2532 if (frames_user_comments) {
2533 const char *comment =
2534 (const char*)g_tree_lookup(frames_user_comments, &read_count);
2535 if (comment != NULL) {
2536 /* Copy and change rather than modify returned rec */
2537 temp_rec = *rec;
2539 /* Erase any existing comments before adding the new one */
2540 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(rec->block, OPT_COMMENT, 0)) {
2541 temp_rec.block_was_modified = true;
2542 continue;
2545 /* The comment is not modified by dumper, cast away. */
2546 wtap_block_add_string_option(rec->block, OPT_COMMENT, (char *)comment, strlen((char *)comment));
2547 temp_rec.block_was_modified = true;
2548 rec = &temp_rec;
2549 } else {
2550 /* Copy and change rather than modify returned rec */
2551 temp_rec = *rec;
2552 temp_rec.block_was_modified = false;
2553 rec = &temp_rec;
2557 if (discard_all_secrets) {
2559 * Discard any secrets we've read since the last packet
2560 * we wrote.
2562 wtap_dump_discard_decryption_secrets(pdh);
2565 /* Attempt to dump out current frame to the output file */
2566 if (!wtap_dump(pdh, rec, buf, &write_err, &write_err_info)) {
2567 cfile_write_failure_message(argv[ws_optind], filename,
2568 write_err, write_err_info,
2569 read_count,
2570 out_file_type_subtype);
2571 ret = DUMP_ERROR;
2574 * Close the dump file, but don't report an error
2575 * or set the exit code, as we've already reported
2576 * an error.
2578 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2579 goto clean_exit;
2581 written_count++;
2583 count++;
2584 wtap_rec_reset(&read_rec);
2586 wtap_rec_cleanup(&read_rec);
2587 ws_buffer_free(&read_buf);
2589 if (verbose)
2590 fprintf(stderr, "Total selected: %" PRIu64 "\n", written_count);
2592 if (read_err != 0) {
2593 /* Print a message noting that the read failed somewhere along the
2594 * line. */
2595 cfile_read_failure_message(argv[ws_optind], read_err, read_err_info);
2598 if (!pdh) {
2599 /* No valid packets found, open the outfile so we can write an
2600 * empty header */
2601 g_free (filename);
2602 filename = g_strdup(argv[ws_optind+1]);
2604 pdh = editcap_dump_open(filename, &params, idbs_seen, &write_err,
2605 &write_err_info, compression_type);
2606 if (pdh == NULL) {
2607 cfile_dump_open_failure_message(filename,
2608 write_err, write_err_info,
2609 out_file_type_subtype);
2610 ret = WS_EXIT_INVALID_FILE;
2611 goto clean_exit;
2616 * Process whatever IDBs we haven't seen yet.
2618 if (!process_new_idbs(wth, pdh, idbs_seen, &write_err, &write_err_info)) {
2619 cfile_write_failure_message(argv[ws_optind], filename,
2620 write_err, write_err_info,
2621 read_count,
2622 out_file_type_subtype);
2623 ret = DUMP_ERROR;
2626 * Close the dump file, but don't report an error
2627 * or set the exit code, as we've already reported
2628 * an error.
2630 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2631 goto clean_exit;
2634 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2635 cfile_close_failure_message(filename, write_err, write_err_info);
2636 ret = WRITE_ERROR;
2637 goto clean_exit;
2640 if (dup_detect) {
2641 fprintf(stderr, "%" PRIu64 " packet%s seen, %" PRIu64 " packet%s skipped with duplicate window of %i packets.\n",
2642 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2643 plurality(duplicate_count, "", "s"), dup_window);
2644 } else if (dup_detect_by_time) {
2645 fprintf(stderr, "%" PRIu64 " packet%s seen, %" PRIu64 " packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2646 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2647 plurality(duplicate_count, "", "s"),
2648 (long)relative_time_window.secs,
2649 (long int)relative_time_window.nsecs);
2652 clean_exit:
2653 g_free(fprefix);
2654 g_free(fsuffix);
2656 if (filename) {
2657 g_free(filename);
2659 if (frames_user_comments) {
2660 g_tree_destroy(frames_user_comments);
2662 if (dsb_filenames) {
2663 g_array_free(dsb_types, TRUE);
2664 g_ptr_array_free(dsb_filenames, TRUE);
2666 if (idbs_seen != NULL) {
2667 for (unsigned b = 0; b < idbs_seen->len; b++) {
2668 wtap_block_t if_data = g_array_index(idbs_seen, wtap_block_t, b);
2669 wtap_block_unref(if_data);
2671 g_array_free(idbs_seen, TRUE);
2673 g_free(params.idb_inf);
2674 wtap_dump_params_cleanup(&params);
2675 if (wth != NULL)
2676 wtap_close(wth);
2677 wtap_rec_reset(&read_rec);
2678 wtap_cleanup();
2679 free_progdirs();
2680 if (capture_comments != NULL) {
2681 g_ptr_array_free(capture_comments, TRUE);
2682 capture_comments = NULL;
2684 return ret;
2687 /* Skip meta-information read from file to return offset of real
2688 * protocol data */
2689 static int
2690 find_dct2000_real_data(uint8_t *buf)
2692 int n = 0;
2694 for (n = 0; buf[n] != '\0'; n++); /* Context name */
2695 n++;
2696 n++; /* Context port number */
2697 for (; buf[n] != '\0'; n++); /* Timestamp */
2698 n++;
2699 for (; buf[n] != '\0'; n++); /* Protocol name */
2700 n++;
2701 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
2702 n++;
2703 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
2704 n++;
2705 n += 2; /* Direction & encap */
2707 return n;
2711 * We support up to 2 chopping regions in a single pass: one specified by the
2712 * positive chop length, and one by the negative chop length.
2714 static void
2715 handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
2716 const wtap_packet_header *in_phdr, uint8_t **buf,
2717 bool adjlen)
2719 /* If we're not chopping anything from one side, then the offset for that
2720 * side is meaningless. */
2721 if (chop.len_begin == 0)
2722 chop.off_begin_pos = chop.off_begin_neg = 0;
2723 if (chop.len_end == 0)
2724 chop.off_end_pos = chop.off_end_neg = 0;
2726 if (chop.off_begin_neg < 0) {
2727 chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
2728 chop.off_begin_neg = 0;
2730 if (chop.off_end_pos > 0) {
2731 chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
2732 chop.off_end_pos = 0;
2735 /* If we've crossed chopping regions, swap them */
2736 if (chop.len_begin && chop.len_end) {
2737 if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
2738 int tmp_len, tmp_off;
2740 tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
2741 tmp_len = -chop.len_end;
2743 chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
2744 chop.len_end = -chop.len_begin;
2746 chop.len_begin = tmp_len;
2747 chop.off_begin_pos = tmp_off;
2751 /* Make sure we don't chop off more than we have available */
2752 if (in_phdr->caplen < (uint32_t)(chop.off_begin_pos - chop.off_end_neg)) {
2753 chop.len_begin = 0;
2754 chop.len_end = 0;
2756 if ((uint32_t)(chop.len_begin - chop.len_end) >
2757 (in_phdr->caplen - (uint32_t)(chop.off_begin_pos - chop.off_end_neg))) {
2758 chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
2759 chop.len_end = 0;
2762 /* Handle chopping from the beginning. Note that if a beginning offset
2763 * was specified, we need to keep that piece */
2764 if (chop.len_begin > 0) {
2765 *out_phdr = *in_phdr;
2767 if (chop.off_begin_pos > 0) {
2768 memmove(*buf + chop.off_begin_pos,
2769 *buf + chop.off_begin_pos + chop.len_begin,
2770 out_phdr->caplen - (chop.off_begin_pos + chop.len_begin));
2771 } else {
2772 *buf += chop.len_begin;
2774 out_phdr->caplen -= chop.len_begin;
2776 if (adjlen) {
2777 if (in_phdr->len > (uint32_t)chop.len_begin)
2778 out_phdr->len -= chop.len_begin;
2779 else
2780 out_phdr->len = 0;
2782 in_phdr = out_phdr;
2785 /* Handle chopping from the end. Note that if an ending offset was
2786 * specified, we need to keep that piece */
2787 if (chop.len_end < 0) {
2788 *out_phdr = *in_phdr;
2790 if (chop.off_end_neg < 0) {
2791 memmove(*buf + (int)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2792 *buf + (int)out_phdr->caplen + chop.off_end_neg,
2793 -chop.off_end_neg);
2795 out_phdr->caplen += chop.len_end;
2797 if (adjlen) {
2798 if (((signed int) in_phdr->len + chop.len_end) > 0)
2799 out_phdr->len += chop.len_end;
2800 else
2801 out_phdr->len = 0;
2803 /*in_phdr = out_phdr;*/
2808 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2810 * Local variables:
2811 * c-basic-offset: 4
2812 * tab-width: 8
2813 * indent-tabs-mode: nil
2814 * End:
2816 * vi: set shiftwidth=4 tabstop=8 expandtab:
2817 * :indentSize=4:tabSize=8:noTabs=true: