Removed a debug printf line.
[obnox/wireshark/wip.git] / editcap.c
1 /* Edit capture files.  We can delete packets, adjust timestamps, or
2  * simply convert from one format to another format.
3  *
4  * $Id$
5  *
6  * Originally written by Richard Sharpe.
7  * Improved by Guy Harris.
8  * Further improved by Richard Sharpe.
9  */
10
11 #ifdef HAVE_CONFIG_H
12 #include "config.h"
13 #endif
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <stdarg.h>
19
20 /*
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
23  * yet defined.
24  */
25
26 #ifndef __USE_XOPEN
27 #  define __USE_XOPEN
28 #endif
29
30 #include <time.h>
31 #include <glib.h>
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37
38
39 #ifdef HAVE_SYS_TIME_H
40 #include <sys/time.h>
41 #endif
42
43 #include "wtap.h"
44
45 #ifdef NEED_GETOPT_H
46 #include "getopt.h"
47 #endif
48
49 #ifdef _WIN32
50 #include <process.h>    /* getpid */
51 #endif
52
53 #ifdef NEED_STRPTIME_H
54 # include "strptime.h"
55 #endif
56
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>
62
63 #include "svnversion.h"
64
65 /*
66  * Some globals so we can pass things to various routines
67  */
68
69 struct select_item {
70
71   int inclusive;
72   int first, second;
73
74 };
75
76
77 /*
78  * Duplicate frame detection
79  */
80 typedef struct _fd_hash_t {
81   md5_byte_t digest[16];
82   guint32 len;
83 } fd_hash_t;
84
85 #define DUP_DEPTH 5
86 fd_hash_t fd_hash[DUP_DEPTH];
87 int cur_dup = 0;
88
89 #define ONE_MILLION 1000000
90
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)
100
101 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
102 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
103
104
105 struct time_adjustment {
106   struct timeval tv;
107   int is_negative;
108 };
109
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;
123
124 static int find_dct2000_real_data(guint8 *buf);
125
126 /* Add a selection item, a simple parser for now */
127 static gboolean
128 add_selection(char *sel)
129 {
130   char *locn;
131   char *next;
132
133   if (++max_selected >= MAX_SELECTIONS) {
134     /* Let the user know we stopped selecting */
135     printf("Out of room for packet selections!\n");
136     return(FALSE);
137   }
138
139   printf("Add_Selected: %s\n", sel);
140
141   if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
142
143     printf("Not inclusive ...");
144
145     selectfrm[max_selected].inclusive = 0;
146     selectfrm[max_selected].first = atoi(sel);
147
148     printf(" %i\n", selectfrm[max_selected].first);
149
150   }
151   else {
152
153     printf("Inclusive ...");
154
155     next = locn + 1;
156     selectfrm[max_selected].inclusive = 1;
157     selectfrm[max_selected].first = atoi(sel);
158     selectfrm[max_selected].second = atoi(next);
159
160     printf(" %i, %i\n", selectfrm[max_selected].first, selectfrm[max_selected].second);
161
162   }
163
164   return(TRUE);
165 }
166
167 /* Was the packet selected? */
168
169 static int
170 selected(int recno)
171 {
172   int i = 0;
173
174   for (i = 0; i<= max_selected; i++) {
175
176     if (selectfrm[i].inclusive) {
177       if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
178         return 1;
179     }
180     else {
181       if (recno == selectfrm[i].first)
182         return 1;
183     }
184   }
185
186   return 0;
187
188 }
189
190 /* is the packet in the selected timeframe */
191 static gboolean
192 check_timestamp(wtap *wth)
193 {
194   struct wtap_pkthdr* pkthdr = wtap_phdr(wth);
195
196   return ( pkthdr->ts.secs >= starttime ) && ( pkthdr->ts.secs <= stoptime );
197 }
198
199 static void
200 set_time_adjustment(char *optarg)
201 {
202   char *frac, *end;
203   long val;
204   int frac_digits;
205
206   if (!optarg)
207     return;
208
209   /* skip leading whitespace */
210   while (*optarg == ' ' || *optarg == '\t') {
211       optarg++;
212   }
213
214   /* check for a negative adjustment */
215   if (*optarg == '-') {
216       time_adj.is_negative = 1;
217       optarg++;
218   }
219
220   /* collect whole number of seconds, if any */
221   if (*optarg == '.') {         /* only fractional (i.e., .5 is ok) */
222       val  = 0;
223       frac = optarg;
224   } else {
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",
228                   optarg);
229           exit(1);
230       }
231       if (val < 0) {            /* implies '--' since we caught '-' above  */
232           fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
233                   optarg);
234           exit(1);
235       }
236   }
237   time_adj.tv.tv_sec = val;
238
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",
245               optarg);
246       exit(1);
247     }
248   }
249   else {
250     return;                     /* no fractional digits */
251   }
252
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 */
258       val *= 10;
259       frac_digits++;
260     }
261   }
262   time_adj.tv.tv_usec = val;
263 }
264
265 static gboolean
266 is_duplicate(guint8* fd, guint32 len) {
267   int i;
268   md5_state_t ms;
269
270   cur_dup++;
271   if (cur_dup >= DUP_DEPTH)
272     cur_dup = 0;
273
274   /* Calculate our digest */
275   md5_init(&ms);
276   md5_append(&ms, fd, len);
277   md5_finish(&ms, fd_hash[cur_dup].digest);
278
279   fd_hash[cur_dup].len = len;
280
281   /* Look for duplicates */
282   for (i = 0; i < DUP_DEPTH; i++) {
283     if (i == cur_dup)
284       continue;
285
286     if (fd_hash[i].len == fd_hash[cur_dup].len &&
287         memcmp(fd_hash[i].digest, fd_hash[cur_dup].digest, 16) == 0) {
288       return TRUE;
289     }
290   }
291
292   return FALSE;
293 }
294
295 static void
296 usage(void)
297 {
298   fprintf(stderr, "Editcap %s"
299 #ifdef SVNVERSION
300           " (" SVNVERSION ")"
301 #endif
302           "\n", VERSION);
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");
339 }
340
341 static void
342 list_capture_types(void) {
343     int i;
344
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));
350     }
351 }
352
353 static void
354 list_encap_types(void) {
355     int i;
356     const char *string;
357
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);
361         if (string != NULL)
362           fprintf(stderr, "    %s - %s\n",
363             string, wtap_encap_string(i));
364     }
365 }
366
367 /*
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).
371  */
372 static void
373 failure_message(const char *msg_format _U_, va_list ap _U_)
374 {
375         return;
376 }
377
378 int
379 main(int argc, char *argv[])
380 {
381   wtap *wth;
382   int i, j, err;
383   gchar *err_info;
384   extern char *optarg;
385   extern int optind;
386   int opt;
387   char *p;
388   unsigned int snaplen = 0;             /* No limit               */
389   unsigned int choplen = 0;             /* No chop                */
390   wtap_dumper *pdh;
391   int count = 1;
392   gint64 data_offset;
393   struct wtap_pkthdr snap_phdr;
394   const struct wtap_pkthdr *phdr;
395   int err_type;
396   guint8 *buf;
397   int split_packet_count = 0;
398   int written_count = 0;
399   char *filename;
400   size_t filenamelen = 0;
401   gboolean check_ts;
402 #ifdef HAVE_PLUGINS
403   char* init_progfile_dir_error;
404 #endif
405
406   /*
407    * Get credential information for later use.
408    */
409   get_credential_info();
410
411 #ifdef HAVE_PLUGINS
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);
416   } else {
417     init_report_err(failure_message,NULL,NULL);
418     init_plugins();
419   }
420 #endif
421
422   /* Process the options */
423   while ((opt = getopt(argc, argv, "A:B:c:C:dE:F:hrs:t:T:v")) !=-1) {
424
425     switch (opt) {
426
427     case 'E':
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",
431             optarg);
432         exit(1);
433       }
434       srand( (unsigned int) (time(NULL) + getpid()) );
435       break;
436
437     case 'F':
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",
441             optarg);
442         list_capture_types();
443         exit(1);
444       }
445       break;
446
447     case 'c':
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",
451             optarg);
452         exit(1);
453       }
454       if (split_packet_count <= 0) {
455         fprintf(stderr, "editcap: \"%d\" packet count must be larger than zero\n",
456             split_packet_count);
457         exit(1);
458       }
459       break;
460
461     case 'C':
462       choplen = strtol(optarg, &p, 10);
463       if (p == optarg || *p != '\0') {
464         fprintf(stderr, "editcap: \"%s\" isn't a valid chop length\n",
465             optarg);
466         exit(1);
467       }
468       break;
469
470     case 'd':
471       dup_detect = TRUE;
472       for (i = 0; i < DUP_DEPTH; i++) {
473         memset(&fd_hash[i].digest, 0, 16);
474         fd_hash[i].len = 0;
475       }
476       break;
477
478     case '?':              /* Bad options if GNU getopt */
479       switch(optopt) {
480       case'F':
481         list_capture_types();
482         break;
483       case'T':
484         list_encap_types();
485         break;
486       default:
487         usage();
488       }
489       exit(1);
490       break;
491
492     case 'h':
493       usage();
494       exit(1);
495       break;
496
497     case 'r':
498       keep_em = !keep_em;  /* Just invert */
499       break;
500
501     case 's':
502       snaplen = strtol(optarg, &p, 10);
503       if (p == optarg || *p != '\0') {
504         fprintf(stderr, "editcap: \"%s\" isn't a valid snapshot length\n",
505                 optarg);
506         exit(1);
507       }
508       break;
509
510     case 't':
511       set_time_adjustment(optarg);
512       break;
513
514     case 'T':
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",
518             optarg);
519         list_encap_types();
520         exit(1);
521       }
522       break;
523
524     case 'v':
525       verbose = !verbose;  /* Just invert */
526       break;
527
528     case 'A':
529     {
530       struct tm starttm;
531
532       memset(&starttm,0,sizeof(struct tm));
533
534       if(!strptime(optarg,"%Y-%m-%d %T",&starttm)) {
535         fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
536         exit(1);
537       }
538
539       check_startstop = TRUE;
540       starttm.tm_isdst = -1;
541
542       starttime = mktime(&starttm);
543       break;
544     }
545
546     case 'B':
547     {
548       struct tm stoptm;
549
550       memset(&stoptm,0,sizeof(struct tm));
551
552       if(!strptime(optarg,"%Y-%m-%d %T",&stoptm)) {
553         fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
554         exit(1);
555       }
556       check_startstop = TRUE;
557       stoptm.tm_isdst = -1;
558       stoptime = mktime(&stoptm);
559       break;
560     }
561     }
562
563   }
564
565 #ifdef DEBUG
566   printf("Optind = %i, argc = %i\n", optind, argc);
567 #endif
568
569   if ((argc - optind) < 1) {
570
571     usage();
572     exit(1);
573
574   }
575
576   if (check_startstop && !stoptime) {
577     struct tm stoptm;
578     /* XXX: will work until 2035 */
579     memset(&stoptm,0,sizeof(struct tm));
580     stoptm.tm_year = 135;
581     stoptm.tm_mday = 31;
582     stoptm.tm_mon = 11;
583
584     stoptime = mktime(&stoptm);
585   }
586
587   if (starttime > stoptime) {
588     fprintf(stderr, "editcap: start time is after the stop time\n");
589     exit(1);
590   }
591
592   wth = wtap_open_offline(argv[optind], &err, &err_info, FALSE);
593
594   if (!wth) {
595     fprintf(stderr, "editcap: Can't open %s: %s\n", argv[optind],
596         wtap_strerror(err));
597     switch (err) {
598
599     case WTAP_ERR_UNSUPPORTED:
600     case WTAP_ERR_UNSUPPORTED_ENCAP:
601     case WTAP_ERR_BAD_RECORD:
602       fprintf(stderr, "(%s)\n", err_info);
603       g_free(err_info);
604       break;
605     }
606     exit(1);
607
608   }
609
610   if (verbose) {
611     fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
612             wtap_file_type_string(wtap_file_type(wth)));
613   }
614
615   /*
616    * Now, process the rest, if any ... we only write if there is an extra
617    * argument or so ...
618    */
619
620   if ((argc - optind) >= 2) {
621
622     if (out_frame_type == -2)
623       out_frame_type = wtap_file_encap(wth);
624
625     if (split_packet_count > 0) {
626       filenamelen = strlen(argv[optind+1]) + 20;
627       filename = (char *) g_malloc(filenamelen);
628       if (!filename) {
629         exit(5);
630       }
631       g_snprintf(filename, filenamelen, "%s-%05d", argv[optind+1], 0);
632     } else {
633       filename = argv[optind+1];
634     }
635
636     pdh = wtap_dump_open(filename, out_file_type,
637         out_frame_type, wtap_snapshot_length(wth),
638         FALSE /* compressed */, &err);
639     if (pdh == NULL) {
640
641       fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
642               wtap_strerror(err));
643       exit(1);
644     }
645
646     for (i = optind + 2; i < argc; i++)
647       if (add_selection(argv[i]) == FALSE)
648         break;
649
650     while (wtap_read(wth, &err, &err_info, &data_offset)) {
651
652       if (split_packet_count > 0 && (written_count % split_packet_count == 0)) {
653         if (!wtap_dump_close(pdh, &err)) {
654
655           fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
656               wtap_strerror(err));
657           exit(1);
658         }
659
660         g_snprintf(filename, filenamelen, "%s-%05d",argv[optind+1], count / split_packet_count);
661
662         if (verbose) {
663           fprintf(stderr, "Continuing writing in file %s\n", filename);
664         }
665
666         pdh = wtap_dump_open(filename, out_file_type,
667             out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
668         if (pdh == NULL) {
669
670           fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
671               wtap_strerror(err));
672           exit(1);
673         }
674       }
675
676       check_ts = check_timestamp(wth);
677
678       if ( ((check_startstop && check_ts) || (!check_startstop && !check_ts)) && ((!selected(count) && !keep_em) ||
679           (selected(count) && keep_em)) ) {
680
681         if (verbose)
682           printf("Packet: %u\n", count);
683
684         /* We simply write it, perhaps after truncating it; we could do other
685            things, like modify it. */
686
687         phdr = wtap_phdr(wth);
688
689         if (choplen != 0 && phdr->caplen > choplen) {
690           snap_phdr = *phdr;
691           snap_phdr.caplen -= choplen;
692           phdr = &snap_phdr;
693         }
694
695         if (snaplen != 0 && phdr->caplen > snaplen) {
696           snap_phdr = *phdr;
697           snap_phdr.caplen = snaplen;
698           phdr = &snap_phdr;
699         }
700
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) {
704           snap_phdr = *phdr;
705           if (time_adj.is_negative)
706             snap_phdr.ts.secs -= time_adj.tv.tv_sec;
707           else
708             snap_phdr.ts.secs += time_adj.tv.tv_sec;
709           phdr = &snap_phdr;
710         }
711
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) {
715           snap_phdr = *phdr;
716           if (time_adj.is_negative) { /* subtract */
717             if (snap_phdr.ts.nsecs/1000 < time_adj.tv.tv_usec) { /* borrow */
718               snap_phdr.ts.secs--;
719               snap_phdr.ts.nsecs += ONE_MILLION * 1000;
720             }
721             snap_phdr.ts.nsecs -= time_adj.tv.tv_usec * 1000;
722           } else {                  /* add */
723             if (snap_phdr.ts.nsecs + time_adj.tv.tv_usec * 1000 > ONE_MILLION * 1000) {
724               /* carry */
725               snap_phdr.ts.secs++;
726               snap_phdr.ts.nsecs += (time_adj.tv.tv_usec - ONE_MILLION) * 1000;
727             } else {
728               snap_phdr.ts.nsecs += time_adj.tv.tv_usec * 1000;
729             }
730           }
731           phdr = &snap_phdr;
732         }
733
734         if (dup_detect) {
735           buf = wtap_buf_ptr(wth);
736           if (is_duplicate(buf, phdr->caplen)) {
737             if (verbose)
738               printf("Skipping duplicate: %u\n", count);
739             count++;
740             continue;
741           }
742         }
743
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);
751           }
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);
755
756               if (err_type < ERR_WT_BIT) {
757                 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
758                 err_type = ERR_WT_TOTAL;
759               } else {
760                 err_type -= ERR_WT_BYTE;
761               }
762
763               if (err_type < ERR_WT_BYTE) {
764                 buf[i] = rand() / (RAND_MAX / 255 + 1);
765                 err_type = ERR_WT_TOTAL;
766               } else {
767                 err_type -= ERR_WT_BYTE;
768               }
769
770               if (err_type < ERR_WT_ALNUM) {
771                 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
772                 err_type = ERR_WT_TOTAL;
773               } else {
774                 err_type -= ERR_WT_ALNUM;
775               }
776
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;
781               } else {
782                 err_type -= ERR_WT_FMT;
783               }
784
785               if (err_type < ERR_WT_AA) {
786                 for (j = i; j < (int) phdr->caplen; j++) {
787                   buf[j] = 0xAA;
788                 }
789                 i = phdr->caplen;
790               }
791             }
792           }
793         }
794
795         if (!wtap_dump(pdh, phdr, wtap_pseudoheader(wth), wtap_buf_ptr(wth),
796                        &err)) {
797           fprintf(stderr, "editcap: Error writing to %s: %s\n",
798                   filename, wtap_strerror(err));
799           exit(1);
800         }
801         written_count++;
802       }
803       count++;
804     }
805
806     if (err != 0) {
807       /* Print a message noting that the read failed somewhere along the line. */
808       fprintf(stderr,
809               "editcap: An error occurred while reading \"%s\": %s.\n",
810               argv[optind], wtap_strerror(err));
811       switch (err) {
812
813       case WTAP_ERR_UNSUPPORTED:
814       case WTAP_ERR_UNSUPPORTED_ENCAP:
815       case WTAP_ERR_BAD_RECORD:
816         fprintf(stderr, "(%s)\n", err_info);
817         break;
818       }
819     }
820
821     if (!wtap_dump_close(pdh, &err)) {
822
823       fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
824           wtap_strerror(err));
825       exit(1);
826
827     }
828   }
829
830   return 0;
831 }
832
833 /* Skip meta-information read from file to return offset of real
834    protocol data */
835 static int find_dct2000_real_data(guint8 *buf)
836 {
837   int n=0;
838
839   for (n=0; buf[n] != '\0'; n++);   /* Context name */
840   n++;
841   n++;                              /* Context port number */
842   for (; buf[n] != '\0'; n++);      /* Timestamp */
843   n++;
844   for (; buf[n] != '\0'; n++);      /* Protocol name */
845   n++;
846   for (; buf[n] != '\0'; n++);      /* Variant number (as string) */
847   n++;
848   for (; buf[n] != '\0'; n++);      /* Outhdr (as string) */
849   n++;
850   n += 2;                           /* Direction & encap */
851
852   return n;
853 }