Qt: Fix leak on CaptureFileDialog preview of file with errors
[wireshark.git] / editcap.c
bloba7954cff8d2dac3a25132c519b7f9809d2a2f542
1 /* editcap.c
2 * Edit capture files. We can delete packets, adjust timestamps, or
3 * simply convert from one format to another format.
5 * Originally written by Richard Sharpe.
6 * Improved by Guy Harris.
7 * Further improved by Richard Sharpe.
9 * Copyright 2013, Richard Sharpe <realrichardsharpe[AT]gmail.com>
11 * Wireshark - Network traffic analyzer
12 * By Gerald Combs <gerald@wireshark.org>
13 * Copyright 1998 Gerald Combs
15 * SPDX-License-Identifier: GPL-2.0-or-later
18 #include <config.h>
19 #define WS_LOG_DOMAIN LOG_DOMAIN_MAIN
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdarg.h>
25 #include <math.h>
26 #include <stddef.h>
28 #include <time.h>
29 #include <glib.h>
30 #include <gcrypt.h>
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
36 #include <ws_exit_codes.h>
37 #include <wsutil/ws_getopt.h>
39 #include <wiretap/secrets-types.h>
40 #include <wiretap/wtap.h>
42 #include "epan/etypes.h"
43 #include "epan/dissectors/packet-ieee80211-radiotap-defs.h"
45 #ifdef _WIN32
46 #include <process.h> /* getpid */
47 #include <winsock2.h>
48 #endif
50 #include <wsutil/clopts_common.h>
51 #include <wsutil/cmdarg_err.h>
52 #include <wsutil/filesystem.h>
53 #include <wsutil/file_util.h>
54 #include <wsutil/plugins.h>
55 #include <wsutil/privileges.h>
56 #include <wsutil/report_message.h>
57 #include <wsutil/strnatcmp.h>
58 #include <wsutil/str_util.h>
59 #include <cli_main.h>
60 #include <wsutil/version_info.h>
61 #include <wsutil/pint.h>
62 #include <wsutil/strtoi.h>
63 #include <wsutil/ws_assert.h>
64 #include <wsutil/wslog.h>
65 #include <wiretap/wtap_opttypes.h>
67 #include "ui/failure_message.h"
69 #include "ringbuffer.h" /* For RINGBUFFER_MAX_NUM_FILES */
71 /* Additional exit codes */
72 #define CANT_EXTRACT_PREFIX 2
73 #define WRITE_ERROR 2
74 #define DUMP_ERROR 2
76 #define NANOSECS_PER_SEC 1000000000
79 * Some globals so we can pass things to various routines
82 struct select_item {
83 gboolean inclusive;
84 guint first, second;
88 * Duplicate frame detection
90 typedef struct _fd_hash_t {
91 guint8 digest[16];
92 guint32 len;
93 nstime_t frame_time;
94 } fd_hash_t;
96 #define DEFAULT_DUP_DEPTH 5 /* Used with -d */
97 #define MAX_DUP_DEPTH 1000000 /* the maximum window (and actual size of fd_hash[]) for de-duplication */
99 static fd_hash_t fd_hash[MAX_DUP_DEPTH];
100 static int dup_window = DEFAULT_DUP_DEPTH;
101 static int cur_dup_entry;
103 static guint32 ignored_bytes; /* Used with -I */
105 #define ONE_BILLION 1000000000
107 /* Weights of different errors we can introduce */
108 /* We should probably make these command-line arguments */
109 /* XXX - Should we add a bit-level error? */
110 #define ERR_WT_BIT 5 /* Flip a random bit */
111 #define ERR_WT_BYTE 5 /* Substitute a random byte */
112 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
113 #define ERR_WT_FMT 2 /* Substitute "%s" */
114 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
115 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
117 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
118 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
120 struct time_adjustment {
121 nstime_t tv;
122 int is_negative;
125 typedef struct _chop_t {
126 int len_begin;
127 int off_begin_pos;
128 int off_begin_neg;
129 int len_end;
130 int off_end_pos;
131 int off_end_neg;
132 } chop_t;
135 /* Table of user comments */
136 GTree *frames_user_comments;
137 GPtrArray *capture_comments;
139 #define MAX_SELECTIONS 512
140 static struct select_item selectfrm[MAX_SELECTIONS];
141 static guint max_selected;
142 static gboolean keep_em;
143 static int out_file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_UNKNOWN;
144 static int out_frame_type = -2; /* Leave frame type alone */
145 static gboolean verbose; /* Not so verbose */
146 static struct time_adjustment time_adj; /* no adjustment */
147 static nstime_t relative_time_window; /* de-dup time window */
148 static double err_prob = -1.0;
149 static nstime_t starttime;
150 static gboolean have_starttime;
151 static nstime_t stoptime;
152 static gboolean have_stoptime;
153 static gboolean check_startstop;
154 static gboolean rem_vlan;
155 static gboolean dup_detect;
156 static gboolean dup_detect_by_time;
157 static gboolean skip_radiotap;
158 static gboolean discard_all_secrets;
159 static gboolean discard_cap_comments;
160 static gboolean set_unused;
161 static gboolean discard_pkt_comments;
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 guint32 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(guint8 *buf);
178 static void handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
179 const wtap_packet_header *in_phdr, guint8 **buf,
180 gboolean adjlen);
182 static gchar *
183 abs_time_to_str_with_sec_resolution(const nstime_t *abs_time)
185 struct tm *tmp;
186 gchar *buf = (gchar *)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 gchar *
206 fileset_get_filename_by_pattern(guint idx, const wtap_rec *rec,
207 gchar *fprefix, gchar *fsuffix)
209 gchar filenum[5+1];
210 gchar *timestr;
211 gchar *abs_str;
213 snprintf(filenum, sizeof(filenum), "%05u", idx % RINGBUFFER_MAX_NUM_FILES);
214 if (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 gboolean
225 fileset_extract_prefix_suffix(const char *fname, gchar **fprefix, gchar **fsuffix)
227 char *pfx, *last_pathsep;
228 gchar *save_file;
230 save_file = g_strdup(fname);
231 if (save_file == NULL) {
232 fprintf(stderr, "editcap: Out of memory\n");
233 return FALSE;
236 last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
237 pfx = strrchr(save_file,'.');
238 if (pfx != NULL && (last_pathsep == NULL || pfx > last_pathsep)) {
239 /* The pathname has a "." in it, and it's in the last component
240 * of the pathname (because there is either only one component,
241 * i.e. last_pathsep is null as there are no path separators,
242 * or the "." is after the path separator before the last
243 * component.
245 * Treat it as a separator between the rest of the file name and
246 * the file name suffix, and arrange that the names given to the
247 * ring buffer files have the specified suffix, i.e. put the
248 * changing part of the name *before* the suffix. */
249 pfx[0] = '\0';
250 *fprefix = g_strdup(save_file);
251 pfx[0] = '.'; /* restore capfile_name */
252 *fsuffix = g_strdup(pfx);
253 } else {
254 /* Either there's no "." in the pathname, or it's in a directory
255 * component, so the last component has no suffix. */
256 *fprefix = g_strdup(save_file);
257 *fsuffix = NULL;
259 g_free(save_file);
260 return TRUE;
263 /* Add a selection item, a simple parser for now */
264 static gboolean
265 add_selection(char *sel, guint* max_selection)
267 char *locn;
268 char *next;
270 if (max_selected >= MAX_SELECTIONS) {
271 /* Let the user know we stopped selecting */
272 fprintf(stderr, "Out of room for packet selections.\n");
273 return FALSE;
276 if (verbose)
277 fprintf(stderr, "Add_Selected: %s\n", sel);
279 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
280 if (verbose)
281 fprintf(stderr, "Not inclusive ...");
283 selectfrm[max_selected].inclusive = FALSE;
284 selectfrm[max_selected].first = get_guint32(sel, "packet number");
285 if (selectfrm[max_selected].first > *max_selection)
286 *max_selection = selectfrm[max_selected].first;
288 if (verbose)
289 fprintf(stderr, " %u\n", selectfrm[max_selected].first);
290 } else {
291 if (verbose)
292 fprintf(stderr, "Inclusive ...");
294 *locn = '\0'; /* split the range */
295 next = locn + 1;
296 selectfrm[max_selected].inclusive = TRUE;
297 selectfrm[max_selected].first = get_guint32(sel, "beginning of packet range");
298 selectfrm[max_selected].second = get_guint32(next, "end of packet range");
300 if (selectfrm[max_selected].second == 0)
302 /* Not a valid number, presume all */
303 selectfrm[max_selected].second = *max_selection = G_MAXUINT;
305 else if (selectfrm[max_selected].second > *max_selection)
306 *max_selection = selectfrm[max_selected].second;
308 if (verbose)
309 fprintf(stderr, " %u, %u\n", selectfrm[max_selected].first,
310 selectfrm[max_selected].second);
313 max_selected++;
314 return TRUE;
317 /* Was the packet selected? */
319 static gboolean
320 selected(guint recno)
322 guint i;
324 for (i = 0; i < max_selected; i++) {
325 if (selectfrm[i].inclusive) {
326 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
327 return TRUE;
328 } else {
329 if (recno == selectfrm[i].first)
330 return TRUE;
334 return FALSE;
337 static gboolean
338 set_time_adjustment(char *optarg_str_p)
340 char *frac, *end;
341 long val;
342 size_t frac_digits;
344 if (!optarg_str_p)
345 return TRUE;
347 /* skip leading whitespace */
348 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
349 optarg_str_p++;
351 /* check for a negative adjustment */
352 if (*optarg_str_p == '-') {
353 time_adj.is_negative = 1;
354 optarg_str_p++;
357 /* collect whole number of seconds, if any */
358 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
359 val = 0;
360 frac = optarg_str_p;
361 } else {
362 val = strtol(optarg_str_p, &frac, 10);
363 if (frac == NULL || frac == optarg_str_p
364 || val == LONG_MIN || val == LONG_MAX) {
365 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
366 optarg_str_p);
367 return FALSE;
369 if (val < 0) { /* implies '--' since we caught '-' above */
370 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
371 optarg_str_p);
372 return FALSE;
375 time_adj.tv.secs = val;
377 /* now collect the partial seconds, if any */
378 if (*frac != '\0') { /* chars left, so get fractional part */
379 val = strtol(&(frac[1]), &end, 10);
380 /* if more than 9 fractional digits truncate to 9 */
381 if ((end - &(frac[1])) > 9) {
382 frac[10] = 't'; /* 't' for truncate */
383 val = strtol(&(frac[1]), &end, 10);
385 if (*frac != '.' || end == NULL || end == frac || val < 0
386 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
387 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
388 optarg_str_p);
389 return FALSE;
391 } else {
392 return TRUE; /* no fractional digits */
395 /* adjust fractional portion from fractional to numerator
396 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
397 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
398 while(frac_digits < 9) { /* this is frac of 10^9 */
399 val *= 10;
400 frac_digits++;
403 time_adj.tv.nsecs = (int)val;
404 return TRUE;
407 static gboolean
408 set_strict_time_adj(char *optarg_str_p)
410 char *frac, *end;
411 long val;
412 size_t frac_digits;
414 if (!optarg_str_p)
415 return TRUE;
417 /* skip leading whitespace */
418 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
419 optarg_str_p++;
422 * check for a negative adjustment
423 * A negative strict adjustment value is a flag
424 * to adjust all frames by the specified delta time.
426 if (*optarg_str_p == '-') {
427 strict_time_adj.is_negative = 1;
428 optarg_str_p++;
431 /* collect whole number of seconds, if any */
432 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
433 val = 0;
434 frac = optarg_str_p;
435 } else {
436 val = strtol(optarg_str_p, &frac, 10);
437 if (frac == NULL || frac == optarg_str_p
438 || val == LONG_MIN || val == LONG_MAX) {
439 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
440 optarg_str_p);
441 return FALSE;
443 if (val < 0) { /* implies '--' since we caught '-' above */
444 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
445 optarg_str_p);
446 return FALSE;
449 strict_time_adj.tv.secs = val;
451 /* now collect the partial seconds, if any */
452 if (*frac != '\0') { /* chars left, so get fractional part */
453 val = strtol(&(frac[1]), &end, 10);
454 /* if more than 9 fractional digits truncate to 9 */
455 if ((end - &(frac[1])) > 9) {
456 frac[10] = 't'; /* 't' for truncate */
457 val = strtol(&(frac[1]), &end, 10);
459 if (*frac != '.' || end == NULL || end == frac || val < 0
460 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
461 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
462 optarg_str_p);
463 return FALSE;
465 } else {
466 return TRUE; /* no fractional digits */
469 /* adjust fractional portion from fractional to numerator
470 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
471 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
472 while(frac_digits < 9) { /* this is frac of 10^9 */
473 val *= 10;
474 frac_digits++;
477 strict_time_adj.tv.nsecs = (int)val;
478 return TRUE;
481 static gboolean
482 set_rel_time(char *optarg_str_p)
484 char *frac, *end;
485 long val;
486 size_t frac_digits;
488 if (!optarg_str_p)
489 return TRUE;
491 /* skip leading whitespace */
492 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
493 optarg_str_p++;
495 /* ignore negative adjustment */
496 if (*optarg_str_p == '-')
497 optarg_str_p++;
499 /* collect whole number of seconds, if any */
500 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
501 val = 0;
502 frac = optarg_str_p;
503 } else {
504 val = strtol(optarg_str_p, &frac, 10);
505 if (frac == NULL || frac == optarg_str_p
506 || val == LONG_MIN || val == LONG_MAX) {
507 fprintf(stderr, "1: editcap: \"%s\" isn't a valid rel time value\n",
508 optarg_str_p);
509 return FALSE;
511 if (val < 0) { /* implies '--' since we caught '-' above */
512 fprintf(stderr, "2: editcap: \"%s\" isn't a valid rel time value\n",
513 optarg_str_p);
514 return FALSE;
517 relative_time_window.secs = val;
519 /* now collect the partial seconds, if any */
520 if (*frac != '\0') { /* chars left, so get fractional part */
521 val = strtol(&(frac[1]), &end, 10);
522 /* if more than 9 fractional digits truncate to 9 */
523 if ((end - &(frac[1])) > 9) {
524 frac[10] = 't'; /* 't' for truncate */
525 val = strtol(&(frac[1]), &end, 10);
527 if (*frac != '.' || end == NULL || end == frac || val < 0
528 || val >= ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
529 fprintf(stderr, "3: editcap: \"%s\" isn't a valid rel time value\n",
530 optarg_str_p);
531 return FALSE;
533 } else {
534 return TRUE; /* no fractional digits */
537 /* adjust fractional portion from fractional to numerator
538 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
539 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
540 while(frac_digits < 9) { /* this is frac of 10^9 */
541 val *= 10;
542 frac_digits++;
545 relative_time_window.nsecs = (int)val;
546 return TRUE;
549 #define SLL_ADDRLEN 8 /* length of address field */
550 struct sll_header {
551 uint16_t sll_pkttype; /* packet type */
552 uint16_t sll_hatype; /* link-layer address type */
553 uint16_t sll_halen; /* link-layer address length */
554 uint8_t sll_addr[SLL_ADDRLEN]; /* link-layer address */
555 uint16_t sll_protocol; /* protocol */
558 struct sll2_header {
559 uint16_t sll2_protocol; /* protocol */
560 uint16_t sll2_reserved_mbz; /* reserved - must be zero */
561 uint32_t sll2_if_index; /* 1-based interface index */
562 uint16_t sll2_hatype; /* link-layer address type */
563 uint8_t sll2_pkttype; /* packet type */
564 uint8_t sll2_halen; /* link-layer address length */
565 uint8_t sll2_addr[SLL_ADDRLEN]; /* link-layer address */
568 #define VLAN_SIZE 4
569 static void
570 sll_remove_vlan_info(guint8* fd, guint32* len) {
571 if (pntoh16(fd + offsetof(struct sll_header, sll_protocol)) == ETHERTYPE_VLAN) {
572 int rest_len;
573 /* point to start of vlan */
574 fd = fd + offsetof(struct sll_header, sll_protocol);
575 /* bytes to read after vlan info */
576 rest_len = *len - (offsetof(struct sll_header, sll_protocol) + VLAN_SIZE);
577 /* remove vlan info from packet */
578 memmove(fd, fd + VLAN_SIZE, rest_len);
579 *len -= 4;
585 static void
586 sll_set_unused_info(guint8* fd) {
587 guint32 ha_len;
588 ha_len = pntoh16(fd + offsetof(struct sll_header, sll_halen));
590 if (ha_len < SLL_ADDRLEN) {
591 int unused;
592 unused = SLL_ADDRLEN - ha_len;
593 /* point to end of sll_ddr */
594 fd = fd + offsetof(struct sll_header, sll_addr) + ha_len;
595 /* set zeros in the unused data */
596 memset(fd, 0, unused);
600 static void
601 sll2_set_unused_info(guint8* fd) {
602 guint32 ha_len;
603 ha_len = *(fd + offsetof(struct sll2_header, sll2_halen));
605 if (ha_len < SLL_ADDRLEN) {
606 int unused;
607 unused = SLL_ADDRLEN - ha_len;
608 /* point to end of sll2_addr */
609 fd = fd + offsetof(struct sll2_header, sll2_addr) + ha_len;
610 /* set zeros in the unused data */
611 memset(fd, 0, unused);
615 static void
616 remove_vlan_info(const wtap_packet_header *phdr, guint8* fd, guint32* len) {
617 switch (phdr->pkt_encap) {
618 case WTAP_ENCAP_SLL:
619 sll_remove_vlan_info(fd, len);
620 break;
621 default:
622 /* no support for current pkt_encap */
623 break;
627 static void
628 set_unused_info(const wtap_packet_header *phdr, guint8* fd) {
629 switch (phdr->pkt_encap) {
630 case WTAP_ENCAP_SLL:
631 sll_set_unused_info(fd);
632 break;
633 case WTAP_ENCAP_SLL2:
634 sll2_set_unused_info(fd);
635 break;
636 default:
637 /* no support for current pkt_encap */
638 break;
642 static gboolean
643 is_duplicate(guint8* fd, guint32 len) {
644 int i;
645 const struct ieee80211_radiotap_header* tap_header;
647 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
648 guint32 offset = ignored_bytes;
649 guint32 new_len;
650 guint8 *new_fd;
652 if (len <= ignored_bytes) {
653 offset = 0;
656 /* Get the size of radiotap header and use that as offset (-p option) */
657 if (skip_radiotap == TRUE) {
658 tap_header = (const struct ieee80211_radiotap_header*)fd;
659 offset = pletoh16(&tap_header->it_len);
660 if (offset >= len)
661 offset = 0;
664 new_fd = &fd[offset];
665 new_len = len - (offset);
667 cur_dup_entry++;
668 if (cur_dup_entry >= dup_window)
669 cur_dup_entry = 0;
671 /* Calculate our digest */
672 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
674 fd_hash[cur_dup_entry].len = len;
676 /* Look for duplicates */
677 for (i = 0; i < dup_window; i++) {
678 if (i == cur_dup_entry)
679 continue;
681 if (fd_hash[i].len == fd_hash[cur_dup_entry].len
682 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
683 return TRUE;
687 return FALSE;
690 static gboolean
691 is_duplicate_rel_time(guint8* fd, guint32 len, const nstime_t *current) {
692 int i;
694 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
695 guint32 offset = ignored_bytes;
696 guint32 new_len;
697 guint8 *new_fd;
699 if (len <= ignored_bytes) {
700 offset = 0;
703 new_fd = &fd[offset];
704 new_len = len - (offset);
706 cur_dup_entry++;
707 if (cur_dup_entry >= dup_window)
708 cur_dup_entry = 0;
710 /* Calculate our digest */
711 gcry_md_hash_buffer(GCRY_MD_MD5, fd_hash[cur_dup_entry].digest, new_fd, new_len);
713 fd_hash[cur_dup_entry].len = len;
714 fd_hash[cur_dup_entry].frame_time.secs = current->secs;
715 fd_hash[cur_dup_entry].frame_time.nsecs = current->nsecs;
718 * Look for relative time related duplicates.
719 * This is hopefully a reasonably efficient mechanism for
720 * finding duplicates by rel time in the fd_hash[] cache.
721 * We check starting from the most recently added hash
722 * entries and work backwards towards older packets.
723 * This approach allows the dup test to be terminated
724 * when the relative time of a cached entry is found to
725 * be beyond the dup time window.
727 * Of course this assumes that the input trace file is
728 * "well-formed" in the sense that the packet timestamps are
729 * in strict chronologically increasing order (which is NOT
730 * always the case!!).
732 * The fd_hash[] table was deliberately created large (1,000,000).
733 * Looking for time related duplicates in large trace files with
734 * non-fractional dup time window values can potentially take
735 * a long time to complete.
738 for (i = cur_dup_entry - 1;; i--) {
739 nstime_t delta;
740 int cmp;
742 if (i < 0)
743 i = dup_window - 1;
745 if (i == cur_dup_entry) {
747 * We've decremented back to where we started.
748 * Check no more!
750 break;
753 if (nstime_is_unset(&(fd_hash[i].frame_time))) {
755 * We've decremented to an unused fd_hash[] entry.
756 * Check no more!
758 break;
761 nstime_delta(&delta, current, &fd_hash[i].frame_time);
763 if (delta.secs < 0 || delta.nsecs < 0) {
765 * A negative delta implies that the current packet
766 * has an absolute timestamp less than the cached packet
767 * that it is being compared to. This is NOT a normal
768 * situation since trace files usually have packets in
769 * chronological order (oldest to newest).
771 * There are several possible ways to deal with this:
772 * 1. 'continue' dup checking with the next cached frame.
773 * 2. 'break' from looking for a duplicate of the current frame.
774 * 3. Take the absolute value of the delta and see if that
775 * falls within the specified dup time window.
777 * Currently this code does option 1. But it would pretty
778 * easy to add yet-another-editcap-option to select one of
779 * the other behaviors for dealing with out-of-sequence
780 * packets.
782 continue;
785 cmp = nstime_cmp(&delta, &relative_time_window);
787 if (cmp > 0) {
789 * The delta time indicates that we are now looking at
790 * cached packets beyond the specified dup time window.
791 * Check no more!
793 break;
794 } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len
795 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
796 return TRUE;
800 return FALSE;
803 static void
804 print_usage(FILE *output)
806 fprintf(output, "\n");
807 fprintf(output, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
808 fprintf(output, "\n");
809 fprintf(output, "<infile> and <outfile> must both be present; use '-' for stdin or stdout.\n");
810 fprintf(output, "A single packet or a range of packets can be selected.\n");
811 fprintf(output, "\n");
812 fprintf(output, "Packet selection:\n");
813 fprintf(output, " -r keep the selected packets; default is to delete them.\n");
814 fprintf(output, " -A <start time> only read packets whose timestamp is after (or equal\n");
815 fprintf(output, " to) the given time.\n");
816 fprintf(output, " -B <stop time> only read packets whose timestamp is before the\n");
817 fprintf(output, " given time.\n");
818 fprintf(output, " Time format for -A/-B options is\n");
819 fprintf(output, " YYYY-MM-DDThh:mm:ss[.nnnnnnnnn][Z|+-hh:mm]\n");
820 fprintf(output, " Unix epoch timestamps are also supported.\n");
821 fprintf(output, "\n");
822 fprintf(output, "Duplicate packet removal:\n");
823 fprintf(output, " --novlan remove vlan info from packets before checking for duplicates.\n");
824 fprintf(output, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH);
825 fprintf(output, " -D <dup window> remove packet if duplicate; configurable <dup window>.\n");
826 fprintf(output, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH);
827 fprintf(output, " NOTE: A <dup window> of 0 with -V (verbose option) is\n");
828 fprintf(output, " useful to print MD5 hashes.\n");
829 fprintf(output, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
830 fprintf(output, " LESS THAN <dup time window> prior to current packet.\n");
831 fprintf(output, " A <dup time window> is specified in relative seconds\n");
832 fprintf(output, " (e.g. 0.000001).\n");
833 fprintf(output, " NOTE: The use of the 'Duplicate packet removal' options with\n");
834 fprintf(output, " other editcap options except -V may not always work as expected.\n");
835 fprintf(output, " Specifically the -r, -t or -S options will very likely NOT have the\n");
836 fprintf(output, " desired effect if combined with the -d, -D or -w.\n");
837 fprintf(output, " --skip-radiotap-header skip radiotap header when checking for packet duplicates.\n");
838 fprintf(output, " Useful when processing packets captured by multiple radios\n");
839 fprintf(output, " on the same channel in the vicinity of each other.\n");
840 fprintf(output, " --set-unused set unused byts to zero in sll link addr.\n");
841 fprintf(output, "\n");
842 fprintf(output, "Packet manipulation:\n");
843 fprintf(output, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
844 fprintf(output, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
845 fprintf(output, " chop at the packet beginning, negative values at the\n");
846 fprintf(output, " packet end. If an optional offset precedes the length,\n");
847 fprintf(output, " then the bytes chopped will be offset from that value.\n");
848 fprintf(output, " Positive offsets are from the packet beginning,\n");
849 fprintf(output, " negative offsets are from the packet end. You can use\n");
850 fprintf(output, " this option more than once, allowing up to 2 chopping\n");
851 fprintf(output, " regions within a packet provided that at least 1\n");
852 fprintf(output, " choplen is positive and at least 1 is negative.\n");
853 fprintf(output, " -L adjust the frame (i.e. reported) length when chopping\n");
854 fprintf(output, " and/or snapping.\n");
855 fprintf(output, " -t <time adjustment> adjust the timestamp of each packet.\n");
856 fprintf(output, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
857 fprintf(output, " -S <strict adjustment> adjust timestamp of packets if necessary to ensure\n");
858 fprintf(output, " strict chronological increasing order. The <strict\n");
859 fprintf(output, " adjustment> is specified in relative seconds with\n");
860 fprintf(output, " values of 0 or 0.000001 being the most reasonable.\n");
861 fprintf(output, " A negative adjustment value will modify timestamps so\n");
862 fprintf(output, " that each packet's delta time is the absolute value\n");
863 fprintf(output, " of the adjustment specified. A value of -0 will set\n");
864 fprintf(output, " all packets to the timestamp of the first packet.\n");
865 fprintf(output, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
866 fprintf(output, " a particular packet byte will be randomly changed.\n");
867 fprintf(output, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
868 fprintf(output, " beginning of the packet. This allows one to preserve some\n");
869 fprintf(output, " bytes, in order to have some headers untouched.\n");
870 fprintf(output, " --seed <seed> When used in conjunction with -E, set the seed to use for\n");
871 fprintf(output, " the pseudo-random number generator. This allows one to\n");
872 fprintf(output, " repeat a particular sequence of errors.\n");
873 fprintf(output, " -I <bytes to ignore> ignore the specified number of bytes at the beginning\n");
874 fprintf(output, " of the frame during MD5 hash calculation, unless the\n");
875 fprintf(output, " frame is too short, then the full frame is used.\n");
876 fprintf(output, " Useful to remove duplicated packets taken on\n");
877 fprintf(output, " several routers (different mac addresses for\n");
878 fprintf(output, " example).\n");
879 fprintf(output, " e.g. -I 26 in case of Ether/IP will ignore\n");
880 fprintf(output, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
881 fprintf(output, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
882 fprintf(output, "\n");
883 fprintf(output, "Output File(s):\n");
884 fprintf(output, " -c <packets per file> split the packet output to different files based on\n");
885 fprintf(output, " uniform packet counts with a maximum of\n");
886 fprintf(output, " <packets per file> each.\n");
887 fprintf(output, " -i <seconds per file> split the packet output to different files based on\n");
888 fprintf(output, " uniform time intervals with a maximum of\n");
889 fprintf(output, " <seconds per file> each.\n");
890 fprintf(output, " -F <capture type> set the output file type; default is pcapng.\n");
891 fprintf(output, " An empty \"-F\" option will list the file types.\n");
892 fprintf(output, " -T <encap type> set the output file encapsulation type; default is the\n");
893 fprintf(output, " same as the input file. An empty \"-T\" option will\n");
894 fprintf(output, " list the encapsulation types.\n");
895 fprintf(output, " --inject-secrets <type>,<file> Insert decryption secrets from <file>. List\n");
896 fprintf(output, " supported secret types with \"--inject-secrets help\".\n");
897 fprintf(output, " --discard-all-secrets Discard all decryption secrets from the input file\n");
898 fprintf(output, " when writing the output file. Does not discard\n");
899 fprintf(output, " secrets added by \"--inject-secrets\" in the same\n");
900 fprintf(output, " command line.\n");
901 fprintf(output, " --capture-comment <comment>\n");
902 fprintf(output, " Add a capture file comment, if supported.\n");
903 fprintf(output, " --discard-capture-comment\n");
904 fprintf(output, " Discard capture file comments from the input file\n");
905 fprintf(output, " when writing the output file. Does not discard\n");
906 fprintf(output, " comments added by \"--capture-comment\" in the same\n");
907 fprintf(output, " command line.\n");
908 fprintf(output, " --discard-packet-comments\n");
909 fprintf(output, " Discard all packet comments from the input file\n");
910 fprintf(output, " when writing the output file. Does not discard\n");
911 fprintf(output, " comments added by \"-a\" in the same command line.\n");
912 fprintf(output, "\n");
913 fprintf(output, "Miscellaneous:\n");
914 fprintf(output, " -h, --help display this help and exit.\n");
915 fprintf(output, " -V verbose output.\n");
916 fprintf(output, " If -V is used with any of the 'Duplicate Packet\n");
917 fprintf(output, " Removal' options (-d, -D or -w) then Packet lengths\n");
918 fprintf(output, " and MD5 hashes are printed to standard-error.\n");
919 fprintf(output, " -v, --version print version information and exit.\n");
922 struct string_elem {
923 const char *sstr; /* The short string */
924 const char *lstr; /* The long string */
927 static gint
928 string_nat_compare(gconstpointer a, gconstpointer b)
930 return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
931 ((const struct string_elem *)b)->sstr);
934 static void
935 string_elem_print(gpointer data, gpointer stream_ptr)
937 fprintf((FILE *) stream_ptr, " %s - %s\n",
938 ((struct string_elem *)data)->sstr,
939 ((struct string_elem *)data)->lstr);
942 static void
943 list_capture_types(FILE *stream) {
944 GArray *writable_type_subtypes;
946 fprintf(stream, "editcap: The available capture file types for the \"-F\" flag are:\n");
947 writable_type_subtypes = wtap_get_writable_file_types_subtypes(FT_SORT_BY_NAME);
948 for (guint i = 0; i < writable_type_subtypes->len; i++) {
949 int ft = g_array_index(writable_type_subtypes, int, i);
950 fprintf(stream, " %s - %s\n", wtap_file_type_subtype_name(ft),
951 wtap_file_type_subtype_description(ft));
953 g_array_free(writable_type_subtypes, TRUE);
956 static void
957 list_encap_types(FILE *stream) {
958 int i;
959 struct string_elem *encaps;
960 GSList *list = NULL;
962 encaps = g_new(struct string_elem, WTAP_NUM_ENCAP_TYPES);
963 fprintf(stream, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
964 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
965 encaps[i].sstr = wtap_encap_name(i);
966 if (encaps[i].sstr != NULL) {
967 encaps[i].lstr = wtap_encap_description(i);
968 list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
971 g_slist_foreach(list, string_elem_print, stream);
972 g_slist_free(list);
973 g_free(encaps);
976 static void
977 list_secrets_types(FILE *stream)
979 for (guint i = 0; i < G_N_ELEMENTS(secrets_types); i++) {
980 fprintf(stream, " %s\n", secrets_types[i].str);
984 static guint32
985 lookup_secrets_type(const char *type)
987 for (guint i = 0; i < G_N_ELEMENTS(secrets_types); i++) {
988 if (!strcmp(secrets_types[i].str, type)) {
989 return secrets_types[i].id;
992 return 0;
995 static void
996 validate_secrets_file(const char *filename, guint32 secrets_type, const char *data)
998 if (secrets_type == SECRETS_TYPE_TLS) {
1000 * A key log file is unlikely going to look like either:
1001 * - a PEM-encoded private key file.
1002 * - a BER-encoded PKCS #12 file ("PFX file"). (Look for a Constructed
1003 * SEQUENCE tag, e.g. bytes 0x30 which happens to be ASCII '0'.)
1005 if (g_str_has_prefix(data, "-----BEGIN ") || data[0] == 0x30) {
1006 fprintf(stderr,
1007 "editcap: Warning: \"%s\" is not a key log file, but an unsupported private key file. Decryption will not work.\n",
1008 filename);
1013 static int
1014 framenum_compare(gconstpointer a, gconstpointer b, gpointer user_data _U_)
1016 if (GPOINTER_TO_UINT(a) < GPOINTER_TO_UINT(b))
1017 return -1;
1019 if (GPOINTER_TO_UINT(a) > GPOINTER_TO_UINT(b))
1020 return 1;
1022 return 0;
1026 * Report an error in command-line arguments.
1028 static void
1029 editcap_cmdarg_err(const char *msg_format, va_list ap)
1031 fprintf(stderr, "editcap: ");
1032 vfprintf(stderr, msg_format, ap);
1033 fprintf(stderr, "\n");
1037 * Report additional information for an error in command-line arguments.
1039 static void
1040 editcap_cmdarg_err_cont(const char *msg_format, va_list ap)
1042 vfprintf(stderr, msg_format, ap);
1043 fprintf(stderr, "\n");
1046 static wtap_dumper *
1047 editcap_dump_open(const char *filename, const wtap_dump_params *params,
1048 GArray *idbs_seen, int *err, gchar **err_info)
1050 wtap_dumper *pdh;
1052 if (strcmp(filename, "-") == 0) {
1053 /* Write to the standard output. */
1054 pdh = wtap_dump_open_stdout(out_file_type_subtype, WTAP_UNCOMPRESSED,
1055 params, err, err_info);
1056 } else {
1057 pdh = wtap_dump_open(filename, out_file_type_subtype, WTAP_UNCOMPRESSED,
1058 params, err, err_info);
1060 if (pdh == NULL)
1061 return NULL;
1064 * If the output file supports identifying the interfaces on which
1065 * packets arrive, add all the IDBs we've seen so far.
1067 * That mean that the abstract interface provided by libwiretap
1068 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1070 if (wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh),
1071 WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
1072 for (guint i = 0; i < idbs_seen->len; i++) {
1073 wtap_block_t if_data = g_array_index(idbs_seen, wtap_block_t, i);
1074 wtap_block_t if_data_copy;
1077 * Make a copy of this IDB, so that we can change the
1078 * encapsulation type without trashing the original.
1080 if_data_copy = wtap_block_make_copy(if_data);
1083 * If an encapsulation type was specified, override the
1084 * encapsulation type of the interface.
1086 if (out_frame_type != -2) {
1087 wtapng_if_descr_mandatory_t *if_mand;
1089 if_mand = (wtapng_if_descr_mandatory_t *)wtap_block_get_mandatory_data(if_data_copy);
1090 if_mand->wtap_encap = out_frame_type;
1094 * Add this possibly-modified IDB to the file to which
1095 * we're currently writing.
1097 if (!wtap_dump_add_idb(pdh, if_data_copy, err, err_info)) {
1098 int close_err;
1099 gchar *close_err_info;
1101 wtap_dump_close(pdh, NULL, &close_err, &close_err_info);
1102 g_free(close_err_info);
1103 wtap_block_unref(if_data_copy);
1104 return NULL;
1108 * Release the copy - wtap_dump_add_idb() makes its own copy.
1110 wtap_block_unref(if_data_copy);
1114 return pdh;
1117 static gboolean
1118 process_new_idbs(wtap *wth, wtap_dumper *pdh, GArray *idbs_seen,
1119 int *err, gchar **err_info)
1121 wtap_block_t if_data;
1123 while ((if_data = wtap_get_next_interface_description(wth)) != NULL) {
1125 * Only add interface blocks if the output file supports (meaning
1126 * *requires*) them.
1128 * That mean that the abstract interface provided by libwiretap
1129 * involves WTAP_BLOCK_IF_ID_AND_INFO blocks.
1131 if (pdh != NULL && wtap_file_type_subtype_supports_block(wtap_dump_file_type_subtype(pdh),
1132 WTAP_BLOCK_IF_ID_AND_INFO) != BLOCK_NOT_SUPPORTED) {
1133 wtap_block_t if_data_copy;
1136 * Make a copy of this IDB, so that we can change the
1137 * encapsulation type without trashing the original.
1139 if_data_copy = wtap_block_make_copy(if_data);
1142 * If an encapsulation type was specified, override the
1143 * encapsulation type of the interface.
1145 if (out_frame_type != -2) {
1146 wtapng_if_descr_mandatory_t *if_mand;
1148 if_mand = (wtapng_if_descr_mandatory_t *)wtap_block_get_mandatory_data(if_data_copy);
1149 if_mand->wtap_encap = out_frame_type;
1153 * Add this possibly-modified IDB to the file to which
1154 * we're currently writing.
1156 if (!wtap_dump_add_idb(pdh, if_data_copy, err, err_info))
1157 return FALSE;
1160 * Release the copy - wtap_dump_add_idb() makes its own copy.
1162 wtap_block_unref(if_data_copy);
1165 * Also add an unmodified copy to the set of IDBs we've seen,
1166 * in case we start writing to another file (which would be
1167 * of the same type as the current file, and thus will also
1168 * require interface IDs).
1170 if_data_copy = wtap_block_make_copy(if_data);
1171 g_array_append_val(idbs_seen, if_data_copy);
1174 return TRUE;
1178 main(int argc, char *argv[])
1180 char *configuration_init_error;
1181 static const struct report_message_routines editcap_report_routines = {
1182 failure_message,
1183 failure_message,
1184 open_failure_message,
1185 read_failure_message,
1186 write_failure_message,
1187 cfile_open_failure_message,
1188 cfile_dump_open_failure_message,
1189 cfile_read_failure_message,
1190 cfile_write_failure_message,
1191 cfile_close_failure_message
1193 wtap *wth = NULL;
1194 int i, j, read_err, write_err;
1195 gchar *read_err_info, *write_err_info;
1196 int opt;
1198 #define LONGOPT_NO_VLAN LONGOPT_BASE_APPLICATION+1
1199 #define LONGOPT_SKIP_RADIOTAP_HEADER LONGOPT_BASE_APPLICATION+2
1200 #define LONGOPT_SEED LONGOPT_BASE_APPLICATION+3
1201 #define LONGOPT_INJECT_SECRETS LONGOPT_BASE_APPLICATION+4
1202 #define LONGOPT_DISCARD_ALL_SECRETS LONGOPT_BASE_APPLICATION+5
1203 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+6
1204 #define LONGOPT_DISCARD_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+7
1205 #define LONGOPT_SET_UNUSED LONGOPT_BASE_APPLICATION+8
1206 #define LONGOPT_DISCARD_PACKET_COMMENTS LONGOPT_BASE_APPLICATION+9
1208 static const struct ws_option long_options[] = {
1209 {"novlan", ws_no_argument, NULL, LONGOPT_NO_VLAN},
1210 {"skip-radiotap-header", ws_no_argument, NULL, LONGOPT_SKIP_RADIOTAP_HEADER},
1211 {"seed", ws_required_argument, NULL, LONGOPT_SEED},
1212 {"inject-secrets", ws_required_argument, NULL, LONGOPT_INJECT_SECRETS},
1213 {"discard-all-secrets", ws_no_argument, NULL, LONGOPT_DISCARD_ALL_SECRETS},
1214 {"help", ws_no_argument, NULL, 'h'},
1215 {"version", ws_no_argument, NULL, 'v'},
1216 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
1217 {"discard-capture-comment", ws_no_argument, NULL, LONGOPT_DISCARD_CAPTURE_COMMENT},
1218 {"set-unused", ws_no_argument, NULL, LONGOPT_SET_UNUSED},
1219 {"discard-packet-comments", ws_no_argument, NULL, LONGOPT_DISCARD_PACKET_COMMENTS},
1220 {0, 0, 0, 0 }
1223 char *p;
1224 guint32 snaplen = 0; /* No limit */
1225 chop_t chop = {0, 0, 0, 0, 0, 0}; /* No chop */
1226 gboolean adjlen = FALSE;
1227 wtap_dumper *pdh = NULL;
1228 GArray *idbs_seen = NULL;
1229 unsigned int count = 1;
1230 unsigned int duplicate_count = 0;
1231 gint64 data_offset;
1232 int err_type;
1233 guint8 *buf;
1234 guint32 read_count = 0;
1235 guint32 split_packet_count = 0;
1236 int written_count = 0;
1237 char *filename = NULL;
1238 gboolean ts_okay;
1239 nstime_t secs_per_block = NSTIME_INIT_UNSET;
1240 int block_cnt = 0;
1241 nstime_t block_next = NSTIME_INIT_UNSET;
1242 gchar *fprefix = NULL;
1243 gchar *fsuffix = NULL;
1244 guint32 change_offset = 0;
1245 guint max_packet_number = 0;
1246 GArray *dsb_types = NULL;
1247 GPtrArray *dsb_filenames = NULL;
1248 wtap_rec read_rec;
1249 Buffer read_buf;
1250 const wtap_rec *rec;
1251 wtap_rec temp_rec;
1252 wtap_dump_params params = WTAP_DUMP_PARAMS_INIT;
1253 char *shb_user_appl;
1254 gboolean do_mutation;
1255 guint32 caplen;
1256 int ret = EXIT_SUCCESS;
1257 gboolean valid_seed = FALSE;
1258 unsigned int seed = 0;
1260 cmdarg_err_init(editcap_cmdarg_err, editcap_cmdarg_err_cont);
1261 memset(&read_rec, 0, sizeof *rec);
1263 /* Initialize log handler early so we can have proper logging during startup. */
1264 ws_log_init("editcap", vcmdarg_err);
1266 /* Early logging command-line initialization. */
1267 ws_log_parse_args(&argc, argv, vcmdarg_err, WS_EXIT_INVALID_OPTION);
1269 ws_noisy("Finished log init and parsing command line log arguments");
1271 #ifdef _WIN32
1272 create_app_running_mutex();
1273 #endif /* _WIN32 */
1275 /* Initialize the version information. */
1276 ws_init_version_info("Editcap", NULL, NULL);
1279 * Get credential information for later use.
1281 init_process_policies();
1284 * Attempt to get the pathname of the directory containing the
1285 * executable file.
1287 configuration_init_error = configuration_init(argv[0], NULL);
1288 if (configuration_init_error != NULL) {
1289 fprintf(stderr,
1290 "editcap: Can't get pathname of directory containing the editcap program: %s.\n",
1291 configuration_init_error);
1292 g_free(configuration_init_error);
1295 init_report_message("editcap", &editcap_report_routines);
1297 wtap_init(TRUE);
1299 /* Process the options */
1300 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) {
1301 switch (opt) {
1302 case LONGOPT_NO_VLAN:
1304 rem_vlan = TRUE;
1305 break;
1308 case LONGOPT_SKIP_RADIOTAP_HEADER:
1310 skip_radiotap = TRUE;
1311 break;
1314 case LONGOPT_SEED:
1316 if (sscanf(ws_optarg, "%u", &seed) != 1) {
1317 fprintf(stderr, "editcap: \"%s\" isn't a valid seed\n\n",
1318 ws_optarg);
1319 ret = WS_EXIT_INVALID_OPTION;
1320 goto clean_exit;
1322 valid_seed = TRUE;
1323 break;
1326 case LONGOPT_INJECT_SECRETS:
1328 guint32 secrets_type_id = 0;
1329 const char *secrets_filename = NULL;
1330 if (strcmp("help", ws_optarg) == 0) {
1331 list_secrets_types(stdout);
1332 goto clean_exit;
1334 gchar **splitted = g_strsplit(ws_optarg, ",", 2);
1335 if (splitted[0] && splitted[0][0] != '\0') {
1336 secrets_type_id = lookup_secrets_type(splitted[0]);
1337 if (secrets_type_id == 0) {
1338 fprintf(stderr, "editcap: \"%s\" isn't a valid secrets type\n", splitted[0]);
1339 g_strfreev(splitted);
1340 ret = WS_EXIT_INVALID_OPTION;
1341 goto clean_exit;
1343 secrets_filename = splitted[1];
1344 } else {
1345 fprintf(stderr, "editcap: no secrets type was specified for --inject-secrets\n");
1346 g_strfreev(splitted);
1347 ret = WS_EXIT_INVALID_OPTION;
1348 goto clean_exit;
1350 if (!dsb_filenames) {
1351 dsb_types = g_array_new(FALSE, FALSE, sizeof(guint32));
1352 dsb_filenames = g_ptr_array_new_with_free_func(g_free);
1354 g_array_append_val(dsb_types, secrets_type_id);
1355 g_ptr_array_add(dsb_filenames, g_strdup(secrets_filename));
1356 g_strfreev(splitted);
1357 break;
1360 case LONGOPT_DISCARD_ALL_SECRETS:
1362 discard_all_secrets = TRUE;
1363 break;
1366 case LONGOPT_CAPTURE_COMMENT:
1369 * Make sure this would fit in a pcapng option.
1371 * XXX - 65535 is the maximum size for an option in pcapng;
1372 * what if another capture file format supports larger
1373 * comments?
1375 if (strlen(ws_optarg) > 65535) {
1376 /* It doesn't fit. Tell the user and give up. */
1377 cmdarg_err("Capture comment %u is too large to save in a capture file.",
1378 capture_comments->len + 1);
1379 ret = WS_EXIT_INVALID_OPTION;
1380 goto clean_exit;
1383 /* pcapng supports multiple comments, so support them here too.
1385 if (!capture_comments) {
1386 capture_comments = g_ptr_array_new_with_free_func(g_free);
1388 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
1389 break;
1392 case LONGOPT_DISCARD_CAPTURE_COMMENT:
1394 discard_cap_comments = TRUE;
1395 break;
1398 case LONGOPT_SET_UNUSED:
1400 set_unused = TRUE;
1401 break;
1404 case LONGOPT_DISCARD_PACKET_COMMENTS:
1406 discard_pkt_comments = TRUE;
1407 break;
1410 case 'a':
1412 guint frame_number;
1413 gint string_start_index = 0;
1415 if ((sscanf(ws_optarg, "%u:%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1416 fprintf(stderr, "editcap: \"%s\" isn't a valid <frame>:<comment>\n\n",
1417 ws_optarg);
1418 ret = WS_EXIT_INVALID_OPTION;
1419 goto clean_exit;
1423 * Make sure this would fit in a pcapng option.
1425 * XXX - 65535 is the maximum size for an option in pcapng;
1426 * what if another capture file format supports larger
1427 * comments?
1429 if (strlen(ws_optarg+string_start_index) > 65535) {
1430 /* It doesn't fit. Tell the user and give up. */
1431 cmdarg_err("A comment for frame %u is too large to save in a capture file.",
1432 frame_number);
1433 ret = WS_EXIT_INVALID_OPTION;
1434 goto clean_exit;
1437 /* Lazily create the table */
1438 if (!frames_user_comments) {
1439 frames_user_comments = g_tree_new_full(framenum_compare, NULL, NULL, g_free);
1442 /* Insert this entry (framenum -> comment) */
1443 g_tree_replace(frames_user_comments, GUINT_TO_POINTER(frame_number), g_strdup(ws_optarg+string_start_index));
1444 break;
1447 case 'A':
1448 case 'B':
1450 nstime_t in_time;
1452 check_startstop = TRUE;
1453 if ((NULL != iso8601_to_nstime(&in_time, ws_optarg, ISO8601_DATETIME)) || (NULL != unix_epoch_to_nstime(&in_time, ws_optarg))) {
1454 if (opt == 'A') {
1455 nstime_copy(&starttime, &in_time);
1456 have_starttime = TRUE;
1457 } else {
1458 nstime_copy(&stoptime, &in_time);
1459 have_stoptime = TRUE;
1461 break;
1463 else {
1464 fprintf(stderr, "editcap: \"%s\" isn't a valid date and time\n\n",
1465 ws_optarg);
1466 ret = WS_EXIT_INVALID_OPTION;
1467 goto clean_exit;
1471 case 'c':
1472 split_packet_count = get_nonzero_guint32(ws_optarg, "packet count");
1473 break;
1475 case 'C':
1477 int choplen = 0, chopoff = 0;
1479 switch (sscanf(ws_optarg, "%d:%d", &chopoff, &choplen)) {
1480 case 1: /* only the chop length was specified */
1481 choplen = chopoff;
1482 chopoff = 0;
1483 break;
1485 case 2: /* both an offset and chop length was specified */
1486 break;
1488 default:
1489 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length or offset:length\n",
1490 ws_optarg);
1491 ret = WS_EXIT_INVALID_OPTION;
1492 goto clean_exit;
1493 break;
1496 if (choplen > 0) {
1497 chop.len_begin += choplen;
1498 if (chopoff > 0)
1499 chop.off_begin_pos += chopoff;
1500 else
1501 chop.off_begin_neg += chopoff;
1502 } else if (choplen < 0) {
1503 chop.len_end += choplen;
1504 if (chopoff > 0)
1505 chop.off_end_pos += chopoff;
1506 else
1507 chop.off_end_neg += chopoff;
1509 break;
1512 case 'd':
1513 dup_detect = TRUE;
1514 dup_detect_by_time = FALSE;
1515 dup_window = DEFAULT_DUP_DEPTH;
1516 break;
1518 case 'D':
1519 dup_detect = TRUE;
1520 dup_detect_by_time = FALSE;
1521 dup_window = get_guint32(ws_optarg, "duplicate window");
1522 if (dup_window > MAX_DUP_DEPTH) {
1523 fprintf(stderr, "editcap: \"%d\" duplicate window value must be between 0 and %d inclusive.\n",
1524 dup_window, MAX_DUP_DEPTH);
1525 ret = WS_EXIT_INVALID_OPTION;
1526 goto clean_exit;
1528 break;
1530 case 'E':
1531 err_prob = g_ascii_strtod(ws_optarg, &p);
1532 if (p == ws_optarg || err_prob < 0.0 || err_prob > 1.0) {
1533 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
1534 ws_optarg);
1535 ret = WS_EXIT_INVALID_OPTION;
1536 goto clean_exit;
1538 break;
1540 case 'F':
1541 out_file_type_subtype = wtap_name_to_file_type_subtype(ws_optarg);
1542 if (out_file_type_subtype < 0) {
1543 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
1544 ws_optarg);
1545 list_capture_types(stderr);
1546 ret = WS_EXIT_INVALID_OPTION;
1547 goto clean_exit;
1549 break;
1551 case 'h':
1552 show_help_header("Edit and/or translate the format of capture files.");
1553 print_usage(stdout);
1554 goto clean_exit;
1555 break;
1557 case 'i': /* break capture file based on time interval */
1559 double spb = get_positive_double(ws_optarg, "time interval");
1560 if (spb == 0.0) {
1561 cmdarg_err("The specified interval is zero");
1562 ret = WS_EXIT_INVALID_OPTION;
1563 goto clean_exit;
1566 double spb_int, spb_frac;
1567 spb_frac = modf(spb, &spb_int);
1568 secs_per_block.secs = (time_t) spb_int;
1569 secs_per_block.nsecs = (int) (NANOSECS_PER_SEC * spb_frac);
1571 break;
1573 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1574 ignored_bytes = get_guint32(ws_optarg, "number of bytes to ignore");
1575 break;
1577 case 'L':
1578 adjlen = TRUE;
1579 break;
1581 case 'o':
1582 change_offset = get_guint32(ws_optarg, "change offset");
1583 break;
1585 case 'r':
1586 if (keep_em) {
1587 cmdarg_err("-r was specified twice");
1588 ret = WS_EXIT_INVALID_OPTION;
1589 goto clean_exit;
1591 keep_em = TRUE;
1592 break;
1594 case 's':
1595 snaplen = get_nonzero_guint32(ws_optarg, "snapshot length");
1596 break;
1598 case 'S':
1599 if (!set_strict_time_adj(ws_optarg)) {
1600 ret = WS_EXIT_INVALID_OPTION;
1601 goto clean_exit;
1603 do_strict_time_adjustment = TRUE;
1604 break;
1606 case 't':
1607 if (!set_time_adjustment(ws_optarg)) {
1608 ret = WS_EXIT_INVALID_OPTION;
1609 goto clean_exit;
1611 break;
1613 case 'T':
1614 out_frame_type = wtap_name_to_encap(ws_optarg);
1615 if (out_frame_type < 0) {
1616 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
1617 ws_optarg);
1618 list_encap_types(stderr);
1619 ret = WS_EXIT_INVALID_OPTION;
1620 goto clean_exit;
1622 break;
1624 case 'V':
1625 if (verbose) {
1626 cmdarg_err("-V was specified twice");
1627 ret = WS_EXIT_INVALID_OPTION;
1628 goto clean_exit;
1630 verbose = TRUE;
1631 break;
1633 case 'v':
1634 show_version();
1635 goto clean_exit;
1636 break;
1638 case 'w':
1639 dup_detect = FALSE;
1640 dup_detect_by_time = TRUE;
1641 dup_window = MAX_DUP_DEPTH;
1642 if (!set_rel_time(ws_optarg)) {
1643 ret = WS_EXIT_INVALID_OPTION;
1644 goto clean_exit;
1646 break;
1648 case '?': /* Bad options if GNU getopt */
1649 case ':': /* missing option argument */
1650 switch(ws_optopt) {
1651 case'F':
1652 list_capture_types(stdout);
1653 break;
1654 case'T':
1655 list_encap_types(stdout);
1656 break;
1657 default:
1658 if (opt == '?') {
1659 fprintf(stderr, "editcap: invalid option -- '%c'\n", ws_optopt);
1660 } else {
1661 fprintf(stderr, "editcap: option requires an argument -- '%c'\n", ws_optopt);
1663 print_usage(stderr);
1664 ret = WS_EXIT_INVALID_OPTION;
1665 break;
1667 goto clean_exit;
1668 break;
1670 } /* processing command-line options */
1672 #ifdef DEBUG
1673 fprintf(stderr, "Optind = %i, argc = %i\n", ws_optind, argc);
1674 #endif
1676 if ((argc - ws_optind) < 2) {
1677 print_usage(stderr);
1678 ret = WS_EXIT_INVALID_OPTION;
1679 goto clean_exit;
1682 if (out_file_type_subtype == WTAP_FILE_TYPE_SUBTYPE_UNKNOWN) {
1683 /* default to pcapng */
1684 out_file_type_subtype = wtap_pcapng_file_type_subtype();
1687 if (err_prob >= 0.0) {
1688 if (!valid_seed) {
1689 seed = (unsigned int) (time(NULL) + ws_getpid());
1691 if (verbose) {
1692 fprintf(stderr, "Using seed %u\n", seed);
1694 srand(seed);
1697 if (have_starttime && have_stoptime &&
1698 nstime_cmp(&starttime, &stoptime) > 0) {
1699 fprintf(stderr, "editcap: start time is after the stop time\n");
1700 ret = WS_EXIT_INVALID_OPTION;
1701 goto clean_exit;
1704 if (split_packet_count != 0 && !nstime_is_unset(&secs_per_block)) {
1705 fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
1706 fprintf(stderr, "editcap: at the same time\n");
1707 ret = WS_EXIT_INVALID_OPTION;
1708 goto clean_exit;
1711 wth = wtap_open_offline(argv[ws_optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, FALSE);
1713 if (!wth) {
1714 cfile_open_failure_message(argv[ws_optind], read_err, read_err_info);
1715 ret = WS_EXIT_INVALID_FILE;
1716 goto clean_exit;
1719 if (verbose) {
1720 fprintf(stderr, "File %s is a %s capture file.\n", argv[ws_optind],
1721 wtap_file_type_subtype_description(wtap_file_type_subtype(wth)));
1724 if (skip_radiotap) {
1725 if (ignored_bytes != 0) {
1726 fprintf(stderr, "editcap: can't skip radiotap headers and %d byte(s)\n", ignored_bytes);
1727 fprintf(stderr, "editcap: at the start of packet at the same time\n");
1728 ret = WS_EXIT_INVALID_OPTION;
1729 goto clean_exit;
1732 if (wtap_file_encap(wth) != WTAP_ENCAP_IEEE_802_11_RADIOTAP) {
1733 fprintf(stderr, "editcap: can't skip radiotap header because input file has non-radiotap packets\n");
1734 if (wtap_file_encap(wth) == WTAP_ENCAP_PER_PACKET) {
1735 fprintf(stderr, "editcap: expected '%s', not all packets are necessarily that type\n",
1736 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP));
1737 } else {
1738 fprintf(stderr, "editcap: expected '%s', packets are '%s'\n",
1739 wtap_encap_description(WTAP_ENCAP_IEEE_802_11_RADIOTAP),
1740 wtap_encap_description(wtap_file_encap(wth)));
1742 ret = WS_EXIT_INVALID_OPTION;
1743 goto clean_exit;
1747 wtap_dump_params_init_no_idbs(&params, wth);
1750 * Discard any secrets we read in while opening the file.
1752 if (discard_all_secrets) {
1753 wtap_dump_params_discard_decryption_secrets(&params);
1757 * Discard capture file comments.
1759 if (discard_cap_comments) {
1760 for (guint b = 0; b < params.shb_hdrs->len; b++) {
1761 wtap_block_t shb = g_array_index(params.shb_hdrs, wtap_block_t, b);
1762 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(shb, OPT_COMMENT, 0)) {
1763 continue;
1769 * Add new capture file comments.
1771 if (capture_comments != NULL) {
1772 for (guint b = 0; b < params.shb_hdrs->len; b++) {
1773 wtap_block_t shb = g_array_index(params.shb_hdrs, wtap_block_t, b);
1774 for (guint c = 0; c < capture_comments->len; c++) {
1775 char *comment = (char *)g_ptr_array_index(capture_comments, c);
1776 wtap_block_add_string_option(shb, OPT_COMMENT, comment, strlen(comment));
1781 if (dsb_filenames) {
1782 for (guint k = 0; k < dsb_filenames->len; k++) {
1783 guint32 secrets_type_id = g_array_index(dsb_types, guint32, k);
1784 const char *secrets_filename = (const char *)g_ptr_array_index(dsb_filenames, k);
1785 char *data;
1786 gsize data_len;
1787 wtap_block_t block;
1788 wtapng_dsb_mandatory_t *dsb;
1789 GError *err = NULL;
1791 if (!g_file_get_contents(secrets_filename, &data, &data_len, &err)) {
1792 fprintf(stderr, "editcap: \"%s\" could not be read: %s\n", secrets_filename, err->message);
1793 g_clear_error(&err);
1794 ret = WS_EXIT_INVALID_OPTION;
1795 goto clean_exit;
1797 if (data_len == 0) {
1798 fprintf(stderr, "editcap: \"%s\" is an empty file, ignoring\n", secrets_filename);
1799 g_free(data);
1800 continue;
1802 if (data_len >= G_MAXINT) {
1803 fprintf(stderr, "editcap: \"%s\" is too large, ignoring\n", secrets_filename);
1804 g_free(data);
1805 continue;
1808 /* Warn for badly formatted files, but proceed anyway. */
1809 validate_secrets_file(secrets_filename, secrets_type_id, data);
1811 block = wtap_block_create(WTAP_BLOCK_DECRYPTION_SECRETS);
1812 dsb = (wtapng_dsb_mandatory_t *)wtap_block_get_mandatory_data(block);
1813 dsb->secrets_type = secrets_type_id;
1814 dsb->secrets_len = (guint)data_len;
1815 dsb->secrets_data = data;
1816 if (params.dsbs_initial == NULL) {
1817 params.dsbs_initial = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
1819 g_array_append_val(params.dsbs_initial, block);
1824 * If an encapsulation type was specified, override the encapsulation
1825 * type of the input file.
1827 if (out_frame_type != -2)
1828 params.encap = out_frame_type;
1831 * If a snapshot length was specified, and it's less than the snapshot
1832 * length of the input file, override the snapshot length of the input
1833 * file.
1835 if (snaplen != 0 && snaplen < wtap_snapshot_length(wth))
1836 params.snaplen = snaplen;
1839 * Now process the arguments following the input and output file
1840 * names, if any; they specify packets to include/exclude.
1842 for (i = ws_optind + 2; i < argc; i++)
1843 if (add_selection(argv[i], &max_packet_number) == FALSE)
1844 break;
1846 if (keep_em && max_selected == 0) {
1847 fprintf(stderr, "editcap: must specify packets to keep when using -r\n");
1848 ret = WS_EXIT_INVALID_OPTION;
1849 goto clean_exit;
1852 if (!keep_em)
1853 max_packet_number = G_MAXUINT;
1855 if (dup_detect || dup_detect_by_time) {
1856 for (i = 0; i < dup_window; i++) {
1857 memset(&fd_hash[i].digest, 0, 16);
1858 fd_hash[i].len = 0;
1859 nstime_set_unset(&fd_hash[i].frame_time);
1863 /* Set up an array of all IDBs seen */
1864 idbs_seen = g_array_new(FALSE, FALSE, sizeof(wtap_block_t));
1866 /* Read all of the packets in turn */
1867 wtap_rec_init(&read_rec);
1868 ws_buffer_init(&read_buf, 1514);
1869 while (wtap_read(wth, &read_rec, &read_buf, &read_err, &read_err_info, &data_offset)) {
1871 * XXX - what about non-packet records in the file after this?
1872 * NRBs, DSBs, and ISBs are now written when wtap_dump_close() calls
1873 * pcapng_dump_finish(), and we handle IDBs below, but what about
1874 * custom blocks?
1876 if (max_packet_number <= read_count)
1877 break;
1879 read_count++;
1881 rec = &read_rec;
1883 /* Extra actions for the first packet */
1884 if (read_count == 1) {
1885 if (split_packet_count != 0 || !nstime_is_unset(&secs_per_block)) {
1886 if (!fileset_extract_prefix_suffix(argv[ws_optind+1], &fprefix, &fsuffix)) {
1887 ret = CANT_EXTRACT_PREFIX;
1888 goto clean_exit;
1891 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
1892 } else {
1893 filename = g_strdup(argv[ws_optind+1]);
1895 ws_assert(filename);
1897 /* If we don't have an application name add one */
1898 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) {
1899 wtap_block_add_string_option_format(g_array_index(params.shb_hdrs, wtap_block_t, 0), OPT_SHB_USERAPPL, "%s", get_appname_and_version());
1902 pdh = editcap_dump_open(filename, &params, idbs_seen, &write_err,
1903 &write_err_info);
1905 if (pdh == NULL) {
1906 cfile_dump_open_failure_message(filename,
1907 write_err, write_err_info,
1908 out_file_type_subtype);
1909 ret = WS_EXIT_INVALID_FILE;
1910 goto clean_exit;
1912 } /* first packet only handling */
1915 * Process whatever IDBs we haven't seen yet.
1917 if (!process_new_idbs(wth, pdh, idbs_seen, &write_err, &write_err_info)) {
1918 cfile_write_failure_message(argv[ws_optind], filename,
1919 write_err, write_err_info,
1920 read_count,
1921 out_file_type_subtype);
1922 ret = DUMP_ERROR;
1925 * Close the dump file, but don't report an error
1926 * or set the exit code, as we've already reported
1927 * an error.
1929 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
1930 goto clean_exit;
1933 buf = ws_buffer_start_ptr(&read_buf);
1936 * Not all packets have time stamps. Only process the time
1937 * stamp if we have one.
1939 if (rec->presence_flags & WTAP_HAS_TS) {
1940 if (!nstime_is_unset(&secs_per_block)) {
1941 if (nstime_is_unset(&block_next)) {
1942 block_next = rec->ts;
1943 nstime_add(&block_next, &secs_per_block);
1945 while (nstime_cmp(&rec->ts, &block_next) > 0) { /* time for the next file */
1947 /* We presumably want to write the DSBs from files given
1948 * on the command line to every file.
1950 wtap_block_array_ref(params.dsbs_initial);
1951 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
1952 cfile_close_failure_message(filename, write_err,
1953 write_err_info);
1954 ret = WRITE_ERROR;
1955 goto clean_exit;
1957 g_free(filename);
1958 /* Use the interval start time for the filename. */
1959 temp_rec = *rec;
1960 temp_rec.ts = block_next;
1961 filename = fileset_get_filename_by_pattern(block_cnt++, &temp_rec, fprefix, fsuffix);
1962 ws_assert(filename);
1963 nstime_add(&block_next, &secs_per_block); /* reset for next interval */
1965 if (verbose)
1966 fprintf(stderr, "Continuing writing in file %s\n", filename);
1968 pdh = editcap_dump_open(filename, &params, idbs_seen,
1969 &write_err, &write_err_info);
1971 if (pdh == NULL) {
1972 cfile_dump_open_failure_message(filename,
1973 write_err,
1974 write_err_info,
1975 out_file_type_subtype);
1976 ret = WS_EXIT_INVALID_FILE;
1977 goto clean_exit;
1981 } /* time stamp handling */
1983 if (split_packet_count != 0) {
1984 /* time for the next file? */
1985 if (written_count > 0 && (written_count % split_packet_count) == 0) {
1987 /* We presumably want to write the DSBs from files given
1988 * on the command line to every file.
1990 wtap_block_array_ref(params.dsbs_initial);
1991 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
1992 cfile_close_failure_message(filename, write_err,
1993 write_err_info);
1994 ret = WRITE_ERROR;
1995 goto clean_exit;
1998 g_free(filename);
1999 filename = fileset_get_filename_by_pattern(block_cnt++, rec, fprefix, fsuffix);
2000 ws_assert(filename);
2002 if (verbose)
2003 fprintf(stderr, "Continuing writing in file %s\n", filename);
2005 pdh = editcap_dump_open(filename, &params, idbs_seen,
2006 &write_err, &write_err_info);
2007 if (pdh == NULL) {
2008 cfile_dump_open_failure_message(filename,
2009 write_err, write_err_info,
2010 out_file_type_subtype);
2011 ret = WS_EXIT_INVALID_FILE;
2012 goto clean_exit;
2015 } /* split packet handling */
2017 if (check_startstop) {
2018 ts_okay = FALSE;
2020 * Is the packet in the selected timeframe?
2021 * If the packet has no time stamp, the answer is "no".
2023 if (rec->presence_flags & WTAP_HAS_TS) {
2024 if (have_starttime && have_stoptime) {
2025 ts_okay = nstime_cmp(&rec->ts, &starttime) >= 0 &&
2026 nstime_cmp(&rec->ts, &stoptime) < 0;
2027 } else if (have_starttime) {
2028 ts_okay = nstime_cmp(&rec->ts, &starttime) >= 0;
2029 } else if (have_stoptime) {
2030 ts_okay = nstime_cmp(&rec->ts, &stoptime) < 0;
2033 } else {
2035 * No selected timeframe, so all packets are "in the
2036 * selected timeframe".
2038 ts_okay = TRUE;
2041 if (ts_okay && ((!selected(count) && !keep_em)
2042 || (selected(count) && keep_em))) {
2044 if (verbose && !dup_detect && !dup_detect_by_time)
2045 fprintf(stderr, "Packet: %u\n", count);
2047 /* We simply write it, perhaps after truncating it; we could
2048 * do other things, like modify it. */
2050 rec = &read_rec;
2052 if (rec->presence_flags & WTAP_HAS_TS) {
2053 /* Do we adjust timestamps to ensure strict chronological
2054 * order? */
2055 if (do_strict_time_adjustment) {
2056 if (previous_time.secs || previous_time.nsecs) {
2057 if (!strict_time_adj.is_negative) {
2058 nstime_t current;
2059 nstime_t delta;
2061 current = rec->ts;
2063 nstime_delta(&delta, &current, &previous_time);
2065 if (delta.secs < 0 || delta.nsecs < 0) {
2067 * A negative delta indicates that the current packet
2068 * has an absolute timestamp less than the previous packet
2069 * that it is being compared to. This is NOT a normal
2070 * situation since trace files usually have packets in
2071 * chronological order (oldest to newest).
2072 * Copy and change rather than modify
2073 * returned rec.
2075 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
2076 temp_rec = *rec;
2077 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
2078 temp_rec.ts.nsecs = previous_time.nsecs;
2079 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
2080 /* carry */
2081 temp_rec.ts.secs++;
2082 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2083 } else {
2084 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
2086 rec = &temp_rec;
2088 } else {
2090 * A negative strict time adjustment is requested.
2091 * Unconditionally set each timestamp to previous
2092 * packet's timestamp plus delta.
2093 * Copy and change rather than modify returned
2094 * rec.
2096 temp_rec = *rec;
2097 temp_rec.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
2098 temp_rec.ts.nsecs = previous_time.nsecs;
2099 if (temp_rec.ts.nsecs + strict_time_adj.tv.nsecs >= ONE_BILLION) {
2100 /* carry */
2101 temp_rec.ts.secs++;
2102 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
2103 } else {
2104 temp_rec.ts.nsecs += strict_time_adj.tv.nsecs;
2106 rec = &temp_rec;
2109 previous_time = rec->ts;
2112 if (time_adj.tv.secs != 0) {
2113 /* Copy and change rather than modify returned rec */
2114 temp_rec = *rec;
2115 if (time_adj.is_negative)
2116 temp_rec.ts.secs -= time_adj.tv.secs;
2117 else
2118 temp_rec.ts.secs += time_adj.tv.secs;
2119 rec = &temp_rec;
2122 if (time_adj.tv.nsecs != 0) {
2123 /* Copy and change rather than modify returned rec */
2124 temp_rec = *rec;
2125 if (time_adj.is_negative) { /* subtract */
2126 if (temp_rec.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
2127 temp_rec.ts.secs--;
2128 temp_rec.ts.nsecs += ONE_BILLION;
2130 temp_rec.ts.nsecs -= time_adj.tv.nsecs;
2131 } else { /* add */
2132 if (temp_rec.ts.nsecs + time_adj.tv.nsecs >= ONE_BILLION) {
2133 /* carry */
2134 temp_rec.ts.secs++;
2135 temp_rec.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
2136 } else {
2137 temp_rec.ts.nsecs += time_adj.tv.nsecs;
2140 rec = &temp_rec;
2142 } /* time stamp adjustment */
2144 if (rec->rec_type == REC_TYPE_PACKET) {
2145 if (snaplen != 0) {
2146 /* Limit capture length to snaplen */
2147 if (rec->rec_header.packet_header.caplen > snaplen) {
2148 /* Copy and change rather than modify returned rec */
2149 temp_rec = *rec;
2150 temp_rec.rec_header.packet_header.caplen = snaplen;
2151 rec = &temp_rec;
2153 /* If -L, also set reported length to snaplen */
2154 if (adjlen && rec->rec_header.packet_header.len > snaplen) {
2155 /* Copy and change rather than modify returned rec */
2156 temp_rec = *rec;
2157 temp_rec.rec_header.packet_header.len = snaplen;
2158 rec = &temp_rec;
2163 * If an encapsulation type was specified, override the
2164 * encapsulation type of the packet.
2165 * Copy and change rather than modify returned rec.
2167 if (out_frame_type != -2) {
2168 temp_rec = *rec;
2169 temp_rec.rec_header.packet_header.pkt_encap = out_frame_type;
2170 rec = &temp_rec;
2174 * CHOP
2175 * Copy and change rather than modify returned rec.
2177 temp_rec = *rec;
2178 handle_chopping(chop, &temp_rec.rec_header.packet_header,
2179 &rec->rec_header.packet_header, &buf,
2180 adjlen);
2181 rec = &temp_rec;
2183 /* set unused info */
2184 if (set_unused) {
2185 /* set unused bytes to zero so that duplicates check ignores unused bytes */
2186 set_unused_info(&rec->rec_header.packet_header, buf);
2189 /* remove vlan info */
2190 if (rem_vlan) {
2191 /* Copy and change rather than modify returned rec */
2192 temp_rec = *rec;
2193 remove_vlan_info(&rec->rec_header.packet_header, buf,
2194 &temp_rec.rec_header.packet_header.caplen);
2195 rec = &temp_rec;
2198 /* suppress duplicates by packet window */
2199 if (dup_detect) {
2200 if (is_duplicate(buf, rec->rec_header.packet_header.caplen)) {
2201 if (verbose) {
2202 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
2203 count,
2204 rec->rec_header.packet_header.caplen);
2205 for (i = 0; i < 16; i++)
2206 fprintf(stderr, "%02x",
2207 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2208 fprintf(stderr, "\n");
2210 duplicate_count++;
2211 count++;
2212 continue;
2213 } else {
2214 if (verbose) {
2215 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
2216 count,
2217 rec->rec_header.packet_header.caplen);
2218 for (i = 0; i < 16; i++)
2219 fprintf(stderr, "%02x",
2220 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2221 fprintf(stderr, "\n");
2224 } /* suppression of duplicates */
2226 if (rec->presence_flags & WTAP_HAS_TS) {
2227 /* suppress duplicates by time window */
2228 if (dup_detect_by_time) {
2229 nstime_t current;
2231 current.secs = rec->ts.secs;
2232 current.nsecs = rec->ts.nsecs;
2234 if (is_duplicate_rel_time(buf,
2235 rec->rec_header.packet_header.caplen,
2236 &current)) {
2237 if (verbose) {
2238 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
2239 count,
2240 rec->rec_header.packet_header.caplen);
2241 for (i = 0; i < 16; i++)
2242 fprintf(stderr, "%02x",
2243 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2244 fprintf(stderr, "\n");
2246 duplicate_count++;
2247 count++;
2248 continue;
2249 } else {
2250 if (verbose) {
2251 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
2252 count,
2253 rec->rec_header.packet_header.caplen);
2254 for (i = 0; i < 16; i++)
2255 fprintf(stderr, "%02x",
2256 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
2257 fprintf(stderr, "\n");
2261 } /* suppress duplicates by time window */
2264 /* Random error mutation */
2265 do_mutation = FALSE;
2266 caplen = 0;
2267 if (err_prob > 0.0) {
2268 switch (rec->rec_type) {
2270 case REC_TYPE_PACKET:
2271 caplen = rec->rec_header.packet_header.caplen;
2272 do_mutation = TRUE;
2273 break;
2275 case REC_TYPE_FT_SPECIFIC_EVENT:
2276 case REC_TYPE_FT_SPECIFIC_REPORT:
2277 caplen = rec->rec_header.ft_specific_header.record_len;
2278 do_mutation = TRUE;
2279 break;
2281 case REC_TYPE_SYSCALL:
2282 caplen = rec->rec_header.syscall_header.event_filelen;
2283 do_mutation = TRUE;
2284 break;
2286 case REC_TYPE_SYSTEMD_JOURNAL_EXPORT:
2287 caplen = rec->rec_header.systemd_journal_export_header.record_len;
2288 do_mutation = TRUE;
2289 break;
2292 if (change_offset > caplen) {
2293 fprintf(stderr, "change offset %u is longer than caplen %u in packet %u\n",
2294 change_offset, caplen, count);
2295 do_mutation = FALSE;
2299 if (do_mutation) {
2300 int real_data_start = 0;
2302 /* Protect non-protocol data */
2303 switch (rec->rec_type) {
2305 case REC_TYPE_PACKET:
2307 * XXX - any reason not to fuzz this part?
2309 if (rec->rec_header.packet_header.pkt_encap == WTAP_ENCAP_CATAPULT_DCT2000)
2310 real_data_start = find_dct2000_real_data(buf);
2311 break;
2314 real_data_start += change_offset;
2316 for (i = real_data_start; i < (int) caplen; i++) {
2317 if (rand() <= err_prob * RAND_MAX) {
2318 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
2320 if (err_type < ERR_WT_BIT) {
2321 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
2322 err_type = ERR_WT_TOTAL;
2323 } else {
2324 err_type -= ERR_WT_BYTE;
2327 if (err_type < ERR_WT_BYTE) {
2328 buf[i] = rand() / (RAND_MAX / 255 + 1);
2329 err_type = ERR_WT_TOTAL;
2330 } else {
2331 err_type -= ERR_WT_BYTE;
2334 if (err_type < ERR_WT_ALNUM) {
2335 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
2336 err_type = ERR_WT_TOTAL;
2337 } else {
2338 err_type -= ERR_WT_ALNUM;
2341 if (err_type < ERR_WT_FMT) {
2342 if ((unsigned int)i < caplen - 2)
2343 (void) g_strlcpy((char*) &buf[i], "%s", 2);
2344 err_type = ERR_WT_TOTAL;
2345 } else {
2346 err_type -= ERR_WT_FMT;
2349 if (err_type < ERR_WT_AA) {
2350 for (j = i; j < (int) caplen; j++)
2351 buf[j] = 0xAA;
2352 i = caplen;
2356 } /* random error mutation */
2358 /* Discard all packet comments when writing */
2359 if (discard_pkt_comments) {
2360 temp_rec = *rec;
2361 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(rec->block, OPT_COMMENT, 0)) {
2362 temp_rec.block_was_modified = TRUE;
2363 continue;
2365 rec = &temp_rec;
2368 /* Find a packet comment we may need to write */
2369 if (frames_user_comments) {
2370 const char *comment =
2371 (const char*)g_tree_lookup(frames_user_comments, GUINT_TO_POINTER(read_count));
2372 if (comment != NULL) {
2373 /* Copy and change rather than modify returned rec */
2374 temp_rec = *rec;
2376 /* Erase any existing comments before adding the new one */
2377 while (WTAP_OPTTYPE_SUCCESS == wtap_block_remove_nth_option_instance(rec->block, OPT_COMMENT, 0)) {
2378 temp_rec.block_was_modified = TRUE;
2379 continue;
2382 /* The comment is not modified by dumper, cast away. */
2383 wtap_block_add_string_option(rec->block, OPT_COMMENT, (char *)comment, strlen((char *)comment));
2384 temp_rec.block_was_modified = TRUE;
2385 rec = &temp_rec;
2386 } else {
2387 /* Copy and change rather than modify returned rec */
2388 temp_rec = *rec;
2389 temp_rec.block_was_modified = FALSE;
2390 rec = &temp_rec;
2394 if (discard_all_secrets) {
2396 * Discard any secrets we've read since the last packet
2397 * we wrote.
2399 wtap_dump_discard_decryption_secrets(pdh);
2402 /* Attempt to dump out current frame to the output file */
2403 if (!wtap_dump(pdh, rec, buf, &write_err, &write_err_info)) {
2404 cfile_write_failure_message(argv[ws_optind], filename,
2405 write_err, write_err_info,
2406 read_count,
2407 out_file_type_subtype);
2408 ret = DUMP_ERROR;
2411 * Close the dump file, but don't report an error
2412 * or set the exit code, as we've already reported
2413 * an error.
2415 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2416 goto clean_exit;
2418 written_count++;
2420 count++;
2421 wtap_rec_reset(&read_rec);
2423 wtap_rec_cleanup(&read_rec);
2424 ws_buffer_free(&read_buf);
2426 g_free(fprefix);
2427 g_free(fsuffix);
2429 if (verbose)
2430 fprintf(stderr, "Total selected: %d\n", written_count);
2432 if (read_err != 0) {
2433 /* Print a message noting that the read failed somewhere along the
2434 * line. */
2435 cfile_read_failure_message(argv[ws_optind], read_err, read_err_info);
2438 if (!pdh) {
2439 /* No valid packets found, open the outfile so we can write an
2440 * empty header */
2441 g_free (filename);
2442 filename = g_strdup(argv[ws_optind+1]);
2444 pdh = editcap_dump_open(filename, &params, idbs_seen, &write_err,
2445 &write_err_info);
2446 if (pdh == NULL) {
2447 cfile_dump_open_failure_message(filename,
2448 write_err, write_err_info,
2449 out_file_type_subtype);
2450 ret = WS_EXIT_INVALID_FILE;
2451 goto clean_exit;
2456 * Process whatever IDBs we haven't seen yet.
2458 if (!process_new_idbs(wth, pdh, idbs_seen, &write_err, &write_err_info)) {
2459 cfile_write_failure_message(argv[ws_optind], filename,
2460 write_err, write_err_info,
2461 read_count,
2462 out_file_type_subtype);
2463 ret = DUMP_ERROR;
2466 * Close the dump file, but don't report an error
2467 * or set the exit code, as we've already reported
2468 * an error.
2470 wtap_dump_close(pdh, NULL, &write_err, &write_err_info);
2471 goto clean_exit;
2474 if (!wtap_dump_close(pdh, NULL, &write_err, &write_err_info)) {
2475 cfile_close_failure_message(filename, write_err, write_err_info);
2476 ret = WRITE_ERROR;
2477 goto clean_exit;
2480 if (dup_detect) {
2481 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate window of %i packets.\n",
2482 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2483 plurality(duplicate_count, "", "s"), dup_window);
2484 } else if (dup_detect_by_time) {
2485 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
2486 count - 1, plurality(count - 1, "", "s"), duplicate_count,
2487 plurality(duplicate_count, "", "s"),
2488 (long)relative_time_window.secs,
2489 (long int)relative_time_window.nsecs);
2492 clean_exit:
2493 if (filename) {
2494 g_free(filename);
2496 if (frames_user_comments) {
2497 g_tree_destroy(frames_user_comments);
2499 if (dsb_filenames) {
2500 g_array_free(dsb_types, TRUE);
2501 g_ptr_array_free(dsb_filenames, TRUE);
2503 if (idbs_seen != NULL) {
2504 for (guint b = 0; b < idbs_seen->len; b++) {
2505 wtap_block_t if_data = g_array_index(idbs_seen, wtap_block_t, b);
2506 wtap_block_unref(if_data);
2508 g_array_free(idbs_seen, TRUE);
2510 g_free(params.idb_inf);
2511 wtap_dump_params_cleanup(&params);
2512 if (wth != NULL)
2513 wtap_close(wth);
2514 wtap_rec_reset(&read_rec);
2515 wtap_cleanup();
2516 free_progdirs();
2517 if (capture_comments != NULL) {
2518 g_ptr_array_free(capture_comments, TRUE);
2519 capture_comments = NULL;
2521 return ret;
2524 /* Skip meta-information read from file to return offset of real
2525 * protocol data */
2526 static int
2527 find_dct2000_real_data(guint8 *buf)
2529 int n = 0;
2531 for (n = 0; buf[n] != '\0'; n++); /* Context name */
2532 n++;
2533 n++; /* Context port number */
2534 for (; buf[n] != '\0'; n++); /* Timestamp */
2535 n++;
2536 for (; buf[n] != '\0'; n++); /* Protocol name */
2537 n++;
2538 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
2539 n++;
2540 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
2541 n++;
2542 n += 2; /* Direction & encap */
2544 return n;
2548 * We support up to 2 chopping regions in a single pass: one specified by the
2549 * positive chop length, and one by the negative chop length.
2551 static void
2552 handle_chopping(chop_t chop, wtap_packet_header *out_phdr,
2553 const wtap_packet_header *in_phdr, guint8 **buf,
2554 gboolean adjlen)
2556 /* If we're not chopping anything from one side, then the offset for that
2557 * side is meaningless. */
2558 if (chop.len_begin == 0)
2559 chop.off_begin_pos = chop.off_begin_neg = 0;
2560 if (chop.len_end == 0)
2561 chop.off_end_pos = chop.off_end_neg = 0;
2563 if (chop.off_begin_neg < 0) {
2564 chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
2565 chop.off_begin_neg = 0;
2567 if (chop.off_end_pos > 0) {
2568 chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
2569 chop.off_end_pos = 0;
2572 /* If we've crossed chopping regions, swap them */
2573 if (chop.len_begin && chop.len_end) {
2574 if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
2575 int tmp_len, tmp_off;
2577 tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
2578 tmp_len = -chop.len_end;
2580 chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
2581 chop.len_end = -chop.len_begin;
2583 chop.len_begin = tmp_len;
2584 chop.off_begin_pos = tmp_off;
2588 /* Make sure we don't chop off more than we have available */
2589 if (in_phdr->caplen < (guint32)(chop.off_begin_pos - chop.off_end_neg)) {
2590 chop.len_begin = 0;
2591 chop.len_end = 0;
2593 if ((guint32)(chop.len_begin - chop.len_end) >
2594 (in_phdr->caplen - (guint32)(chop.off_begin_pos - chop.off_end_neg))) {
2595 chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
2596 chop.len_end = 0;
2599 /* Handle chopping from the beginning. Note that if a beginning offset
2600 * was specified, we need to keep that piece */
2601 if (chop.len_begin > 0) {
2602 *out_phdr = *in_phdr;
2604 if (chop.off_begin_pos > 0) {
2605 memmove(*buf + chop.off_begin_pos,
2606 *buf + chop.off_begin_pos + chop.len_begin,
2607 out_phdr->caplen - (chop.off_begin_pos + chop.len_begin));
2608 } else {
2609 *buf += chop.len_begin;
2611 out_phdr->caplen -= chop.len_begin;
2613 if (adjlen) {
2614 if (in_phdr->len > (guint32)chop.len_begin)
2615 out_phdr->len -= chop.len_begin;
2616 else
2617 out_phdr->len = 0;
2619 in_phdr = out_phdr;
2622 /* Handle chopping from the end. Note that if an ending offset was
2623 * specified, we need to keep that piece */
2624 if (chop.len_end < 0) {
2625 *out_phdr = *in_phdr;
2627 if (chop.off_end_neg < 0) {
2628 memmove(*buf + (gint)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
2629 *buf + (gint)out_phdr->caplen + chop.off_end_neg,
2630 -chop.off_end_neg);
2632 out_phdr->caplen += chop.len_end;
2634 if (adjlen) {
2635 if (((signed int) in_phdr->len + chop.len_end) > 0)
2636 out_phdr->len += chop.len_end;
2637 else
2638 out_phdr->len = 0;
2640 /*in_phdr = out_phdr;*/
2645 * Editor modelines - https://www.wireshark.org/tools/modelines.html
2647 * Local variables:
2648 * c-basic-offset: 4
2649 * tab-width: 8
2650 * indent-tabs-mode: nil
2651 * End:
2653 * vi: set shiftwidth=4 tabstop=8 expandtab:
2654 * :indentSize=4:tabSize=8:noTabs=true: