From RD Thrush: Fix for 'editcap relies on gnu extension to strptime(3)'
[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
62 #include "svnversion.h"
63
64 /*
65  * Some globals so we can pass things to various routines
66  */
67
68 struct select_item {
69
70   int inclusive;
71   int first, second;
72
73 };
74
75
76 /*
77  * Duplicate frame detection
78  */
79 typedef struct _fd_hash_t {
80   md5_byte_t digest[16];
81   guint32 len;
82 } fd_hash_t;
83
84 #define DUP_DEPTH 5
85 fd_hash_t fd_hash[DUP_DEPTH];
86 int cur_dup = 0;
87
88 #define ONE_MILLION 1000000
89
90 /* Weights of different errors we can introduce */
91 /* We should probably make these command-line arguments */
92 /* XXX - Should we add a bit-level error? */
93 #define ERR_WT_BIT   5  /* Flip a random bit */
94 #define ERR_WT_BYTE  5  /* Substitute a random byte */
95 #define ERR_WT_ALNUM 5  /* Substitute a random character in [A-Za-z0-9] */
96 #define ERR_WT_FMT   2  /* Substitute "%s" */
97 #define ERR_WT_AA    1  /* Fill the remainder of the buffer with 0xAA */
98 #define ERR_WT_TOTAL (ERR_WT_BIT + ERR_WT_BYTE + ERR_WT_ALNUM + ERR_WT_FMT + ERR_WT_AA)
99
100 #define ALNUM_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
101 #define ALNUM_LEN (sizeof(ALNUM_CHARS) - 1)
102
103
104 struct time_adjustment {
105   struct timeval tv;
106   int is_negative;
107 };
108
109 #define MAX_SELECTIONS 512
110 static struct select_item selectfrm[MAX_SELECTIONS];
111 static int max_selected = -1;
112 static int keep_em = 0;
113 static int out_file_type = WTAP_FILE_PCAP;   /* default to "libpcap"   */
114 static int out_frame_type = -2;              /* Leave frame type alone */
115 static int verbose = 0;                      /* Not so verbose         */
116 static struct time_adjustment time_adj = {{0, 0}, 0}; /* no adjustment */
117 static double err_prob = 0.0;
118 static time_t starttime = 0;
119 static time_t stoptime = 0;
120 static gboolean check_startstop = FALSE;
121 static gboolean dup_detect = FALSE;
122
123 /* Add a selection item, a simple parser for now */
124 static gboolean
125 add_selection(char *sel)
126 {
127   char *locn;
128   char *next;
129
130   if (++max_selected >= MAX_SELECTIONS) {
131     /* Let the user know we stopped selecting */
132     printf("Out of room for packet selections!\n");
133     return(FALSE);
134   }
135
136   printf("Add_Selected: %s\n", sel);
137
138   if ((locn = strchr(sel, '-')) == NULL) { /* No dash, so a single number? */
139
140     printf("Not inclusive ...");
141
142     selectfrm[max_selected].inclusive = 0;
143     selectfrm[max_selected].first = atoi(sel);
144
145     printf(" %i\n", selectfrm[max_selected].first);
146
147   }
148   else {
149
150     printf("Inclusive ...");
151
152     next = locn + 1;
153     selectfrm[max_selected].inclusive = 1;
154     selectfrm[max_selected].first = atoi(sel);
155     selectfrm[max_selected].second = atoi(next);
156
157     printf(" %i, %i\n", selectfrm[max_selected].first, selectfrm[max_selected].second);
158
159   }
160
161   return(TRUE);
162 }
163
164 /* Was the packet selected? */
165
166 static int
167 selected(int recno)
168 {
169   int i = 0;
170
171   for (i = 0; i<= max_selected; i++) {
172
173     if (selectfrm[i].inclusive) {
174       if (selectfrm[i].first <= recno && selectfrm[i].second >= recno)
175         return 1;
176     }
177     else {
178       if (recno == selectfrm[i].first)
179         return 1;
180     }
181   }
182
183   return 0;
184
185 }
186
187 /* is the packet in the selected timeframe */
188 static gboolean
189 check_timestamp(wtap *wth)
190 {
191   static int i = 0;
192   struct wtap_pkthdr* pkthdr = wtap_phdr(wth);
193
194   if (!((i++)%250))
195     printf("== %d starttime=%lu stoptime=%lu ts=%lu\n",i,
196            (unsigned long)starttime,
197            (unsigned long)stoptime,
198            (unsigned long)pkthdr->ts.secs);
199   return ( pkthdr->ts.secs >= starttime ) && ( pkthdr->ts.secs <= stoptime );
200 }
201
202 static void
203 set_time_adjustment(char *optarg)
204 {
205   char *frac, *end;
206   long val;
207   int frac_digits;
208
209   if (!optarg)
210     return;
211
212   /* skip leading whitespace */
213   while (*optarg == ' ' || *optarg == '\t') {
214       optarg++;
215   }
216
217   /* check for a negative adjustment */
218   if (*optarg == '-') {
219       time_adj.is_negative = 1;
220       optarg++;
221   }
222
223   /* collect whole number of seconds, if any */
224   if (*optarg == '.') {         /* only fractional (i.e., .5 is ok) */
225       val  = 0;
226       frac = optarg;
227   } else {
228       val = strtol(optarg, &frac, 10);
229       if (frac == NULL || frac == optarg || val == LONG_MIN || val == LONG_MAX) {
230           fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
231                   optarg);
232           exit(1);
233       }
234       if (val < 0) {            /* implies '--' since we caught '-' above  */
235           fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
236                   optarg);
237           exit(1);
238       }
239   }
240   time_adj.tv.tv_sec = val;
241
242   /* now collect the partial seconds, if any */
243   if (*frac != '\0') {             /* chars left, so get fractional part */
244     val = strtol(&(frac[1]), &end, 10);
245     if (*frac != '.' || end == NULL || end == frac
246         || val < 0 || val > ONE_MILLION || val == LONG_MIN || val == LONG_MAX) {
247       fprintf(stderr, "editcap: \"%s\" isn't a valid time adjustment\n",
248               optarg);
249       exit(1);
250     }
251   }
252   else {
253     return;                     /* no fractional digits */
254   }
255
256   /* adjust fractional portion from fractional to numerator
257    * e.g., in "1.5" from 5 to 500000 since .5*10^6 = 500000 */
258   if (frac && end) {            /* both are valid */
259     frac_digits = end - frac - 1;   /* fractional digit count (remember '.') */
260     while(frac_digits < 6) {    /* this is frac of 10^6 */
261       val *= 10;
262       frac_digits++;
263     }
264   }
265   time_adj.tv.tv_usec = val;
266 }
267
268 static gboolean
269 is_duplicate(guint8* fd, guint32 len) {
270   int i;
271   md5_state_t ms;
272
273   cur_dup++;
274   if (cur_dup >= DUP_DEPTH)
275     cur_dup = 0;
276
277   /* Calculate our digest */
278   md5_init(&ms);
279   md5_append(&ms, fd, len);
280   md5_finish(&ms, fd_hash[cur_dup].digest);
281
282   fd_hash[cur_dup].len = len;
283
284   /* Look for duplicates */
285   for (i = 0; i < DUP_DEPTH; i++) {
286     if (i == cur_dup)
287       continue;
288
289     if (fd_hash[i].len == fd_hash[cur_dup].len &&
290         memcmp(fd_hash[i].digest, fd_hash[cur_dup].digest, 16) == 0) {
291       return TRUE;
292     }
293   }
294
295   return FALSE;
296 }
297
298 static void usage(void)
299 {
300   fprintf(stderr, "Editcap %s"
301 #ifdef SVNVERSION
302           " (" SVNVERSION ")"
303 #endif
304           "\n", VERSION);
305   fprintf(stderr, "Edit and/or translate the format of capture files.\n");
306   fprintf(stderr, "See http://www.wireshark.org for more information.\n");
307   fprintf(stderr, "\n");
308   fprintf(stderr, "Usage: editcap [options] ... <infile> <outfile> [ <packet#>[-<packet#>] ... ]\n");
309   fprintf(stderr, "\n");
310   fprintf(stderr, "A single packet or a range of packets can be selected.\n");
311   fprintf(stderr, "\n");
312   fprintf(stderr, "Packet selection:\n");
313   fprintf(stderr, "  -r                     keep the selected packets, default is to delete them\n");
314   fprintf(stderr, "  -A <start time>        don't output packets whose timestamp is before the\n");
315   fprintf(stderr, "                         given time (format as YYYY-MM-DD hh:mm:ss)\n");
316   fprintf(stderr, "  -B <stop time>         don't output packets whose timestamp is after the\n");
317   fprintf(stderr, "                         given time (format as YYYY-MM-DD hh:mm:ss)\n");
318   fprintf(stderr, "  -d                     remove duplicate packets\n");
319   fprintf(stderr, "\n");
320   fprintf(stderr, "Packet manipulation:\n");
321   fprintf(stderr, "  -s <snaplen>           truncate each packet to max. <snaplen> bytes of data\n");
322   fprintf(stderr, "  -C <choplen>           chop each packet at the end by <choplen> bytes\n");
323   fprintf(stderr, "  -t <time adjustment>   adjust the timestamp of each packet,\n");
324   fprintf(stderr, "                         <time adjustment> is in relative seconds (e.g. -0.5)\n");
325   fprintf(stderr, "  -E <error probability> set the probability (between 0.0 and 1.0 incl.)\n");
326   fprintf(stderr, "                         that a particular packet byte will be randomly changed\n");
327   fprintf(stderr, "\n");
328   fprintf(stderr, "Output File(s):\n");
329   fprintf(stderr, "  -c <packets per file>  split the packet output to different files,\n");
330   fprintf(stderr, "                         with a maximum of <packets per file> each\n");
331   fprintf(stderr, "  -F <capture type>      set the output file type, default is libpcap\n");
332   fprintf(stderr, "                         an empty \"-F\" option will list the file types\n");
333   fprintf(stderr, "  -T <encap type>        set the output file encapsulation type,\n");
334   fprintf(stderr, "                         default is the same as the input file\n");
335   fprintf(stderr, "                         an empty \"-T\" option will list the encapsulation types\n");
336   fprintf(stderr, "\n");
337   fprintf(stderr, "Miscellaneous:\n");
338   fprintf(stderr, "  -h                     display this help and exit\n");
339   fprintf(stderr, "  -v                     verbose output\n");
340   fprintf(stderr, "\n");
341 }
342
343 static void list_capture_types(void) {
344     int i;
345
346     fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
347     for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
348       if (wtap_dump_can_open(i))
349         fprintf(stderr, "    %s - %s\n",
350           wtap_file_type_short_string(i), wtap_file_type_string(i));
351     }
352 }
353
354 static void 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 static void
368 failure_message(const char *msg_format, va_list ap)
369 {
370         fprintf(stderr, "editcap: ");
371         vfprintf(stderr, msg_format, ap);
372         fprintf(stderr, "\n");
373 }
374
375 int main(int argc, char *argv[])
376
377 {
378   wtap *wth;
379   int i, j, err;
380   gchar *err_info;
381   extern char *optarg;
382   extern int optind;
383   int opt;
384   char *p;
385   unsigned int snaplen = 0;             /* No limit               */
386   unsigned int choplen = 0;             /* No chop                */
387   wtap_dumper *pdh;
388   int count = 1;
389   gint64 data_offset;
390   struct wtap_pkthdr snap_phdr;
391   const struct wtap_pkthdr *phdr;
392   int err_type;
393   guint8 *buf;
394   int split_packet_count = 0;
395   int written_count = 0;
396   char *filename;
397   gboolean check_ts;
398 #ifdef HAVE_PLUGINS
399   char* init_progfile_dir_error;
400
401   /* Register wiretap plugins */
402   if ((init_progfile_dir_error = init_progfile_dir(argv[0]))) {
403           g_warning("capinfos: init_progfile_dir(): %s", init_progfile_dir_error);
404           g_free(init_progfile_dir_error);
405     } else {
406                 init_report_err(failure_message,NULL,NULL);
407                 init_plugins();
408     }
409 #endif
410
411   /* Process the options */
412   while ((opt = getopt(argc, argv, "A:B:c:C:dE:F:hrs:t:T:v")) !=-1) {
413
414     switch (opt) {
415
416     case 'E':
417       err_prob = strtod(optarg, &p);
418       if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
419         fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
420             optarg);
421         exit(1);
422       }
423       srand( (unsigned int) (time(NULL) + getpid()) );
424       break;
425
426     case 'F':
427       out_file_type = wtap_short_string_to_file_type(optarg);
428       if (out_file_type < 0) {
429         fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
430             optarg);
431         list_capture_types();
432         exit(1);
433       }
434       break;
435
436     case 'c':
437       split_packet_count = strtol(optarg, &p, 10);
438       if (p == optarg || *p != '\0') {
439         fprintf(stderr, "editcap: \"%s\" isn't a valid packet count\n",
440             optarg);
441         exit(1);
442       }
443       if (split_packet_count <= 0) {
444         fprintf(stderr, "editcap: \"%d\" packet count must be larger than zero\n",
445                 split_packet_count);
446         exit(1);
447       }
448       break;
449
450     case 'C':
451       choplen = strtol(optarg, &p, 10);
452       if (p == optarg || *p != '\0') {
453         fprintf(stderr, "editcap: \"%s\" isn't a valid chop length\n",
454             optarg);
455         exit(1);
456       }
457       break;
458
459     case 'd':
460       dup_detect = TRUE;
461       for (i = 0; i < DUP_DEPTH; i++) {
462         memset(&fd_hash[i].digest, 0, 16);
463         fd_hash[i].len = 0;
464       }
465       break;
466
467     case '?':              /* Bad options if GNU getopt */
468       switch(optopt) {
469       case'F':
470         list_capture_types();
471         break;
472       case'T':
473         list_encap_types();
474         break;
475       default:
476         usage();
477       }
478       exit(1);
479       break;
480
481     case 'h':
482       usage();
483       exit(1);
484       break;
485
486     case 'r':
487       keep_em = !keep_em;  /* Just invert */
488       break;
489
490     case 's':
491       snaplen = strtol(optarg, &p, 10);
492       if (p == optarg || *p != '\0') {
493         fprintf(stderr, "editcap: \"%s\" isn't a valid snapshot length\n",
494             optarg);
495         exit(1);
496       }
497       break;
498
499     case 't':
500       set_time_adjustment(optarg);
501       break;
502
503     case 'T':
504       out_frame_type = wtap_short_string_to_encap(optarg);
505       if (out_frame_type < 0) {
506         fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
507             optarg);
508         list_encap_types();
509         exit(1);
510       }
511       break;
512
513     case 'v':
514       verbose = !verbose;  /* Just invert */
515       break;
516
517     case 'A':
518     {
519       struct tm starttm;
520
521       memset(&starttm,0,sizeof(struct tm));
522
523       if(!strptime(optarg,"%Y-%m-%d %T",&starttm)) {
524         fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
525         exit(1);
526       }
527
528       check_startstop = TRUE;
529       starttm.tm_isdst = -1;
530
531       starttime = mktime(&starttm);
532       printf("=START=> given='%s' stoptime=%lu\n",optarg,(unsigned long)starttime);
533       break;
534     }
535
536     case 'B':
537     {
538       struct tm stoptm;
539
540       memset(&stoptm,0,sizeof(struct tm));
541
542       if(!strptime(optarg,"%Y-%m-%d %T",&stoptm)) {
543         fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
544         exit(1);
545       }
546       check_startstop = TRUE;
547       stoptm.tm_isdst = -1;
548       stoptime = mktime(&stoptm);
549       printf("=STOP=> given='%s' stoptime=%lu\n",optarg,(unsigned long)stoptime);
550       break;
551     }
552     }
553
554   }
555
556 #ifdef DEBUG
557   printf("Optind = %i, argc = %i\n", optind, argc);
558 #endif
559
560   if ((argc - optind) < 1) {
561
562     usage();
563     exit(1);
564
565   }
566
567   if (check_startstop && !stoptime) {
568     struct tm stoptm;
569     /* XXX: will work until 2035 */
570     memset(&stoptm,0,sizeof(struct tm));
571     stoptm.tm_year = 135;
572     stoptm.tm_mday = 31;
573     stoptm.tm_mon = 11;
574
575     stoptime = mktime(&stoptm);
576     printf("=STOP=NEVER=> stoptime=%lu\n",(unsigned long)stoptime);
577   }
578
579   if (starttime > stoptime) {
580     fprintf(stderr, "editcap: start time is after the stop time\n");
581     exit(1);
582   }
583   printf("==> stoptime=%lu stoptime=%lu\n",(unsigned long)starttime,(unsigned long)stoptime);
584
585   wth = wtap_open_offline(argv[optind], &err, &err_info, FALSE);
586
587   if (!wth) {
588     fprintf(stderr, "editcap: Can't open %s: %s\n", argv[optind],
589         wtap_strerror(err));
590     switch (err) {
591
592     case WTAP_ERR_UNSUPPORTED:
593     case WTAP_ERR_UNSUPPORTED_ENCAP:
594     case WTAP_ERR_BAD_RECORD:
595       fprintf(stderr, "(%s)\n", err_info);
596       g_free(err_info);
597       break;
598     }
599     exit(1);
600
601   }
602
603   if (verbose) {
604
605     fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
606             wtap_file_type_string(wtap_file_type(wth)));
607
608   }
609
610   /*
611    * Now, process the rest, if any ... we only write if there is an extra
612    * argument or so ...
613    */
614
615   if ((argc - optind) >= 2) {
616
617     if (out_frame_type == -2)
618       out_frame_type = wtap_file_encap(wth);
619
620     if (split_packet_count > 0) {
621       filename = (char *) malloc(strlen(argv[optind+1]) + 20);
622       if (!filename) {
623         exit(5);
624       }
625       sprintf(filename, "%s-%05d", argv[optind+1], 0);
626     } else {
627       filename = argv[optind+1];
628     }
629
630     pdh = wtap_dump_open(filename, out_file_type,
631                          out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
632     if (pdh == NULL) {
633
634       fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
635               wtap_strerror(err));
636       exit(1);
637
638     }
639
640     for (i = optind + 2; i < argc; i++)
641       if (add_selection(argv[i]) == FALSE)
642         break;
643
644     while (wtap_read(wth, &err, &err_info, &data_offset)) {
645
646       if (split_packet_count > 0 && (written_count % split_packet_count == 0)) {
647         if (!wtap_dump_close(pdh, &err)) {
648
649           fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
650                   wtap_strerror(err));
651           exit(1);
652         }
653
654         sprintf(filename, "%s-%05d",argv[optind+1], count / split_packet_count);
655
656         if (verbose) {
657           fprintf(stderr, "Continuing writing in file %s\n", filename);
658         }
659
660         pdh = wtap_dump_open(filename, out_file_type,
661                              out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
662         if (pdh == NULL) {
663
664           fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
665                   wtap_strerror(err));
666           exit(1);
667
668         }
669       }
670
671       check_ts = check_timestamp(wth);
672
673       if ( ((check_startstop && check_ts) || (!check_startstop && !check_ts)) && ((!selected(count) && !keep_em) ||
674           (selected(count) && keep_em)) ) {
675
676         if (verbose)
677           printf("Packet: %u\n", count);
678
679         /* We simply write it, perhaps after truncating it; we could do other
680            things, like modify it. */
681
682         phdr = wtap_phdr(wth);
683
684         if (choplen != 0 && phdr->caplen > choplen) {
685           snap_phdr = *phdr;
686           snap_phdr.caplen -= choplen;
687           phdr = &snap_phdr;
688         }
689
690         if (snaplen != 0 && phdr->caplen > snaplen) {
691           snap_phdr = *phdr;
692           snap_phdr.caplen = snaplen;
693           phdr = &snap_phdr;
694         }
695
696         /* assume that if the frame's tv_sec is 0, then
697          * the timestamp isn't supported */
698         if (phdr->ts.secs > 0 && time_adj.tv.tv_sec != 0) {
699           snap_phdr = *phdr;
700           if (time_adj.is_negative)
701             snap_phdr.ts.secs -= time_adj.tv.tv_sec;
702           else
703             snap_phdr.ts.secs += time_adj.tv.tv_sec;
704           phdr = &snap_phdr;
705         }
706
707         /* assume that if the frame's tv_sec is 0, then
708          * the timestamp isn't supported */
709         if (phdr->ts.secs > 0 && time_adj.tv.tv_usec != 0) {
710           snap_phdr = *phdr;
711           if (time_adj.is_negative) { /* subtract */
712             if (snap_phdr.ts.nsecs/1000 < time_adj.tv.tv_usec) { /* borrow */
713               snap_phdr.ts.secs--;
714               snap_phdr.ts.nsecs += ONE_MILLION * 1000;
715             }
716             snap_phdr.ts.nsecs -= time_adj.tv.tv_usec * 1000;
717           } else {                  /* add */
718             if (snap_phdr.ts.nsecs + time_adj.tv.tv_usec * 1000 > ONE_MILLION * 1000) {
719               /* carry */
720               snap_phdr.ts.secs++;
721               snap_phdr.ts.nsecs += (time_adj.tv.tv_usec - ONE_MILLION) * 1000;
722             } else {
723               snap_phdr.ts.nsecs += time_adj.tv.tv_usec * 1000;
724             }
725           }
726           phdr = &snap_phdr;
727         }
728
729         if (dup_detect) {
730           buf = wtap_buf_ptr(wth);
731           if (is_duplicate(buf, phdr->caplen)) {
732             if (verbose)
733               printf("Skipping duplicate: %u\n", count);
734             count++;
735             continue;
736           }
737         }
738
739         if (err_prob > 0.0) {
740           buf = wtap_buf_ptr(wth);
741           for (i = 0; i < (int) phdr->caplen; i++) {
742             if (rand() <= err_prob * RAND_MAX) {
743               err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
744
745               if (err_type < ERR_WT_BIT) {
746                 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
747                 err_type = ERR_WT_TOTAL;
748               } else {
749                 err_type -= ERR_WT_BYTE;
750               }
751
752               if (err_type < ERR_WT_BYTE) {
753                 buf[i] = rand() / (RAND_MAX / 255 + 1);
754                 err_type = ERR_WT_TOTAL;
755               } else {
756                 err_type -= ERR_WT_BYTE;
757               }
758
759               if (err_type < ERR_WT_ALNUM) {
760                 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
761                 err_type = ERR_WT_TOTAL;
762               } else {
763                 err_type -= ERR_WT_ALNUM;
764               }
765
766               if (err_type < ERR_WT_FMT) {
767                 if ((unsigned int)i < phdr->caplen - 2)
768                   strcpy((char*) &buf[i],  "%s");
769                 err_type = ERR_WT_TOTAL;
770               } else {
771                 err_type -= ERR_WT_FMT;
772               }
773
774               if (err_type < ERR_WT_AA) {
775                 for (j = i; j < (int) phdr->caplen; j++) {
776                   buf[j] = 0xAA;
777                 }
778                 i = phdr->caplen;
779               }
780             }
781           }
782         }
783
784         if (!wtap_dump(pdh, phdr, wtap_pseudoheader(wth), wtap_buf_ptr(wth),
785                        &err)) {
786
787           fprintf(stderr, "editcap: Error writing to %s: %s\n",
788                   filename, wtap_strerror(err));
789           exit(1);
790
791         }
792
793         written_count++;
794
795       }
796
797       count++;
798
799     }
800
801     if (err != 0) {
802       /* Print a message noting that the read failed somewhere along the line. */
803       fprintf(stderr,
804               "editcap: An error occurred while reading \"%s\": %s.\n",
805               argv[optind], wtap_strerror(err));
806       switch (err) {
807
808       case WTAP_ERR_UNSUPPORTED:
809       case WTAP_ERR_UNSUPPORTED_ENCAP:
810       case WTAP_ERR_BAD_RECORD:
811         fprintf(stderr, "(%s)\n", err_info);
812         break;
813       }
814     }
815
816     if (!wtap_dump_close(pdh, &err)) {
817
818       fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
819               wtap_strerror(err));
820       exit(1);
821
822     }
823   }
824
825   return 0;
826 }
827