1 /* Edit capture files. We can delete packets, adjust timestamps, or
2 * simply convert from one format to another format.
4 * Originally written by Richard Sharpe.
5 * Improved by Guy Harris.
6 * Further improved by Richard Sharpe.
8 * Copyright 2013, Richard Sharpe <realrichardsharpe[AT]gmail.com>
10 * Wireshark - Network traffic analyzer
11 * By Gerald Combs <gerald@wireshark.org>
12 * Copyright 1998 Gerald Combs
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License along
25 * with this program; if not, write to the Free Software Foundation, Inc.,
26 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
37 * Just make sure we include the prototype for strptime as well
38 * (needed for glibc 2.2) but make sure we do this only if not
57 #include <wiretap/wtap.h>
59 #include "epan/etypes.h"
61 #ifndef HAVE_GETOPT_LONG
62 #include "wsutil/wsgetopt.h"
66 #include <wsutil/unicode-utils.h>
67 #include <process.h> /* getpid */
68 #ifdef HAVE_WINSOCK2_H
74 # include "wsutil/strptime.h"
77 #include <wsutil/crash_info.h>
78 #include <wsutil/filesystem.h>
79 #include <wsutil/file_util.h>
80 #include <wsutil/md5.h>
81 #include <wsutil/plugins.h>
82 #include <wsutil/privileges.h>
83 #include <wsutil/report_err.h>
84 #include <wsutil/strnatcmp.h>
85 #include <wsutil/str_util.h>
86 #include <ws_version_info.h>
87 #include <wsutil/pint.h>
88 #include <wiretap/wtap_opttypes.h>
89 #include <wiretap/pcapng.h>
91 #include "ringbuffer.h" /* For RINGBUFFER_MAX_NUM_FILES */
94 * Some globals so we can pass things to various routines
103 * Duplicate frame detection
105 typedef struct _fd_hash_t {
106 md5_byte_t digest[16];
111 #define DEFAULT_DUP_DEPTH 5 /* Used with -d */
112 #define MAX_DUP_DEPTH 1000000 /* the maximum window (and actual size of fd_hash[]) for de-duplication */
114 static fd_hash_t fd_hash[MAX_DUP_DEPTH];
115 static int dup_window = DEFAULT_DUP_DEPTH;
116 static int cur_dup_entry = 0;
118 static int ignored_bytes = 0; /* Used with -I */
120 #define ONE_BILLION 1000000000
122 /* Weights of different errors we can introduce */
123 /* We should probably make these command-line arguments */
124 /* XXX - Should we add a bit-level error? */
125 #define ERR_WT_BIT 5 /* Flip a random bit */
126 #define ERR_WT_BYTE 5 /* Substitute a random byte */
127 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
128 #define ERR_WT_FMT 2 /* Substitute "%s" */
129 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
130 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
132 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
133 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
135 struct time_adjustment {
140 typedef struct _chop_t {
150 /* Table of user comments */
151 GTree *frames_user_comments = NULL;
153 #define MAX_SELECTIONS 512
154 static struct select_item selectfrm[MAX_SELECTIONS];
155 static guint max_selected = 0;
156 static int keep_em = 0;
157 #ifdef PCAP_NG_DEFAULT
158 static int out_file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcapng */
160 static int out_file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcap */
162 static int out_frame_type = -2; /* Leave frame type alone */
163 static int verbose = 0; /* Not so verbose */
164 static struct time_adjustment time_adj = {{0, 0}, 0}; /* no adjustment */
165 static nstime_t relative_time_window = {0, 0}; /* de-dup time window */
166 static double err_prob = 0.0;
167 static time_t starttime = 0;
168 static time_t stoptime = 0;
169 static gboolean check_startstop = FALSE;
170 static gboolean rem_vlan = FALSE;
171 static gboolean dup_detect = FALSE;
172 static gboolean dup_detect_by_time = FALSE;
174 static int do_strict_time_adjustment = FALSE;
175 static struct time_adjustment strict_time_adj = {{0, 0}, 0}; /* strict time adjustment */
176 static nstime_t previous_time = {0, 0}; /* previous time */
178 static int find_dct2000_real_data(guint8 *buf);
179 static void handle_chopping(chop_t chop, struct wtap_pkthdr *out_phdr,
180 const struct wtap_pkthdr *in_phdr, guint8 **buf,
184 abs_time_to_str_with_sec_resolution(const nstime_t *abs_time)
187 gchar *buf = (gchar *)g_malloc(16);
189 tmp = localtime(&abs_time->secs);
192 g_snprintf(buf, 16, "%d%02d%02d%02d%02d%02d",
207 fileset_get_filename_by_pattern(guint idx, const struct wtap_pkthdr *phdr,
208 gchar *fprefix, gchar *fsuffix)
214 g_snprintf(filenum, sizeof(filenum), "%05u", idx % RINGBUFFER_MAX_NUM_FILES);
215 if (phdr->presence_flags & WTAP_HAS_TS) {
216 timestr = abs_time_to_str_with_sec_resolution(&phdr->ts);
217 abs_str = g_strconcat(fprefix, "_", filenum, "_", timestr, fsuffix, NULL);
220 abs_str = g_strconcat(fprefix, "_", filenum, fsuffix, NULL);
226 fileset_extract_prefix_suffix(const char *fname, gchar **fprefix, gchar **fsuffix)
228 char *pfx, *last_pathsep;
231 save_file = g_strdup(fname);
232 if (save_file == NULL) {
233 fprintf(stderr, "editcap: Out of memory\n");
237 last_pathsep = strrchr(save_file, G_DIR_SEPARATOR);
238 pfx = strrchr(save_file,'.');
239 if (pfx != NULL && (last_pathsep == NULL || pfx > last_pathsep)) {
240 /* The pathname has a "." in it, and it's in the last component
241 * of the pathname (because there is either only one component,
242 * i.e. last_pathsep is null as there are no path separators,
243 * or the "." is after the path separator before the last
246 * Treat it as a separator between the rest of the file name and
247 * the file name suffix, and arrange that the names given to the
248 * ring buffer files have the specified suffix, i.e. put the
249 * changing part of the name *before* the suffix. */
251 *fprefix = g_strdup(save_file);
252 pfx[0] = '.'; /* restore capfile_name */
253 *fsuffix = g_strdup(pfx);
255 /* Either there's no "." in the pathname, or it's in a directory
256 * component, so the last component has no suffix. */
257 *fprefix = g_strdup(save_file);
264 /* Add a selection item, a simple parser for now */
266 add_selection(char *sel, guint* max_selection)
271 if (max_selected >= MAX_SELECTIONS) {
272 /* Let the user know we stopped selecting */
273 fprintf(stderr, "Out of room for packet selections!\n");
278 fprintf(stderr, "Add_Selected: %s\n", sel);
280 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
282 fprintf(stderr, "Not inclusive ...");
284 selectfrm[max_selected].inclusive = FALSE;
285 selectfrm[max_selected].first = (guint)strtoul(sel, NULL, 10);
286 if (selectfrm[max_selected].first < *max_selection)
287 *max_selection = selectfrm[max_selected].first;
290 fprintf(stderr, " %i\n", selectfrm[max_selected].first);
293 fprintf(stderr, "Inclusive ...");
296 selectfrm[max_selected].inclusive = TRUE;
297 selectfrm[max_selected].first = (guint)strtoul(sel, NULL, 10);
298 selectfrm[max_selected].second = (guint)strtoul(next, NULL, 10);
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;
309 fprintf(stderr, " %i, %i\n", selectfrm[max_selected].first,
310 selectfrm[max_selected].second);
317 /* Was the packet selected? */
320 selected(guint recno)
324 for (i = 0; i < max_selected; i++) {
325 if (selectfrm[i].inclusive) {
326 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
329 if (recno == selectfrm[i].first)
338 set_time_adjustment(char *optarg_str_p)
347 /* skip leading whitespace */
348 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
351 /* check for a negative adjustment */
352 if (*optarg_str_p == '-') {
353 time_adj.is_negative = 1;
357 /* collect whole number of seconds, if any */
358 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
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",
369 if (val < 0) { /* implies '--' since we caught '-' above */
370 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
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",
392 return; /* 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 */
403 time_adj.tv.nsecs = (int)val;
407 set_strict_time_adj(char *optarg_str_p)
416 /* skip leading whitespace */
417 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
421 * check for a negative adjustment
422 * A negative strict adjustment value is a flag
423 * to adjust all frames by the specifed delta time.
425 if (*optarg_str_p == '-') {
426 strict_time_adj.is_negative = 1;
430 /* collect whole number of seconds, if any */
431 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
435 val = strtol(optarg_str_p, &frac, 10);
436 if (frac == NULL || frac == optarg_str_p
437 || val == LONG_MIN || val == LONG_MAX) {
438 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
442 if (val < 0) { /* implies '--' since we caught '-' above */
443 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
448 strict_time_adj.tv.secs = val;
450 /* now collect the partial seconds, if any */
451 if (*frac != '\0') { /* chars left, so get fractional part */
452 val = strtol(&(frac[1]), &end, 10);
453 /* if more than 9 fractional digits truncate to 9 */
454 if ((end - &(frac[1])) > 9) {
455 frac[10] = 't'; /* 't' for truncate */
456 val = strtol(&(frac[1]), &end, 10);
458 if (*frac != '.' || end == NULL || end == frac || val < 0
459 || val > ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
460 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
465 return; /* no fractional digits */
468 /* adjust fractional portion from fractional to numerator
469 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
470 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
471 while(frac_digits < 9) { /* this is frac of 10^9 */
476 strict_time_adj.tv.nsecs = (int)val;
480 set_rel_time(char *optarg_str_p)
489 /* skip leading whitespace */
490 while (*optarg_str_p == ' ' || *optarg_str_p == '\t')
493 /* ignore negative adjustment */
494 if (*optarg_str_p == '-')
497 /* collect whole number of seconds, if any */
498 if (*optarg_str_p == '.') { /* only fractional (i.e., .5 is ok) */
502 val = strtol(optarg_str_p, &frac, 10);
503 if (frac == NULL || frac == optarg_str_p
504 || val == LONG_MIN || val == LONG_MAX) {
505 fprintf(stderr, "1: editcap: \"%s\" isn't a valid rel time value\n",
509 if (val < 0) { /* implies '--' since we caught '-' above */
510 fprintf(stderr, "2: editcap: \"%s\" isn't a valid rel time value\n",
515 relative_time_window.secs = val;
517 /* now collect the partial seconds, if any */
518 if (*frac != '\0') { /* chars left, so get fractional part */
519 val = strtol(&(frac[1]), &end, 10);
520 /* if more than 9 fractional digits truncate to 9 */
521 if ((end - &(frac[1])) > 9) {
522 frac[10] = 't'; /* 't' for truncate */
523 val = strtol(&(frac[1]), &end, 10);
525 if (*frac != '.' || end == NULL || end == frac || val < 0
526 || val > ONE_BILLION || val == LONG_MIN || val == LONG_MAX) {
527 fprintf(stderr, "3: editcap: \"%s\" isn't a valid rel time value\n",
532 return; /* no fractional digits */
535 /* adjust fractional portion from fractional to numerator
536 * e.g., in "1.5" from 5 to 500000000 since .5*10^9 = 500000000 */
537 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
538 while(frac_digits < 9) { /* this is frac of 10^9 */
543 relative_time_window.nsecs = (int)val;
546 #define LINUX_SLL_OFFSETP 14
549 sll_remove_vlan_info(guint8* fd, guint32* len) {
550 if (pntoh16(fd + LINUX_SLL_OFFSETP) == ETHERTYPE_VLAN) {
552 /* point to start of vlan */
553 fd = fd + LINUX_SLL_OFFSETP;
554 /* bytes to read after vlan info */
555 rest_len = *len - (LINUX_SLL_OFFSETP + VLAN_SIZE);
556 /* remove vlan info from packet */
557 memmove(fd, fd + VLAN_SIZE, rest_len);
563 remove_vlan_info(const struct wtap_pkthdr *phdr, guint8* fd, guint32* len) {
564 switch (phdr->pkt_encap) {
566 sll_remove_vlan_info(fd, len);
569 /* no support for current pkt_encap */
575 is_duplicate(guint8* fd, guint32 len) {
579 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
583 new_fd = &fd[ignored_bytes];
584 new_len = len - (ignored_bytes);
587 if (cur_dup_entry >= dup_window)
590 /* Calculate our digest */
592 md5_append(&ms, new_fd, new_len);
593 md5_finish(&ms, fd_hash[cur_dup_entry].digest);
595 fd_hash[cur_dup_entry].len = len;
597 /* Look for duplicates */
598 for (i = 0; i < dup_window; i++) {
599 if (i == cur_dup_entry)
602 if (fd_hash[i].len == fd_hash[cur_dup_entry].len
603 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
612 is_duplicate_rel_time(guint8* fd, guint32 len, const nstime_t *current) {
616 /*Hint to ignore some bytes at the start of the frame for the digest calculation(-I option) */
620 new_fd = &fd[ignored_bytes];
621 new_len = len - (ignored_bytes);
624 if (cur_dup_entry >= dup_window)
627 /* Calculate our digest */
629 md5_append(&ms, new_fd, new_len);
630 md5_finish(&ms, fd_hash[cur_dup_entry].digest);
632 fd_hash[cur_dup_entry].len = len;
633 fd_hash[cur_dup_entry].frame_time.secs = current->secs;
634 fd_hash[cur_dup_entry].frame_time.nsecs = current->nsecs;
637 * Look for relative time related duplicates.
638 * This is hopefully a reasonably efficient mechanism for
639 * finding duplicates by rel time in the fd_hash[] cache.
640 * We check starting from the most recently added hash
641 * entries and work backwards towards older packets.
642 * This approach allows the dup test to be terminated
643 * when the relative time of a cached entry is found to
644 * be beyond the dup time window.
646 * Of course this assumes that the input trace file is
647 * "well-formed" in the sense that the packet timestamps are
648 * in strict chronologically increasing order (which is NOT
649 * always the case!!).
651 * The fd_hash[] table was deliberately created large (1,000,000).
652 * Looking for time related duplicates in large trace files with
653 * non-fractional dup time window values can potentially take
654 * a long time to complete.
657 for (i = cur_dup_entry - 1;; i--) {
664 if (i == cur_dup_entry) {
666 * We've decremented back to where we started.
672 if (nstime_is_unset(&(fd_hash[i].frame_time))) {
674 * We've decremented to an unused fd_hash[] entry.
680 nstime_delta(&delta, current, &fd_hash[i].frame_time);
682 if (delta.secs < 0 || delta.nsecs < 0) {
684 * A negative delta implies that the current packet
685 * has an absolute timestamp less than the cached packet
686 * that it is being compared to. This is NOT a normal
687 * situation since trace files usually have packets in
688 * chronological order (oldest to newest).
690 * There are several possible ways to deal with this:
691 * 1. 'continue' dup checking with the next cached frame.
692 * 2. 'break' from looking for a duplicate of the current frame.
693 * 3. Take the absolute value of the delta and see if that
694 * falls within the specifed dup time window.
696 * Currently this code does option 1. But it would pretty
697 * easy to add yet-another-editcap-option to select one of
698 * the other behaviors for dealing with out-of-sequence
704 cmp = nstime_cmp(&delta, &relative_time_window);
708 * The delta time indicates that we are now looking at
709 * cached packets beyond the specified dup time window.
713 } else if (fd_hash[i].len == fd_hash[cur_dup_entry].len
714 && memcmp(fd_hash[i].digest, fd_hash[cur_dup_entry].digest, 16) == 0) {
723 print_usage(FILE *output)
725 fprintf(output, "\n");
726 fprintf(output, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
727 fprintf(output, "\n");
728 fprintf(output, "<infile> and <outfile> must both be present.\n");
729 fprintf(output, "A single packet or a range of packets can be selected.\n");
730 fprintf(output, "\n");
731 fprintf(output, "Packet selection:\n");
732 fprintf(output, " -r keep the selected packets; default is to delete them.\n");
733 fprintf(output, " -A <start time> only output packets whose timestamp is after (or equal\n");
734 fprintf(output, " to) the given time (format as YYYY-MM-DD hh:mm:ss).\n");
735 fprintf(output, " -B <stop time> only output packets whose timestamp is before the\n");
736 fprintf(output, " given time (format as YYYY-MM-DD hh:mm:ss).\n");
737 fprintf(output, "\n");
738 fprintf(output, "Duplicate packet removal:\n");
739 fprintf(output, " --novlan remove vlan info from packets before checking for duplicates.\n");
740 fprintf(output, " -d remove packet if duplicate (window == %d).\n", DEFAULT_DUP_DEPTH);
741 fprintf(output, " -D <dup window> remove packet if duplicate; configurable <dup window>\n");
742 fprintf(output, " Valid <dup window> values are 0 to %d.\n", MAX_DUP_DEPTH);
743 fprintf(output, " NOTE: A <dup window> of 0 with -v (verbose option) is\n");
744 fprintf(output, " useful to print MD5 hashes.\n");
745 fprintf(output, " -w <dup time window> remove packet if duplicate packet is found EQUAL TO OR\n");
746 fprintf(output, " LESS THAN <dup time window> prior to current packet.\n");
747 fprintf(output, " A <dup time window> is specified in relative seconds\n");
748 fprintf(output, " (e.g. 0.000001).\n");
749 fprintf(output, " -a <framenum>:<comment> Add or replace comment for given frame number\n");
750 fprintf(output, "\n");
751 fprintf(output, " -I <bytes to ignore> ignore the specified bytes at the beginning of\n");
752 fprintf(output, " the frame during MD5 hash calculation\n");
753 fprintf(output, " Useful to remove duplicated packets taken on\n");
754 fprintf(output, " several routers(differents mac addresses for \n");
755 fprintf(output, " example)\n");
756 fprintf(output, " e.g. -I 26 in case of Ether/IP/ will ignore \n");
757 fprintf(output, " ether(14) and IP header(20 - 4(src ip) - 4(dst ip)).\n");
758 fprintf(output, "\n");
759 fprintf(output, " NOTE: The use of the 'Duplicate packet removal' options with\n");
760 fprintf(output, " other editcap options except -v may not always work as expected.\n");
761 fprintf(output, " Specifically the -r, -t or -S options will very likely NOT have the\n");
762 fprintf(output, " desired effect if combined with the -d, -D or -w.\n");
763 fprintf(output, "\n");
764 fprintf(output, "Packet manipulation:\n");
765 fprintf(output, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data.\n");
766 fprintf(output, " -C [offset:]<choplen> chop each packet by <choplen> bytes. Positive values\n");
767 fprintf(output, " chop at the packet beginning, negative values at the\n");
768 fprintf(output, " packet end. If an optional offset precedes the length,\n");
769 fprintf(output, " then the bytes chopped will be offset from that value.\n");
770 fprintf(output, " Positive offsets are from the packet beginning,\n");
771 fprintf(output, " negative offsets are from the packet end. You can use\n");
772 fprintf(output, " this option more than once, allowing up to 2 chopping\n");
773 fprintf(output, " regions within a packet provided that at least 1\n");
774 fprintf(output, " choplen is positive and at least 1 is negative.\n");
775 fprintf(output, " -L adjust the frame (i.e. reported) length when chopping\n");
776 fprintf(output, " and/or snapping\n");
777 fprintf(output, " -t <time adjustment> adjust the timestamp of each packet;\n");
778 fprintf(output, " <time adjustment> is in relative seconds (e.g. -0.5).\n");
779 fprintf(output, " -S <strict adjustment> adjust timestamp of packets if necessary to insure\n");
780 fprintf(output, " strict chronological increasing order. The <strict\n");
781 fprintf(output, " adjustment> is specified in relative seconds with\n");
782 fprintf(output, " values of 0 or 0.000001 being the most reasonable.\n");
783 fprintf(output, " A negative adjustment value will modify timestamps so\n");
784 fprintf(output, " that each packet's delta time is the absolute value\n");
785 fprintf(output, " of the adjustment specified. A value of -0 will set\n");
786 fprintf(output, " all packets to the timestamp of the first packet.\n");
787 fprintf(output, " -E <error probability> set the probability (between 0.0 and 1.0 incl.) that\n");
788 fprintf(output, " a particular packet byte will be randomly changed.\n");
789 fprintf(output, " -o <change offset> When used in conjunction with -E, skip some bytes from the\n");
790 fprintf(output, " beginning of the packet. This allows one to preserve some\n");
791 fprintf(output, " bytes, in order to have some headers untouched.\n");
792 fprintf(output, "\n");
793 fprintf(output, "Output File(s):\n");
794 fprintf(output, " -c <packets per file> split the packet output to different files based on\n");
795 fprintf(output, " uniform packet counts with a maximum of\n");
796 fprintf(output, " <packets per file> each.\n");
797 fprintf(output, " -i <seconds per file> split the packet output to different files based on\n");
798 fprintf(output, " uniform time intervals with a maximum of\n");
799 fprintf(output, " <seconds per file> each.\n");
800 fprintf(output, " -F <capture type> set the output file type; default is pcapng. An empty\n");
801 fprintf(output, " \"-F\" option will list the file types.\n");
802 fprintf(output, " -T <encap type> set the output file encapsulation type; default is the\n");
803 fprintf(output, " same as the input file. An empty \"-T\" option will\n");
804 fprintf(output, " list the encapsulation types.\n");
805 fprintf(output, "\n");
806 fprintf(output, "Miscellaneous:\n");
807 fprintf(output, " -h display this help and exit.\n");
808 fprintf(output, " -v verbose output.\n");
809 fprintf(output, " If -v is used with any of the 'Duplicate Packet\n");
810 fprintf(output, " Removal' options (-d, -D or -w) then Packet lengths\n");
811 fprintf(output, " and MD5 hashes are printed to standard-error.\n");
812 fprintf(output, "\n");
816 const char *sstr; /* The short string */
817 const char *lstr; /* The long string */
821 string_compare(gconstpointer a, gconstpointer b)
823 return strcmp(((const struct string_elem *)a)->sstr,
824 ((const struct string_elem *)b)->sstr);
828 string_nat_compare(gconstpointer a, gconstpointer b)
830 return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
831 ((const struct string_elem *)b)->sstr);
835 string_elem_print(gpointer data, gpointer not_used _U_)
837 fprintf(stderr, " %s - %s\n",
838 ((struct string_elem *)data)->sstr,
839 ((struct string_elem *)data)->lstr);
843 list_capture_types(void) {
845 struct string_elem *captypes;
848 captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES_SUBTYPES);
849 fprintf(stderr, "editcap: The available capture file types for the \"-F\" flag are:\n");
850 for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
851 if (wtap_dump_can_open(i)) {
852 captypes[i].sstr = wtap_file_type_subtype_short_string(i);
853 captypes[i].lstr = wtap_file_type_subtype_string(i);
854 list = g_slist_insert_sorted(list, &captypes[i], string_compare);
857 g_slist_foreach(list, string_elem_print, NULL);
863 list_encap_types(void) {
865 struct string_elem *encaps;
868 encaps = (struct string_elem *)g_malloc(sizeof(struct string_elem) * WTAP_NUM_ENCAP_TYPES);
869 fprintf(stderr, "editcap: The available encapsulation types for the \"-T\" flag are:\n");
870 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
871 encaps[i].sstr = wtap_encap_short_string(i);
872 if (encaps[i].sstr != NULL) {
873 encaps[i].lstr = wtap_encap_string(i);
874 list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
877 g_slist_foreach(list, string_elem_print, NULL);
883 framenum_compare(gconstpointer a, gconstpointer b, gpointer user_data _U_)
885 if (GPOINTER_TO_UINT(a) < GPOINTER_TO_UINT(b))
888 if (GPOINTER_TO_UINT(a) > GPOINTER_TO_UINT(b))
896 * Don't report failures to load plugins because most (non-wiretap) plugins
897 * *should* fail to load (because we're not linked against libwireshark and
898 * dissector plugins need libwireshark).
901 failure_message(const char *msg_format _U_, va_list ap _U_)
907 editcap_dump_open(const char *filename, guint32 snaplen,
909 wtapng_iface_descriptions_t *idb_inf,
910 GArray* nrb_hdrs, int *write_err)
914 if (strcmp(filename, "-") == 0) {
915 /* Write to the standard output. */
916 pdh = wtap_dump_open_stdout_ng(out_file_type_subtype, out_frame_type,
917 snaplen, FALSE /* compressed */,
918 shb_hdrs, idb_inf, nrb_hdrs, write_err);
920 pdh = wtap_dump_open_ng(filename, out_file_type_subtype, out_frame_type,
921 snaplen, FALSE /* compressed */,
922 shb_hdrs, idb_inf, nrb_hdrs, write_err);
928 main(int argc, char *argv[])
930 GString *comp_info_str;
931 GString *runtime_info_str;
933 int i, j, read_err, write_err;
934 gchar *read_err_info, *write_err_info;
936 static const struct option long_options[] = {
937 {"novlan", no_argument, NULL, 0x8100},
938 {"help", no_argument, NULL, 'h'},
939 {"version", no_argument, NULL, 'V'},
944 guint32 snaplen = 0; /* No limit */
945 chop_t chop = {0, 0, 0, 0, 0, 0}; /* No chop */
946 gboolean adjlen = FALSE;
947 wtap_dumper *pdh = NULL;
948 unsigned int count = 1;
949 unsigned int duplicate_count = 0;
953 guint32 read_count = 0;
954 int split_packet_count = 0;
955 int written_count = 0;
956 char *filename = NULL;
958 int secs_per_block = 0;
960 nstime_t block_start;
961 gchar *fprefix = NULL;
962 gchar *fsuffix = NULL;
963 guint32 change_offset = 0;
964 guint max_packet_number = G_MAXUINT;
965 const struct wtap_pkthdr *phdr;
966 struct wtap_pkthdr temp_phdr;
967 wtapng_iface_descriptions_t *idb_inf = NULL;
968 GArray *shb_hdrs = NULL;
969 GArray *nrb_hdrs = NULL;
973 char* init_progfile_dir_error;
977 arg_list_utf_16to8(argc, argv);
978 create_app_running_mutex();
981 /* Get the compile-time version information string */
982 comp_info_str = get_compiled_version_info(NULL, NULL);
984 /* Get the run-time version information string */
985 runtime_info_str = get_runtime_version_info(NULL);
987 /* Add it to the information to be reported on a crash. */
988 ws_add_crash_info("Editcap (Wireshark) %s\n"
993 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
996 * Get credential information for later use.
998 init_process_policies();
999 init_open_routines();
1002 /* Register wiretap plugins */
1003 if ((init_progfile_dir_error = init_progfile_dir(argv[0], main))) {
1004 g_warning("editcap: init_progfile_dir(): %s", init_progfile_dir_error);
1005 g_free(init_progfile_dir_error);
1007 /* Register all the plugin types we have. */
1008 wtap_register_plugin_types(); /* Types known to libwiretap */
1010 init_report_err(failure_message,NULL,NULL,NULL);
1012 /* Scan for plugins. This does *not* call their registration routines;
1013 that's done later. */
1016 /* Register all libwiretap plugin modules. */
1017 register_all_wiretap_modules();
1021 /* Process the options */
1022 while ((opt = getopt_long(argc, argv, "a:A:B:c:C:dD:E:F:hi:I:Lo:rs:S:t:T:vVw:", long_options, NULL)) != -1) {
1033 gint string_start_index = 0;
1035 if ((sscanf(optarg, "%u:%n", &frame_number, &string_start_index) < 1) || (string_start_index == 0)) {
1036 fprintf(stderr, "editcap: \"%s\" isn't a valid <frame>:<comment>\n\n",
1041 /* Lazily create the table */
1042 if (!frames_user_comments) {
1043 frames_user_comments = g_tree_new_full(framenum_compare, NULL, NULL, g_free);
1046 /* Insert this entry (framenum -> comment) */
1047 g_tree_replace(frames_user_comments, GUINT_TO_POINTER(frame_number), g_strdup(optarg+string_start_index));
1055 memset(&starttm,0,sizeof(struct tm));
1057 if (!strptime(optarg,"%Y-%m-%d %T", &starttm)) {
1058 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1063 check_startstop = TRUE;
1064 starttm.tm_isdst = -1;
1066 starttime = mktime(&starttm);
1074 memset(&stoptm,0,sizeof(struct tm));
1076 if (!strptime(optarg,"%Y-%m-%d %T", &stoptm)) {
1077 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n",
1081 check_startstop = TRUE;
1082 stoptm.tm_isdst = -1;
1083 stoptime = mktime(&stoptm);
1088 split_packet_count = (int)strtol(optarg, &p, 10);
1089 if (p == optarg || *p != '\0') {
1090 fprintf(stderr, "editcap: \"%s\" isn't a valid packet count\n",
1094 if (split_packet_count <= 0) {
1095 fprintf(stderr, "editcap: \"%d\" packet count must be larger than zero\n",
1096 split_packet_count);
1103 int choplen = 0, chopoff = 0;
1105 switch (sscanf(optarg, "%d:%d", &chopoff, &choplen)) {
1106 case 1: /* only the chop length was specififed */
1111 case 2: /* both an offset and chop length was specified */
1115 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length or offset:length\n",
1122 chop.len_begin += choplen;
1124 chop.off_begin_pos += chopoff;
1126 chop.off_begin_neg += chopoff;
1127 } else if (choplen < 0) {
1128 chop.len_end += choplen;
1130 chop.off_end_pos += chopoff;
1132 chop.off_end_neg += chopoff;
1139 dup_detect_by_time = FALSE;
1140 dup_window = DEFAULT_DUP_DEPTH;
1145 dup_detect_by_time = FALSE;
1146 dup_window = (int)strtol(optarg, &p, 10);
1147 if (p == optarg || *p != '\0') {
1148 fprintf(stderr, "editcap: \"%s\" isn't a valid duplicate window value\n",
1152 if (dup_window < 0 || dup_window > MAX_DUP_DEPTH) {
1153 fprintf(stderr, "editcap: \"%d\" duplicate window value must be between 0 and %d inclusive.\n",
1154 dup_window, MAX_DUP_DEPTH);
1160 err_prob = g_ascii_strtod(optarg, &p);
1161 if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
1162 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
1166 srand( (unsigned int) (time(NULL) + ws_getpid()) );
1170 out_file_type_subtype = wtap_short_string_to_file_type_subtype(optarg);
1171 if (out_file_type_subtype < 0) {
1172 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
1174 list_capture_types();
1180 printf("Editcap (Wireshark) %s\n"
1181 "Edit and/or translate the format of capture files.\n"
1182 "See https://www.wireshark.org for more information.\n",
1183 get_ws_vcs_version_info());
1184 print_usage(stdout);
1188 case 'i': /* break capture file based on time interval */
1189 secs_per_block = atoi(optarg);
1190 if (secs_per_block <= 0) {
1191 fprintf(stderr, "editcap: \"%s\" isn't a valid time interval\n\n",
1197 case 'I': /* ignored_bytes at the beginning of the frame for duplications removal */
1198 ignored_bytes = atoi(optarg);
1199 if(ignored_bytes <= 0) {
1200 fprintf(stderr, "editcap: \"%s\" isn't a valid number of bytes to ignore\n", optarg);
1210 change_offset = (guint32)strtol(optarg, &p, 10);
1214 keep_em = !keep_em; /* Just invert */
1218 snaplen = (guint32)strtol(optarg, &p, 10);
1219 if (p == optarg || *p != '\0') {
1220 fprintf(stderr, "editcap: \"%s\" isn't a valid snapshot length\n",
1227 set_strict_time_adj(optarg);
1228 do_strict_time_adjustment = TRUE;
1232 set_time_adjustment(optarg);
1236 out_frame_type = wtap_short_string_to_encap(optarg);
1237 if (out_frame_type < 0) {
1238 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
1246 verbose = !verbose; /* Just invert */
1250 show_version("Editcap (Wireshark)", comp_info_str, runtime_info_str);
1251 g_string_free(comp_info_str, TRUE);
1252 g_string_free(runtime_info_str, TRUE);
1258 dup_detect_by_time = TRUE;
1259 dup_window = MAX_DUP_DEPTH;
1260 set_rel_time(optarg);
1263 case '?': /* Bad options if GNU getopt */
1266 list_capture_types();
1272 print_usage(stderr);
1278 } /* processing commmand-line options */
1281 fprintf(stderr, "Optind = %i, argc = %i\n", optind, argc);
1284 if ((argc - optind) < 1) {
1285 print_usage(stderr);
1289 if (check_startstop && !stoptime) {
1292 /* XXX: will work until 2035 */
1293 memset(&stoptm,0,sizeof(struct tm));
1294 stoptm.tm_year = 135;
1295 stoptm.tm_mday = 31;
1298 stoptime = mktime(&stoptm);
1301 nstime_set_unset(&block_start);
1303 if (starttime > stoptime) {
1304 fprintf(stderr, "editcap: start time is after the stop time\n");
1308 if (split_packet_count > 0 && secs_per_block > 0) {
1309 fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
1310 fprintf(stderr, "editcap: at the same time\n");
1314 wth = wtap_open_offline(argv[optind], WTAP_TYPE_AUTO, &read_err, &read_err_info, FALSE);
1317 fprintf(stderr, "editcap: Can't open %s: %s\n", argv[optind],
1318 wtap_strerror(read_err));
1319 if (read_err_info != NULL) {
1320 fprintf(stderr, "(%s)\n", read_err_info);
1321 g_free(read_err_info);
1327 fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
1328 wtap_file_type_subtype_string(wtap_file_type_subtype(wth)));
1331 shb_hdrs = wtap_file_get_shb_for_new_file(wth);
1332 idb_inf = wtap_file_get_idb_info(wth);
1333 nrb_hdrs = wtap_file_get_nrb_for_new_file(wth);
1336 * Now, process the rest, if any ... we only write if there is an extra
1337 * argument or so ...
1340 if ((argc - optind) >= 2) {
1341 if (out_frame_type == -2)
1342 out_frame_type = wtap_file_encap(wth);
1344 for (i = optind + 2; i < argc; i++)
1345 if (add_selection(argv[i], &max_packet_number) == FALSE)
1348 if (keep_em == FALSE)
1349 max_packet_number = G_MAXUINT;
1351 if (dup_detect || dup_detect_by_time) {
1352 for (i = 0; i < dup_window; i++) {
1353 memset(&fd_hash[i].digest, 0, 16);
1355 nstime_set_unset(&fd_hash[i].frame_time);
1359 /* Read all of the packets in turn */
1360 while (wtap_read(wth, &read_err, &read_err_info, &data_offset)) {
1361 if (max_packet_number <= read_count)
1366 phdr = wtap_phdr(wth);
1368 /* Extra actions for the first packet */
1369 if (read_count == 1) {
1370 if (split_packet_count > 0 || secs_per_block > 0) {
1371 if (!fileset_extract_prefix_suffix(argv[optind+1], &fprefix, &fsuffix))
1374 filename = fileset_get_filename_by_pattern(block_cnt++, phdr, fprefix, fsuffix);
1376 filename = g_strdup(argv[optind+1]);
1380 /* If we don't have an application name add Editcap */
1381 wtap_optionblock_get_option_string(g_array_index(shb_hdrs, wtap_optionblock_t, 0), OPT_SHB_USERAPPL, &shb_user_appl);
1382 if (shb_user_appl == NULL) {
1383 wtap_optionblock_set_option_string_format(g_array_index(shb_hdrs, wtap_optionblock_t, 0), OPT_SHB_USERAPPL, "Editcap " VERSION);
1386 pdh = editcap_dump_open(filename,
1387 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1388 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1391 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1392 filename, wtap_strerror(write_err));
1395 } /* first packet only handling */
1398 buf = wtap_buf_ptr(wth);
1401 * Not all packets have time stamps. Only process the time
1402 * stamp if we have one.
1404 if (phdr->presence_flags & WTAP_HAS_TS) {
1405 if (nstime_is_unset(&block_start)) {
1406 block_start = phdr->ts;
1409 if (secs_per_block > 0) {
1410 while ((phdr->ts.secs - block_start.secs > secs_per_block)
1411 || (phdr->ts.secs - block_start.secs == secs_per_block
1412 && phdr->ts.nsecs >= block_start.nsecs )) { /* time for the next file */
1414 if (!wtap_dump_close(pdh, &write_err)) {
1415 fprintf(stderr, "editcap: Error writing to %s: %s\n",
1416 filename, wtap_strerror(write_err));
1419 block_start.secs = block_start.secs + secs_per_block; /* reset for next interval */
1421 filename = fileset_get_filename_by_pattern(block_cnt++, phdr, fprefix, fsuffix);
1425 fprintf(stderr, "Continuing writing in file %s\n", filename);
1427 pdh = editcap_dump_open(filename,
1428 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1429 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1432 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1433 filename, wtap_strerror(write_err));
1438 } /* time stamp handling */
1440 if (split_packet_count > 0) {
1441 /* time for the next file? */
1442 if (written_count > 0 && written_count % split_packet_count == 0) {
1443 if (!wtap_dump_close(pdh, &write_err)) {
1444 fprintf(stderr, "editcap: Error writing to %s: %s\n",
1445 filename, wtap_strerror(write_err));
1450 filename = fileset_get_filename_by_pattern(block_cnt++, phdr, fprefix, fsuffix);
1454 fprintf(stderr, "Continuing writing in file %s\n", filename);
1456 pdh = editcap_dump_open(filename,
1457 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)) : wtap_snapshot_length(wth),
1458 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1460 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1461 filename, wtap_strerror(write_err));
1465 } /* split packet handling */
1467 if (check_startstop) {
1469 * Is the packet in the selected timeframe?
1470 * If the packet has no time stamp, the answer is "no".
1472 if (phdr->presence_flags & WTAP_HAS_TS)
1473 ts_okay = (phdr->ts.secs >= starttime) && (phdr->ts.secs < stoptime);
1478 * No selected timeframe, so all packets are "in the
1479 * selected timeframe".
1484 if (ts_okay && ((!selected(count) && !keep_em)
1485 || (selected(count) && keep_em))) {
1487 if (verbose && !dup_detect && !dup_detect_by_time)
1488 fprintf(stderr, "Packet: %u\n", count);
1490 /* We simply write it, perhaps after truncating it; we could
1491 * do other things, like modify it. */
1493 phdr = wtap_phdr(wth);
1496 /* Limit capture length to snaplen */
1497 if (phdr->caplen > snaplen) {
1498 /* Copy and change rather than modify returned phdr */
1500 temp_phdr.caplen = snaplen;
1503 /* If -L, also set reported length to snaplen */
1504 if (adjlen && phdr->len > snaplen) {
1505 /* Copy and change rather than modify returned phdr */
1507 temp_phdr.len = snaplen;
1514 handle_chopping(chop, &temp_phdr, phdr, &buf, adjlen);
1517 if (phdr->presence_flags & WTAP_HAS_TS) {
1518 /* Do we adjust timestamps to ensure strict chronological
1520 if (do_strict_time_adjustment) {
1521 if (previous_time.secs || previous_time.nsecs) {
1522 if (!strict_time_adj.is_negative) {
1528 nstime_delta(&delta, ¤t, &previous_time);
1530 if (delta.secs < 0 || delta.nsecs < 0) {
1532 * A negative delta indicates that the current packet
1533 * has an absolute timestamp less than the previous packet
1534 * that it is being compared to. This is NOT a normal
1535 * situation since trace files usually have packets in
1536 * chronological order (oldest to newest).
1538 /* fprintf(stderr, "++out of order, need to adjust this packet!\n"); */
1540 temp_phdr.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1541 temp_phdr.ts.nsecs = previous_time.nsecs;
1542 if (temp_phdr.ts.nsecs + strict_time_adj.tv.nsecs > ONE_BILLION) {
1544 temp_phdr.ts.secs++;
1545 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1547 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs;
1553 * A negative strict time adjustment is requested.
1554 * Unconditionally set each timestamp to previous
1555 * packet's timestamp plus delta.
1558 temp_phdr.ts.secs = previous_time.secs + strict_time_adj.tv.secs;
1559 temp_phdr.ts.nsecs = previous_time.nsecs;
1560 if (temp_phdr.ts.nsecs + strict_time_adj.tv.nsecs > ONE_BILLION) {
1562 temp_phdr.ts.secs++;
1563 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs - ONE_BILLION;
1565 temp_phdr.ts.nsecs += strict_time_adj.tv.nsecs;
1570 previous_time = phdr->ts;
1573 if (time_adj.tv.secs != 0) {
1575 if (time_adj.is_negative)
1576 temp_phdr.ts.secs -= time_adj.tv.secs;
1578 temp_phdr.ts.secs += time_adj.tv.secs;
1582 if (time_adj.tv.nsecs != 0) {
1584 if (time_adj.is_negative) { /* subtract */
1585 if (temp_phdr.ts.nsecs < time_adj.tv.nsecs) { /* borrow */
1586 temp_phdr.ts.secs--;
1587 temp_phdr.ts.nsecs += ONE_BILLION;
1589 temp_phdr.ts.nsecs -= time_adj.tv.nsecs;
1591 if (temp_phdr.ts.nsecs + time_adj.tv.nsecs > ONE_BILLION) {
1593 temp_phdr.ts.secs++;
1594 temp_phdr.ts.nsecs += time_adj.tv.nsecs - ONE_BILLION;
1596 temp_phdr.ts.nsecs += time_adj.tv.nsecs;
1601 } /* time stamp adjustment */
1603 /* remove vlan info */
1605 /* TODO: keep casting const like this? change pointer instead of value? */
1606 remove_vlan_info(phdr, buf, (guint32 *) &phdr->caplen);
1609 /* suppress duplicates by packet window */
1611 if (is_duplicate(buf, phdr->caplen)) {
1613 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1614 count, phdr->caplen);
1615 for (i = 0; i < 16; i++)
1616 fprintf(stderr, "%02x",
1617 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1618 fprintf(stderr, "\n");
1625 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1626 count, phdr->caplen);
1627 for (i = 0; i < 16; i++)
1628 fprintf(stderr, "%02x",
1629 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1630 fprintf(stderr, "\n");
1633 } /* suppression of duplicates */
1635 if (phdr->presence_flags & WTAP_HAS_TS) {
1636 /* suppress duplicates by time window */
1637 if (dup_detect_by_time) {
1640 current.secs = phdr->ts.secs;
1641 current.nsecs = phdr->ts.nsecs;
1643 if (is_duplicate_rel_time(buf, phdr->caplen, ¤t)) {
1645 fprintf(stderr, "Skipped: %u, Len: %u, MD5 Hash: ",
1646 count, phdr->caplen);
1647 for (i = 0; i < 16; i++)
1648 fprintf(stderr, "%02x",
1649 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1650 fprintf(stderr, "\n");
1657 fprintf(stderr, "Packet: %u, Len: %u, MD5 Hash: ",
1658 count, phdr->caplen);
1659 for (i = 0; i < 16; i++)
1660 fprintf(stderr, "%02x",
1661 (unsigned char)fd_hash[cur_dup_entry].digest[i]);
1662 fprintf(stderr, "\n");
1666 } /* suppress duplicates by time window */
1668 if (change_offset > phdr->caplen) {
1669 fprintf(stderr, "change offset %u is longer than caplen %u in packet %u\n",
1670 change_offset, phdr->caplen, count);
1673 /* Random error mutation */
1674 if (err_prob > 0.0 && change_offset <= phdr->caplen) {
1675 int real_data_start = 0;
1677 /* Protect non-protocol data */
1678 if (wtap_file_type_subtype(wth) == WTAP_FILE_TYPE_SUBTYPE_CATAPULT_DCT2000)
1679 real_data_start = find_dct2000_real_data(buf);
1681 real_data_start += change_offset;
1683 for (i = real_data_start; i < (int) phdr->caplen; i++) {
1684 if (rand() <= err_prob * RAND_MAX) {
1685 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
1687 if (err_type < ERR_WT_BIT) {
1688 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
1689 err_type = ERR_WT_TOTAL;
1691 err_type -= ERR_WT_BYTE;
1694 if (err_type < ERR_WT_BYTE) {
1695 buf[i] = rand() / (RAND_MAX / 255 + 1);
1696 err_type = ERR_WT_TOTAL;
1698 err_type -= ERR_WT_BYTE;
1701 if (err_type < ERR_WT_ALNUM) {
1702 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
1703 err_type = ERR_WT_TOTAL;
1705 err_type -= ERR_WT_ALNUM;
1708 if (err_type < ERR_WT_FMT) {
1709 if ((unsigned int)i < phdr->caplen - 2)
1710 g_strlcpy((char*) &buf[i], "%s", 2);
1711 err_type = ERR_WT_TOTAL;
1713 err_type -= ERR_WT_FMT;
1716 if (err_type < ERR_WT_AA) {
1717 for (j = i; j < (int) phdr->caplen; j++)
1723 } /* random error mutation */
1725 /* Find a packet comment we may need to write */
1726 if (frames_user_comments) {
1727 const char *comment =
1728 (const char*)g_tree_lookup(frames_user_comments, GUINT_TO_POINTER(read_count));
1729 if (comment != NULL) {
1730 /* Copy and change rather than modify returned phdr */
1732 temp_phdr.opt_comment = g_strdup(comment);
1737 /* Attempt to dump out current frame to the output file */
1738 if (!wtap_dump(pdh, phdr, buf, &write_err, &write_err_info)) {
1739 switch (write_err) {
1740 case WTAP_ERR_UNWRITABLE_ENCAP:
1742 * This is a problem with the particular frame we're
1743 * writing and the file type and subtype we're
1744 * writing; note that, and report the frame number
1745 * and file type/subtype.
1748 "editcap: Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
1749 read_count, argv[optind],
1750 wtap_file_type_subtype_string(out_file_type_subtype));
1753 case WTAP_ERR_PACKET_TOO_LARGE:
1755 * This is a problem with the particular frame we're
1756 * writing and the file type and subtype we're
1757 * writing; note that, and report the frame number
1758 * and file type/subtype.
1761 "editcap: Frame %u of \"%s\" is too large for a \"%s\" file.\n",
1762 read_count, argv[optind],
1763 wtap_file_type_subtype_string(out_file_type_subtype));
1766 case WTAP_ERR_UNWRITABLE_REC_TYPE:
1768 * This is a problem with the particular record we're
1769 * writing and the file type and subtype we're
1770 * writing; note that, and report the record number
1771 * and file type/subtype.
1774 "editcap: Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
1775 read_count, argv[optind],
1776 wtap_file_type_subtype_string(out_file_type_subtype));
1779 case WTAP_ERR_UNWRITABLE_REC_DATA:
1781 * This is a problem with the particular record we're
1782 * writing and the file type and subtype we're
1783 * writing; note that, and report the record number
1784 * and file type/subtype.
1787 "editcap: Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
1788 read_count, argv[optind],
1789 wtap_file_type_subtype_string(out_file_type_subtype),
1790 write_err_info != NULL ? write_err_info : "no information supplied");
1791 g_free(write_err_info);
1795 fprintf(stderr, "editcap: Error writing to %s: %s\n",
1796 filename, wtap_strerror(write_err));
1809 if (read_err != 0) {
1810 /* Print a message noting that the read failed somewhere along the
1813 "editcap: An error occurred while reading \"%s\": %s.\n",
1814 argv[optind], wtap_strerror(read_err));
1815 if (read_err_info != NULL) {
1816 fprintf(stderr, "(%s)\n", read_err_info);
1817 g_free(read_err_info);
1822 /* No valid packages found, open the outfile so we can write an
1825 filename = g_strdup(argv[optind+1]);
1827 pdh = editcap_dump_open(filename,
1828 snaplen ? MIN(snaplen, wtap_snapshot_length(wth)): wtap_snapshot_length(wth),
1829 shb_hdrs, idb_inf, nrb_hdrs, &write_err);
1831 fprintf(stderr, "editcap: Can't open or create %s: %s\n",
1832 filename, wtap_strerror(write_err));
1840 if (!wtap_dump_close(pdh, &write_err)) {
1841 fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
1842 wtap_strerror(write_err));
1845 wtap_optionblock_array_free(shb_hdrs);
1847 wtap_optionblock_array_free(nrb_hdrs);
1851 if (frames_user_comments) {
1852 g_tree_destroy(frames_user_comments);
1857 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate window of %i packets.\n",
1858 count - 1, plurality(count - 1, "", "s"), duplicate_count,
1859 plurality(duplicate_count, "", "s"), dup_window);
1860 } else if (dup_detect_by_time) {
1861 fprintf(stderr, "%u packet%s seen, %u packet%s skipped with duplicate time window equal to or less than %ld.%09ld seconds.\n",
1862 count - 1, plurality(count - 1, "", "s"), duplicate_count,
1863 plurality(duplicate_count, "", "s"),
1864 (long)relative_time_window.secs,
1865 (long int)relative_time_window.nsecs);
1871 wtap_optionblock_array_free(shb_hdrs);
1872 wtap_optionblock_array_free(nrb_hdrs);
1877 /* Skip meta-information read from file to return offset of real
1880 find_dct2000_real_data(guint8 *buf)
1884 for (n = 0; buf[n] != '\0'; n++); /* Context name */
1886 n++; /* Context port number */
1887 for (; buf[n] != '\0'; n++); /* Timestamp */
1889 for (; buf[n] != '\0'; n++); /* Protocol name */
1891 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
1893 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
1895 n += 2; /* Direction & encap */
1901 * We support up to 2 chopping regions in a single pass: one specified by the
1902 * positive chop length, and one by the negative chop length.
1905 handle_chopping(chop_t chop, struct wtap_pkthdr *out_phdr,
1906 const struct wtap_pkthdr *in_phdr, guint8 **buf,
1909 /* Only packets can be chopped. */
1910 if (in_phdr->rec_type != REC_TYPE_PACKET)
1913 /* If we're not chopping anything from one side, then the offset for that
1914 * side is meaningless. */
1915 if (chop.len_begin == 0)
1916 chop.off_begin_pos = chop.off_begin_neg = 0;
1917 if (chop.len_end == 0)
1918 chop.off_end_pos = chop.off_end_neg = 0;
1920 if (chop.off_begin_neg < 0) {
1921 chop.off_begin_pos += in_phdr->caplen + chop.off_begin_neg;
1922 chop.off_begin_neg = 0;
1924 if (chop.off_end_pos > 0) {
1925 chop.off_end_neg += chop.off_end_pos - in_phdr->caplen;
1926 chop.off_end_pos = 0;
1929 /* If we've crossed chopping regions, swap them */
1930 if (chop.len_begin && chop.len_end) {
1931 if (chop.off_begin_pos > ((int)in_phdr->caplen + chop.off_end_neg)) {
1932 int tmp_len, tmp_off;
1934 tmp_off = in_phdr->caplen + chop.off_end_neg + chop.len_end;
1935 tmp_len = -chop.len_end;
1937 chop.off_end_neg = chop.len_begin + chop.off_begin_pos - in_phdr->caplen;
1938 chop.len_end = -chop.len_begin;
1940 chop.len_begin = tmp_len;
1941 chop.off_begin_pos = tmp_off;
1945 /* Make sure we don't chop off more than we have available */
1946 if (in_phdr->caplen < (guint32)(chop.off_begin_pos - chop.off_end_neg)) {
1950 if ((guint32)(chop.len_begin - chop.len_end) >
1951 (in_phdr->caplen - (guint32)(chop.off_begin_pos - chop.off_end_neg))) {
1952 chop.len_begin = in_phdr->caplen - (chop.off_begin_pos - chop.off_end_neg);
1956 /* Handle chopping from the beginning. Note that if a beginning offset
1957 * was specified, we need to keep that piece */
1958 if (chop.len_begin > 0) {
1959 *out_phdr = *in_phdr;
1961 if (chop.off_begin_pos > 0) {
1962 memmove(*buf + chop.off_begin_pos,
1963 *buf + chop.off_begin_pos + chop.len_begin,
1964 out_phdr->caplen - chop.len_begin);
1966 *buf += chop.len_begin;
1968 out_phdr->caplen -= chop.len_begin;
1971 if (in_phdr->len > (guint32)chop.len_begin)
1972 out_phdr->len -= chop.len_begin;
1979 /* Handle chopping from the end. Note that if an ending offset was
1980 * specified, we need to keep that piece */
1981 if (chop.len_end < 0) {
1982 *out_phdr = *in_phdr;
1984 if (chop.off_end_neg < 0) {
1985 memmove(*buf + (gint)out_phdr->caplen + (chop.len_end + chop.off_end_neg),
1986 *buf + (gint)out_phdr->caplen + chop.off_end_neg,
1989 out_phdr->caplen += chop.len_end;
1992 if (((signed int) in_phdr->len + chop.len_end) > 0)
1993 out_phdr->len += chop.len_end;
1997 /*in_phdr = out_phdr;*/
2002 * Editor modelines - http://www.wireshark.org/tools/modelines.html
2007 * indent-tabs-mode: nil
2010 * vi: set shiftwidth=4 tabstop=8 expandtab:
2011 * :indentSize=4:tabSize=8:noTabs=true: