1 /* Edit capture files. We can delete packets, adjust timestamps, or
2 * simply convert from one format to another format.
6 * Originally written by Richard Sharpe.
7 * Improved by Guy Harris.
8 * Further improved by Richard Sharpe.
21 * Just make sure we include the prototype for strptime as well
22 * (needed for glibc 2.2) but make sure we do this only if not
39 #ifdef HAVE_SYS_TIME_H
50 #include <process.h> /* getpid */
53 #ifdef NEED_STRPTIME_H
54 # include "strptime.h"
57 #include "epan/crypt/crypt-md5.h"
58 #include "epan/plugins.h"
59 #include "epan/report_err.h"
60 #include "epan/filesystem.h"
61 #include <epan/privileges.h>
63 #include "svnversion.h"
66 * Some globals so we can pass things to various routines
78 * Duplicate frame detection
80 typedef struct _fd_hash_t {
81 md5_byte_t digest[16];
86 fd_hash_t fd_hash[DUP_DEPTH];
89 #define ONE_MILLION 1000000
91 /* Weights of different errors we can introduce */
92 /* We should probably make these command-line arguments */
93 /* XXX - Should we add a bit-level error? */
94 #define ERR_WT_BIT 5 /* Flip a random bit */
95 #define ERR_WT_BYTE 5 /* Substitute a random byte */
96 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
97 #define ERR_WT_FMT 2 /* Substitute "%s" */
98 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
99 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
101 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
102 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
105 struct time_adjustment {
110 #define MAX_SELECTIONS 512
111 static struct select_item selectfrm[MAX_SELECTIONS];
112 static int max_selected = -1;
113 static int keep_em = 0;
114 static int out_file_type = WTAP_FILE_PCAP; /* default to "libpcap" */
115 static int out_frame_type = -2; /* Leave frame type alone */
116 static int verbose = 0; /* Not so verbose */
117 static struct time_adjustment time_adj = {{0, 0}, 0}; /* no adjustment */
118 static double err_prob = 0.0;
119 static time_t starttime = 0;
120 static time_t stoptime = 0;
121 static gboolean check_startstop = FALSE;
122 static gboolean dup_detect = FALSE;
124 static int find_dct2000_real_data(guint8 *buf);
126 /* Add a selection item, a simple parser for now */
128 add_selection(char *sel)
133 if (++max_selected >= MAX_SELECTIONS) {
134 /* Let the user know we stopped selecting */
135 printf("Out of room for packet selections!\n");
139 printf("Add_Selected: %s\n", sel);
141 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
143 printf("Not inclusive ...");
145 selectfrm[max_selected].inclusive = 0;
146 selectfrm[max_selected].first = atoi(sel);
148 printf(" %i\n", selectfrm[max_selected].first);
153 printf("Inclusive ...");
156 selectfrm[max_selected].inclusive = 1;
157 selectfrm[max_selected].first = atoi(sel);
158 selectfrm[max_selected].second = atoi(next);
160 printf(" %i, %i\n", selectfrm[max_selected].first, selectfrm[max_selected].second);
167 /* Was the packet selected? */
174 for (i = 0; i<= max_selected; i++) {
176 if (selectfrm[i].inclusive) {
177 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
181 if (recno == selectfrm[i].first)
190 /* is the packet in the selected timeframe */
192 check_timestamp(wtap *wth)
194 struct wtap_pkthdr* pkthdr = wtap_phdr(wth);
196 return ( pkthdr->ts.secs >= starttime ) && ( pkthdr->ts.secs <= stoptime );
200 set_time_adjustment(char *optarg)
209 /* skip leading whitespace */
210 while (*optarg == ' ' || *optarg == '\t') {
214 /* check for a negative adjustment */
215 if (*optarg == '-') {
216 time_adj.is_negative = 1;
220 /* collect whole number of seconds, if any */
221 if (*optarg == '.') { /* only fractional (i.e., .5 is ok) */
225 val = strtol(optarg, &frac, 10);
226 if (frac == NULL || frac == optarg || val == LONG_MIN || val == LONG_MAX) {
227 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
231 if (val < 0) { /* implies '--' since we caught '-' above */
232 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
237 time_adj.tv.tv_sec = val;
239 /* now collect the partial seconds, if any */
240 if (*frac != '\0') { /* chars left, so get fractional part */
241 val = strtol(&(frac[1]), &end, 10);
242 if (*frac != '.' || end == NULL || end == frac
243 || val < 0 || val > ONE_MILLION || val == LONG_MIN || val == LONG_MAX) {
244 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
250 return; /* no fractional digits */
253 /* adjust fractional portion from fractional to numerator
254 * e.g., in "1.5" from 5 to 500000 since .5*10^6 = 500000 */
255 if (frac && end) { /* both are valid */
256 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
257 while(frac_digits < 6) { /* this is frac of 10^6 */
262 time_adj.tv.tv_usec = val;
266 is_duplicate(guint8* fd, guint32 len) {
271 if (cur_dup >= DUP_DEPTH)
274 /* Calculate our digest */
276 md5_append(&ms, fd, len);
277 md5_finish(&ms, fd_hash[cur_dup].digest);
279 fd_hash[cur_dup].len = len;
281 /* Look for duplicates */
282 for (i = 0; i < DUP_DEPTH; i++) {
286 if (fd_hash[i].len == fd_hash[cur_dup].len &&
287 memcmp(fd_hash[i].digest, fd_hash[cur_dup].digest, 16) == 0) {
298 fprintf(stderr, "Editcap %s"
303 fprintf(stderr, "Edit and/or translate the format of capture files.\n");
304 fprintf(stderr, "See http://www.wireshark.org for more information.\n");
305 fprintf(stderr, "\n");
306 fprintf(stderr, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
307 fprintf(stderr, "\n");
308 fprintf(stderr, "A single packet or a range of packets can be selected.\n");
309 fprintf(stderr, "\n");
310 fprintf(stderr, "Packet selection:\n");
311 fprintf(stderr, " -r keep the selected packets, default is to delete them\n");
312 fprintf(stderr, " -A <start time> don't output packets whose timestamp is before the\n");
313 fprintf(stderr, " given time (format as YYYY-MM-DD hh:mm:ss)\n");
314 fprintf(stderr, " -B <stop time> don't output packets whose timestamp is after the\n");
315 fprintf(stderr, " given time (format as YYYY-MM-DD hh:mm:ss)\n");
316 fprintf(stderr, " -d remove duplicate packets\n");
317 fprintf(stderr, "\n");
318 fprintf(stderr, "Packet manipulation:\n");
319 fprintf(stderr, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data\n");
320 fprintf(stderr, " -C <choplen> chop each packet at the end by <choplen> bytes\n");
321 fprintf(stderr, " -t <time adjustment> adjust the timestamp of each packet,\n");
322 fprintf(stderr, " <time adjustment> is in relative seconds (e.g. -0.5)\n");
323 fprintf(stderr, " -E <error probability> set the probability (between 0.0 and 1.0 incl.)\n");
324 fprintf(stderr, " that a particular packet byte will be randomly changed\n");
325 fprintf(stderr, "\n");
326 fprintf(stderr, "Output File(s):\n");
327 fprintf(stderr, " -c <packets per file> split the packet output to different files,\n");
328 fprintf(stderr, " with a maximum of <packets per file> each\n");
329 fprintf(stderr, " -F <capture type> set the output file type, default is libpcap\n");
330 fprintf(stderr, " an empty \"-F\" option will list the file types\n");
331 fprintf(stderr, " -T <encap type> set the output file encapsulation type,\n");
332 fprintf(stderr, " default is the same as the input file\n");
333 fprintf(stderr, " an empty \"-T\" option will list the encapsulation types\n");
334 fprintf(stderr, "\n");
335 fprintf(stderr, "Miscellaneous:\n");
336 fprintf(stderr, " -h display this help and exit\n");
337 fprintf(stderr, " -v verbose output\n");
338 fprintf(stderr, "\n");
342 list_capture_types(void) {
345 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
346 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
347 if (wtap_dump_can_open(i))
348 fprintf(stderr, " %s - %s\n",
349 wtap_file_type_short_string(i), wtap_file_type_string(i));
354 list_encap_types(void) {
358 fprintf(stderr, "editcap: The available encapsulation types for \"T\":\n");
359 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
360 string = wtap_encap_short_string(i);
362 fprintf(stderr, " %s - %s\n",
363 string, wtap_encap_string(i));
368 * Don't report failures to load plugins because most (non-wiretap) plugins
369 * *should* fail to load (because we're not linked against libwireshark and
370 * dissector plugins need libwireshark).
373 failure_message(const char *msg_format _U_, va_list ap _U_)
379 main(int argc, char *argv[])
388 unsigned int snaplen = 0; /* No limit */
389 unsigned int choplen = 0; /* No chop */
393 struct wtap_pkthdr snap_phdr;
394 const struct wtap_pkthdr *phdr;
397 int split_packet_count = 0;
398 int written_count = 0;
400 size_t filenamelen = 0;
403 char* init_progfile_dir_error;
407 * Get credential information for later use.
409 get_credential_info();
412 /* Register wiretap plugins */
413 if ((init_progfile_dir_error = init_progfile_dir(argv[0]))) {
414 g_warning("capinfos: init_progfile_dir(): %s", init_progfile_dir_error);
415 g_free(init_progfile_dir_error);
417 init_report_err(failure_message,NULL,NULL);
422 /* Process the options */
423 while ((opt = getopt(argc, argv, "A:B:c:C:dE:F:hrs:t:T:v")) !=-1) {
428 err_prob = strtod(optarg, &p);
429 if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
430 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
434 srand( (unsigned int) (time(NULL) + getpid()) );
438 out_file_type = wtap_short_string_to_file_type(optarg);
439 if (out_file_type < 0) {
440 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
442 list_capture_types();
448 split_packet_count = strtol(optarg, &p, 10);
449 if (p == optarg || *p != '\0') {
450 fprintf(stderr, "editcap: \"%s\" isn't a valid packet count\n",
454 if (split_packet_count <= 0) {
455 fprintf(stderr, "editcap: \"%d\" packet count must be larger than zero\n",
462 choplen = strtol(optarg, &p, 10);
463 if (p == optarg || *p != '\0') {
464 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length\n",
472 for (i = 0; i < DUP_DEPTH; i++) {
473 memset(&fd_hash[i].digest, 0, 16);
478 case '?': /* Bad options if GNU getopt */
481 list_capture_types();
498 keep_em = !keep_em; /* Just invert */
502 snaplen = strtol(optarg, &p, 10);
503 if (p == optarg || *p != '\0') {
504 fprintf(stderr, "editcap: \"%s\" isn't a valid snapshot length\n",
511 set_time_adjustment(optarg);
515 out_frame_type = wtap_short_string_to_encap(optarg);
516 if (out_frame_type < 0) {
517 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
525 verbose = !verbose; /* Just invert */
532 memset(&starttm,0,sizeof(struct tm));
534 if(!strptime(optarg,"%Y-%m-%d %T",&starttm)) {
535 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
539 check_startstop = TRUE;
540 starttm.tm_isdst = -1;
542 starttime = mktime(&starttm);
550 memset(&stoptm,0,sizeof(struct tm));
552 if(!strptime(optarg,"%Y-%m-%d %T",&stoptm)) {
553 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
556 check_startstop = TRUE;
557 stoptm.tm_isdst = -1;
558 stoptime = mktime(&stoptm);
566 printf("Optind = %i, argc = %i\n", optind, argc);
569 if ((argc - optind) < 1) {
576 if (check_startstop && !stoptime) {
578 /* XXX: will work until 2035 */
579 memset(&stoptm,0,sizeof(struct tm));
580 stoptm.tm_year = 135;
584 stoptime = mktime(&stoptm);
587 if (starttime > stoptime) {
588 fprintf(stderr, "editcap: start time is after the stop time\n");
592 wth = wtap_open_offline(argv[optind], &err, &err_info, FALSE);
595 fprintf(stderr, "editcap: Can't open %s: %s\n", argv[optind],
599 case WTAP_ERR_UNSUPPORTED:
600 case WTAP_ERR_UNSUPPORTED_ENCAP:
601 case WTAP_ERR_BAD_RECORD:
602 fprintf(stderr, "(%s)\n", err_info);
611 fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
612 wtap_file_type_string(wtap_file_type(wth)));
616 * Now, process the rest, if any ... we only write if there is an extra
620 if ((argc - optind) >= 2) {
622 if (out_frame_type == -2)
623 out_frame_type = wtap_file_encap(wth);
625 if (split_packet_count > 0) {
626 filenamelen = strlen(argv[optind+1]) + 20;
627 filename = (char *) g_malloc(filenamelen);
631 g_snprintf(filename, filenamelen, "%s-%05d", argv[optind+1], 0);
633 filename = argv[optind+1];
636 pdh = wtap_dump_open(filename, out_file_type,
637 out_frame_type, wtap_snapshot_length(wth),
638 FALSE /* compressed */, &err);
641 fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
646 for (i = optind + 2; i < argc; i++)
647 if (add_selection(argv[i]) == FALSE)
650 while (wtap_read(wth, &err, &err_info, &data_offset)) {
652 if (split_packet_count > 0 && (written_count % split_packet_count == 0)) {
653 if (!wtap_dump_close(pdh, &err)) {
655 fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
660 g_snprintf(filename, filenamelen, "%s-%05d",argv[optind+1], count / split_packet_count);
663 fprintf(stderr, "Continuing writing in file %s\n", filename);
666 pdh = wtap_dump_open(filename, out_file_type,
667 out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
670 fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
676 check_ts = check_timestamp(wth);
678 if ( ((check_startstop && check_ts) || (!check_startstop && !check_ts)) && ((!selected(count) && !keep_em) ||
679 (selected(count) && keep_em)) ) {
682 printf("Packet: %u\n", count);
684 /* We simply write it, perhaps after truncating it; we could do other
685 things, like modify it. */
687 phdr = wtap_phdr(wth);
689 if (choplen != 0 && phdr->caplen > choplen) {
691 snap_phdr.caplen -= choplen;
695 if (snaplen != 0 && phdr->caplen > snaplen) {
697 snap_phdr.caplen = snaplen;
701 /* assume that if the frame's tv_sec is 0, then
702 * the timestamp isn't supported */
703 if (phdr->ts.secs > 0 && time_adj.tv.tv_sec != 0) {
705 if (time_adj.is_negative)
706 snap_phdr.ts.secs -= time_adj.tv.tv_sec;
708 snap_phdr.ts.secs += time_adj.tv.tv_sec;
712 /* assume that if the frame's tv_sec is 0, then
713 * the timestamp isn't supported */
714 if (phdr->ts.secs > 0 && time_adj.tv.tv_usec != 0) {
716 if (time_adj.is_negative) { /* subtract */
717 if (snap_phdr.ts.nsecs/1000 < time_adj.tv.tv_usec) { /* borrow */
719 snap_phdr.ts.nsecs += ONE_MILLION * 1000;
721 snap_phdr.ts.nsecs -= time_adj.tv.tv_usec * 1000;
723 if (snap_phdr.ts.nsecs + time_adj.tv.tv_usec * 1000 > ONE_MILLION * 1000) {
726 snap_phdr.ts.nsecs += (time_adj.tv.tv_usec - ONE_MILLION) * 1000;
728 snap_phdr.ts.nsecs += time_adj.tv.tv_usec * 1000;
735 buf = wtap_buf_ptr(wth);
736 if (is_duplicate(buf, phdr->caplen)) {
738 printf("Skipping duplicate: %u\n", count);
744 /* Random error mutation */
745 if (err_prob > 0.0) {
746 int real_data_start = 0;
747 buf = wtap_buf_ptr(wth);
748 /* Protect non-protocol data */
749 if (wtap_file_type(wth) == WTAP_FILE_CATAPULT_DCT2000) {
750 real_data_start = find_dct2000_real_data(buf);
752 for (i = real_data_start; i < (int) phdr->caplen; i++) {
753 if (rand() <= err_prob * RAND_MAX) {
754 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
756 if (err_type < ERR_WT_BIT) {
757 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
758 err_type = ERR_WT_TOTAL;
760 err_type -= ERR_WT_BYTE;
763 if (err_type < ERR_WT_BYTE) {
764 buf[i] = rand() / (RAND_MAX / 255 + 1);
765 err_type = ERR_WT_TOTAL;
767 err_type -= ERR_WT_BYTE;
770 if (err_type < ERR_WT_ALNUM) {
771 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
772 err_type = ERR_WT_TOTAL;
774 err_type -= ERR_WT_ALNUM;
777 if (err_type < ERR_WT_FMT) {
778 if ((unsigned int)i < phdr->caplen - 2)
779 strncpy((char*) &buf[i], "%s", 2);
780 err_type = ERR_WT_TOTAL;
782 err_type -= ERR_WT_FMT;
785 if (err_type < ERR_WT_AA) {
786 for (j = i; j < (int) phdr->caplen; j++) {
795 if (!wtap_dump(pdh, phdr, wtap_pseudoheader(wth), wtap_buf_ptr(wth),
797 fprintf(stderr, "editcap: Error writing to %s: %s\n",
798 filename, wtap_strerror(err));
807 /* Print a message noting that the read failed somewhere along the line. */
809 "editcap: An error occurred while reading \"%s\": %s.\n",
810 argv[optind], wtap_strerror(err));
813 case WTAP_ERR_UNSUPPORTED:
814 case WTAP_ERR_UNSUPPORTED_ENCAP:
815 case WTAP_ERR_BAD_RECORD:
816 fprintf(stderr, "(%s)\n", err_info);
821 if (!wtap_dump_close(pdh, &err)) {
823 fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
833 /* Skip meta-information read from file to return offset of real
835 static int find_dct2000_real_data(guint8 *buf)
839 for (n=0; buf[n] != '\0'; n++); /* Context name */
841 n++; /* Context port number */
842 for (; buf[n] != '\0'; n++); /* Timestamp */
844 for (; buf[n] != '\0'; n++); /* Protocol name */
846 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
848 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
850 n += 2; /* Direction & encap */