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 */
51 #ifdef HAVE_WINSOCK2_H
56 #ifdef NEED_STRPTIME_H
57 # include "strptime.h"
60 #include "epan/crypt/crypt-md5.h"
61 #include "epan/plugins.h"
62 #include "epan/report_err.h"
63 #include "epan/filesystem.h"
64 #include <wsutil/privileges.h>
65 #include "epan/nstime.h"
67 #include "svnversion.h"
70 * Some globals so we can pass things to various routines
82 * Duplicate frame detection
84 typedef struct _fd_hash_t {
85 md5_byte_t digest[16];
90 fd_hash_t fd_hash[DUP_DEPTH];
93 #define ONE_MILLION 1000000
95 /* Weights of different errors we can introduce */
96 /* We should probably make these command-line arguments */
97 /* XXX - Should we add a bit-level error? */
98 #define ERR_WT_BIT 5 /* Flip a random bit */
99 #define ERR_WT_BYTE 5 /* Substitute a random byte */
100 #define ERR_WT_ALNUM 5 /* Substitute a random character in [A-Za-z0-9] */
101 #define ERR_WT_FMT 2 /* Substitute "%s" */
102 #define ERR_WT_AA 1 /* Fill the remainder of the buffer with 0xAA */
103 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
105 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
106 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
109 struct time_adjustment {
114 #define MAX_SELECTIONS 512
115 static struct select_item selectfrm[MAX_SELECTIONS];
116 static int max_selected = -1;
117 static int keep_em = 0;
118 static int out_file_type = WTAP_FILE_PCAP; /* default to "libpcap" */
119 static int out_frame_type = -2; /* Leave frame type alone */
120 static int verbose = 0; /* Not so verbose */
121 static struct time_adjustment time_adj = {{0, 0}, 0}; /* no adjustment */
122 static double err_prob = 0.0;
123 static time_t starttime = 0;
124 static time_t stoptime = 0;
125 static gboolean check_startstop = FALSE;
126 static gboolean dup_detect = FALSE;
128 static int find_dct2000_real_data(guint8 *buf);
130 /* Add a selection item, a simple parser for now */
132 add_selection(char *sel)
137 if (++max_selected >= MAX_SELECTIONS) {
138 /* Let the user know we stopped selecting */
139 printf("Out of room for packet selections!\n");
143 printf("Add_Selected: %s\n", sel);
145 if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
147 printf("Not inclusive ...");
149 selectfrm[max_selected].inclusive = 0;
150 selectfrm[max_selected].first = atoi(sel);
152 printf(" %i\n", selectfrm[max_selected].first);
157 printf("Inclusive ...");
160 selectfrm[max_selected].inclusive = 1;
161 selectfrm[max_selected].first = atoi(sel);
162 selectfrm[max_selected].second = atoi(next);
164 printf(" %i, %i\n", selectfrm[max_selected].first, selectfrm[max_selected].second);
171 /* Was the packet selected? */
178 for (i = 0; i<= max_selected; i++) {
180 if (selectfrm[i].inclusive) {
181 if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
185 if (recno == selectfrm[i].first)
194 /* is the packet in the selected timeframe */
196 check_timestamp(wtap *wth)
198 struct wtap_pkthdr* pkthdr = wtap_phdr(wth);
200 return ( pkthdr->ts.secs >= starttime ) && ( pkthdr->ts.secs <= stoptime );
204 set_time_adjustment(char *optarg)
213 /* skip leading whitespace */
214 while (*optarg == ' ' || *optarg == '\t') {
218 /* check for a negative adjustment */
219 if (*optarg == '-') {
220 time_adj.is_negative = 1;
224 /* collect whole number of seconds, if any */
225 if (*optarg == '.') { /* only fractional (i.e., .5 is ok) */
229 val = strtol(optarg, &frac, 10);
230 if (frac == NULL || frac == optarg || val == LONG_MIN || val == LONG_MAX) {
231 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
235 if (val < 0) { /* implies '--' since we caught '-' above */
236 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
241 time_adj.tv.tv_sec = val;
243 /* now collect the partial seconds, if any */
244 if (*frac != '\0') { /* chars left, so get fractional part */
245 val = strtol(&(frac[1]), &end, 10);
246 if (*frac != '.' || end == NULL || end == frac
247 || val < 0 || val > ONE_MILLION || val == LONG_MIN || val == LONG_MAX) {
248 fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
254 return; /* no fractional digits */
257 /* adjust fractional portion from fractional to numerator
258 * e.g., in "1.5" from 5 to 500000 since .5*10^6 = 500000 */
259 if (frac && end) { /* both are valid */
260 frac_digits = end - frac - 1; /* fractional digit count (remember '.') */
261 while(frac_digits < 6) { /* this is frac of 10^6 */
266 time_adj.tv.tv_usec = val;
270 is_duplicate(guint8* fd, guint32 len) {
275 if (cur_dup >= DUP_DEPTH)
278 /* Calculate our digest */
280 md5_append(&ms, fd, len);
281 md5_finish(&ms, fd_hash[cur_dup].digest);
283 fd_hash[cur_dup].len = len;
285 /* Look for duplicates */
286 for (i = 0; i < DUP_DEPTH; i++) {
290 if (fd_hash[i].len == fd_hash[cur_dup].len &&
291 memcmp(fd_hash[i].digest, fd_hash[cur_dup].digest, 16) == 0) {
302 fprintf(stderr, "Editcap %s"
307 fprintf(stderr, "Edit and/or translate the format of capture files.\n");
308 fprintf(stderr, "See http://www.wireshark.org for more information.\n");
309 fprintf(stderr, "\n");
310 fprintf(stderr, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
311 fprintf(stderr, "\n");
312 fprintf(stderr, "A single packet or a range of packets can be selected.\n");
313 fprintf(stderr, "\n");
314 fprintf(stderr, "Packet selection:\n");
315 fprintf(stderr, " -r keep the selected packets, default is to delete them\n");
316 fprintf(stderr, " -A <start time> don't output packets whose timestamp is before the\n");
317 fprintf(stderr, " given time (format as YYYY-MM-DD hh:mm:ss)\n");
318 fprintf(stderr, " -B <stop time> don't output packets whose timestamp is after the\n");
319 fprintf(stderr, " given time (format as YYYY-MM-DD hh:mm:ss)\n");
320 fprintf(stderr, " -d remove duplicate packets\n");
321 fprintf(stderr, "\n");
322 fprintf(stderr, "Packet manipulation:\n");
323 fprintf(stderr, " -s <snaplen> truncate each packet to max. <snaplen> bytes of data\n");
324 fprintf(stderr, " -C <choplen> chop each packet at the end by <choplen> bytes\n");
325 fprintf(stderr, " -t <time adjustment> adjust the timestamp of each packet,\n");
326 fprintf(stderr, " <time adjustment> is in relative seconds (e.g. -0.5)\n");
327 fprintf(stderr, " -E <error probability> set the probability (between 0.0 and 1.0 incl.)\n");
328 fprintf(stderr, " that a particular packet byte will be randomly changed\n");
329 fprintf(stderr, "\n");
330 fprintf(stderr, "Output File(s):\n");
331 fprintf(stderr, " -c <packets per file> split the packet output to different files,\n");
332 fprintf(stderr, " based on uniform packet counts \n");
333 fprintf(stderr, " with a maximum of <packets per file> each\n");
334 fprintf(stderr, " -i <seconds per file> split the packet output to different files,\n");
335 fprintf(stderr, " based on uniform time intervals \n");
336 fprintf(stderr, " with a maximum of <seconds per file> each\n");
337 fprintf(stderr, " -F <capture type> set the output file type, default is libpcap\n");
338 fprintf(stderr, " an empty \"-F\" option will list the file types\n");
339 fprintf(stderr, " -T <encap type> set the output file encapsulation type,\n");
340 fprintf(stderr, " default is the same as the input file\n");
341 fprintf(stderr, " an empty \"-T\" option will list the encapsulation types\n");
342 fprintf(stderr, "\n");
343 fprintf(stderr, "Miscellaneous:\n");
344 fprintf(stderr, " -h display this help and exit\n");
345 fprintf(stderr, " -v verbose output\n");
346 fprintf(stderr, "\n");
350 list_capture_types(void) {
353 fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
354 for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
355 if (wtap_dump_can_open(i))
356 fprintf(stderr, " %s - %s\n",
357 wtap_file_type_short_string(i), wtap_file_type_string(i));
362 list_encap_types(void) {
366 fprintf(stderr, "editcap: The available encapsulation types for \"T\":\n");
367 for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
368 string = wtap_encap_short_string(i);
370 fprintf(stderr, " %s - %s\n",
371 string, wtap_encap_string(i));
376 * Don't report failures to load plugins because most (non-wiretap) plugins
377 * *should* fail to load (because we're not linked against libwireshark and
378 * dissector plugins need libwireshark).
381 failure_message(const char *msg_format _U_, va_list ap _U_)
387 main(int argc, char *argv[])
396 unsigned int snaplen = 0; /* No limit */
397 unsigned int choplen = 0; /* No chop */
401 struct wtap_pkthdr snap_phdr;
402 const struct wtap_pkthdr *phdr;
405 int split_packet_count = 0;
406 int written_count = 0;
408 size_t filenamelen = 0;
410 int secs_per_block = 0;
412 nstime_t block_start;
415 char* init_progfile_dir_error;
419 * Get credential information for later use.
421 get_credential_info();
424 /* Register wiretap plugins */
425 if ((init_progfile_dir_error = init_progfile_dir(argv[0]))) {
426 g_warning("capinfos: init_progfile_dir(): %s", init_progfile_dir_error);
427 g_free(init_progfile_dir_error);
429 init_report_err(failure_message,NULL,NULL);
434 /* Process the options */
435 while ((opt = getopt(argc, argv, "A:B:c:C:dE:F:hrs:i:t:T:v")) !=-1) {
440 err_prob = strtod(optarg, &p);
441 if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
442 fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
446 srand( (unsigned int) (time(NULL) + getpid()) );
450 out_file_type = wtap_short_string_to_file_type(optarg);
451 if (out_file_type < 0) {
452 fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
454 list_capture_types();
460 split_packet_count = strtol(optarg, &p, 10);
461 if (p == optarg || *p != '\0') {
462 fprintf(stderr, "editcap: \"%s\" isn't a valid packet count\n",
466 if (split_packet_count <= 0) {
467 fprintf(stderr, "editcap: \"%d\" packet count must be larger than zero\n",
474 choplen = strtol(optarg, &p, 10);
475 if (p == optarg || *p != '\0') {
476 fprintf(stderr, "editcap: \"%s\" isn't a valid chop length\n",
484 for (i = 0; i < DUP_DEPTH; i++) {
485 memset(&fd_hash[i].digest, 0, 16);
490 case '?': /* Bad options if GNU getopt */
493 list_capture_types();
510 keep_em = !keep_em; /* Just invert */
514 snaplen = strtol(optarg, &p, 10);
515 if (p == optarg || *p != '\0') {
516 fprintf(stderr, "editcap: \"%s\" isn't a valid snapshot length\n",
523 set_time_adjustment(optarg);
527 out_frame_type = wtap_short_string_to_encap(optarg);
528 if (out_frame_type < 0) {
529 fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
537 verbose = !verbose; /* Just invert */
540 case 'i': /* break capture file based on time interval */
541 secs_per_block = atoi(optarg);
542 nstime_set_unset(&block_start);
543 if(secs_per_block <= 0) {
544 fprintf(stderr, "editcap: \"%s\" isn't a valid time interval\n\n", optarg);
553 memset(&starttm,0,sizeof(struct tm));
555 if(!strptime(optarg,"%Y-%m-%d %T",&starttm)) {
556 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
560 check_startstop = TRUE;
561 starttm.tm_isdst = -1;
563 starttime = mktime(&starttm);
571 memset(&stoptm,0,sizeof(struct tm));
573 if(!strptime(optarg,"%Y-%m-%d %T",&stoptm)) {
574 fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
577 check_startstop = TRUE;
578 stoptm.tm_isdst = -1;
579 stoptime = mktime(&stoptm);
587 printf("Optind = %i, argc = %i\n", optind, argc);
590 if ((argc - optind) < 1) {
597 if (check_startstop && !stoptime) {
599 /* XXX: will work until 2035 */
600 memset(&stoptm,0,sizeof(struct tm));
601 stoptm.tm_year = 135;
605 stoptime = mktime(&stoptm);
608 if (starttime > stoptime) {
609 fprintf(stderr, "editcap: start time is after the stop time\n");
613 if (split_packet_count > 0 && secs_per_block > 0) {
614 fprintf(stderr, "editcap: can't split on both packet count and time interval\n");
615 fprintf(stderr, "editcap: at the same time\n");
619 wth = wtap_open_offline(argv[optind], &err, &err_info, FALSE);
622 fprintf(stderr, "editcap: Can't open %s: %s\n", argv[optind],
626 case WTAP_ERR_UNSUPPORTED:
627 case WTAP_ERR_UNSUPPORTED_ENCAP:
628 case WTAP_ERR_BAD_RECORD:
629 fprintf(stderr, "(%s)\n", err_info);
638 fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
639 wtap_file_type_string(wtap_file_type(wth)));
643 * Now, process the rest, if any ... we only write if there is an extra
647 if ((argc - optind) >= 2) {
649 if (out_frame_type == -2)
650 out_frame_type = wtap_file_encap(wth);
652 if (split_packet_count > 0) {
653 filenamelen = strlen(argv[optind+1]) + 20;
654 filename = (char *) g_malloc(filenamelen);
658 g_snprintf(filename, filenamelen, "%s-%05d", argv[optind+1], 0);
660 if (secs_per_block > 0) {
661 filenamelen = strlen(argv[optind+1]) + 7;
662 filename = (char *) g_malloc(filenamelen);
666 g_snprintf(filename, filenamelen, "%s-%05d", argv[optind+1], block_cnt);
669 filename = argv[optind+1];
673 pdh = wtap_dump_open(filename, out_file_type,
674 out_frame_type, wtap_snapshot_length(wth),
675 FALSE /* compressed */, &err);
678 fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
683 for (i = optind + 2; i < argc; i++)
684 if (add_selection(argv[i]) == FALSE)
687 while (wtap_read(wth, &err, &err_info, &data_offset)) {
689 if (secs_per_block > 0) {
690 phdr = wtap_phdr(wth);
692 if (nstime_is_unset(&block_start)) { /* should only be the first packet */
693 block_start.secs = phdr->ts.secs;
694 block_start.nsecs = phdr->ts.nsecs;
697 while ((phdr->ts.secs - block_start.secs > secs_per_block) ||
698 (phdr->ts.secs - block_start.secs == secs_per_block &&
699 phdr->ts.nsecs >= block_start.nsecs )) { /* time for the next file */
701 if (!wtap_dump_close(pdh, &err)) {
702 fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
706 block_start.secs = block_start.secs + secs_per_block; /* reset for next interval */
707 g_snprintf(filename, filenamelen, "%s-%05d",argv[optind+1], ++block_cnt);
710 fprintf(stderr, "Continuing writing in file %s\n", filename);
713 pdh = wtap_dump_open(filename, out_file_type,
714 out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
717 fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
724 if (split_packet_count > 0 && (written_count % split_packet_count == 0)) {
725 if (!wtap_dump_close(pdh, &err)) {
727 fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
732 g_snprintf(filename, filenamelen, "%s-%05d",argv[optind+1], count / split_packet_count);
735 fprintf(stderr, "Continuing writing in file %s\n", filename);
738 pdh = wtap_dump_open(filename, out_file_type,
739 out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
742 fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
748 check_ts = check_timestamp(wth);
750 if ( ((check_startstop && check_ts) || (!check_startstop && !check_ts)) && ((!selected(count) && !keep_em) ||
751 (selected(count) && keep_em)) ) {
754 printf("Packet: %u\n", count);
756 /* We simply write it, perhaps after truncating it; we could do other
757 things, like modify it. */
759 phdr = wtap_phdr(wth);
761 if (choplen != 0 && phdr->caplen > choplen) {
763 snap_phdr.caplen -= choplen;
767 if (snaplen != 0 && phdr->caplen > snaplen) {
769 snap_phdr.caplen = snaplen;
773 /* assume that if the frame's tv_sec is 0, then
774 * the timestamp isn't supported */
775 if (phdr->ts.secs > 0 && time_adj.tv.tv_sec != 0) {
777 if (time_adj.is_negative)
778 snap_phdr.ts.secs -= time_adj.tv.tv_sec;
780 snap_phdr.ts.secs += time_adj.tv.tv_sec;
784 /* assume that if the frame's tv_sec is 0, then
785 * the timestamp isn't supported */
786 if (phdr->ts.secs > 0 && time_adj.tv.tv_usec != 0) {
788 if (time_adj.is_negative) { /* subtract */
789 if (snap_phdr.ts.nsecs/1000 < time_adj.tv.tv_usec) { /* borrow */
791 snap_phdr.ts.nsecs += ONE_MILLION * 1000;
793 snap_phdr.ts.nsecs -= time_adj.tv.tv_usec * 1000;
795 if (snap_phdr.ts.nsecs + time_adj.tv.tv_usec * 1000 > ONE_MILLION * 1000) {
798 snap_phdr.ts.nsecs += (time_adj.tv.tv_usec - ONE_MILLION) * 1000;
800 snap_phdr.ts.nsecs += time_adj.tv.tv_usec * 1000;
807 buf = wtap_buf_ptr(wth);
808 if (is_duplicate(buf, phdr->caplen)) {
810 printf("Skipping duplicate: %u\n", count);
816 /* Random error mutation */
817 if (err_prob > 0.0) {
818 int real_data_start = 0;
819 buf = wtap_buf_ptr(wth);
820 /* Protect non-protocol data */
821 if (wtap_file_type(wth) == WTAP_FILE_CATAPULT_DCT2000) {
822 real_data_start = find_dct2000_real_data(buf);
824 for (i = real_data_start; i < (int) phdr->caplen; i++) {
825 if (rand() <= err_prob * RAND_MAX) {
826 err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
828 if (err_type < ERR_WT_BIT) {
829 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
830 err_type = ERR_WT_TOTAL;
832 err_type -= ERR_WT_BYTE;
835 if (err_type < ERR_WT_BYTE) {
836 buf[i] = rand() / (RAND_MAX / 255 + 1);
837 err_type = ERR_WT_TOTAL;
839 err_type -= ERR_WT_BYTE;
842 if (err_type < ERR_WT_ALNUM) {
843 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
844 err_type = ERR_WT_TOTAL;
846 err_type -= ERR_WT_ALNUM;
849 if (err_type < ERR_WT_FMT) {
850 if ((unsigned int)i < phdr->caplen - 2)
851 strncpy((char*) &buf[i], "%s", 2);
852 err_type = ERR_WT_TOTAL;
854 err_type -= ERR_WT_FMT;
857 if (err_type < ERR_WT_AA) {
858 for (j = i; j < (int) phdr->caplen; j++) {
867 if (!wtap_dump(pdh, phdr, wtap_pseudoheader(wth), wtap_buf_ptr(wth),
869 fprintf(stderr, "editcap: Error writing to %s: %s\n",
870 filename, wtap_strerror(err));
879 /* Print a message noting that the read failed somewhere along the line. */
881 "editcap: An error occurred while reading \"%s\": %s.\n",
882 argv[optind], wtap_strerror(err));
885 case WTAP_ERR_UNSUPPORTED:
886 case WTAP_ERR_UNSUPPORTED_ENCAP:
887 case WTAP_ERR_BAD_RECORD:
888 fprintf(stderr, "(%s)\n", err_info);
894 if (!wtap_dump_close(pdh, &err)) {
896 fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
906 /* Skip meta-information read from file to return offset of real
908 static int find_dct2000_real_data(guint8 *buf)
912 for (n=0; buf[n] != '\0'; n++); /* Context name */
914 n++; /* Context port number */
915 for (; buf[n] != '\0'; n++); /* Timestamp */
917 for (; buf[n] != '\0'; n++); /* Protocol name */
919 for (; buf[n] != '\0'; n++); /* Variant number (as string) */
921 for (; buf[n] != '\0'; n++); /* Outhdr (as string) */
923 n += 2; /* Direction & encap */