Clean up indentation.
[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",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, "Packets:\n");
313   fprintf(stderr, "  -C <choplen>           chop each packet at the end by <choplen> bytes\n");
314   fprintf(stderr, "  -d                     remove duplicate packets\n");
315   fprintf(stderr, "  -E <error probability> set the probability (between 0.0 and 1.0 incl.)\n");
316   fprintf(stderr, "                         that a particular packet byte will be randomly changed\n");
317   fprintf(stderr, "  -r                     keep the selected packets, default is to delete them\n");
318   fprintf(stderr, "  -s <snaplen>           truncate packets to max. <snaplen> bytes of data\n");
319   fprintf(stderr, "  -t <time adjustment>   adjust the timestamp of selected packets,\n");
320   fprintf(stderr, "                         <time adjustment> is in relative seconds (e.g. -0.5)\n");
321   fprintf(stderr, "  -A <start time>        don't output packets whose timestamp is before the\n");
322   fprintf(stderr, "                         given time (format as YYYY-MM-DD hh:mm:ss)\n");
323   fprintf(stderr, "  -B <stop time>         don't output packets whose timestamp is after the\n");
324   fprintf(stderr, "                         given time (format as YYYY-MM-DD hh:mm:ss)\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 list_capture_types(void) {
342     int i;
343
344     fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
345     for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
346       if (wtap_dump_can_open(i))
347         fprintf(stderr, "    %s - %s\n",
348           wtap_file_type_short_string(i), wtap_file_type_string(i));
349     }
350 }
351
352 static void list_encap_types(void) {
353     int i;
354     const char *string;
355
356     fprintf(stderr, "editcap: The available encapsulation types for \"T\":\n");
357     for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
358         string = wtap_encap_short_string(i);
359         if (string != NULL)
360           fprintf(stderr, "    %s - %s\n",
361             string, wtap_encap_string(i));
362     }
363 }
364
365 static void
366 failure_message(const char *msg_format, va_list ap)
367 {
368         fprintf(stderr, "editcap: ");
369         vfprintf(stderr, msg_format, ap);
370         fprintf(stderr, "\n");
371 }
372
373 int main(int argc, char *argv[])
374
375 {
376   wtap *wth;
377   int i, j, err;
378   gchar *err_info;
379   extern char *optarg;
380   extern int optind;
381   int opt;
382   char *p;
383   unsigned int snaplen = 0;             /* No limit               */
384   unsigned int choplen = 0;             /* No chop                */
385   wtap_dumper *pdh;
386   int count = 1;
387   gint64 data_offset;
388   struct wtap_pkthdr snap_phdr;
389   const struct wtap_pkthdr *phdr;
390   int err_type;
391   guint8 *buf;
392   int split_packet_count = 0;
393   int written_count = 0;
394   char *filename;
395   gboolean check_ts;
396 #ifdef HAVE_PLUGINS
397   char* init_progfile_dir_error;
398   
399   /* Register wiretap plugins */
400   if ((init_progfile_dir_error = init_progfile_dir(argv[0]))) {
401           g_warning("capinfos: init_progfile_dir(): %s", init_progfile_dir_error);
402           g_free(init_progfile_dir_error);
403     } else {
404                 init_report_err(failure_message,NULL,NULL);
405                 init_plugins();
406     }
407 #endif
408   
409   /* Process the options */
410   while ((opt = getopt(argc, argv, "A:B:c:C:dE:F:hrs:t:T:v")) !=-1) {
411
412     switch (opt) {
413
414     case 'E':
415       err_prob = strtod(optarg, &p);
416       if (p == optarg || err_prob < 0.0 || err_prob > 1.0) {
417         fprintf(stderr, "editcap: probability \"%s\" must be between 0.0 and 1.0\n",
418             optarg);
419         exit(1);
420       }
421       srand( (unsigned int) (time(NULL) + getpid()) );
422       break;
423
424     case 'F':
425       out_file_type = wtap_short_string_to_file_type(optarg);
426       if (out_file_type < 0) {
427         fprintf(stderr, "editcap: \"%s\" isn't a valid capture file type\n\n",
428             optarg);
429         list_capture_types();
430         exit(1);
431       }
432       break;
433
434     case 'c':
435       split_packet_count = strtol(optarg, &p, 10);
436       if (p == optarg || *p != '\0') {
437         fprintf(stderr, "editcap: \"%s\" isn't a valid packet count\n",
438             optarg);
439         exit(1);
440       }
441       if (split_packet_count <= 0) {
442         fprintf(stderr, "editcap: \"%d\" packet count must be larger than zero\n",
443                 split_packet_count);
444         exit(1);
445       }
446       break;
447
448     case 'C':
449       choplen = strtol(optarg, &p, 10);
450       if (p == optarg || *p != '\0') {
451         fprintf(stderr, "editcap: \"%s\" isn't a valid chop length\n",
452             optarg);
453         exit(1);
454       }
455       break;
456
457     case 'd':
458       dup_detect = TRUE;
459       for (i = 0; i < DUP_DEPTH; i++) {
460         memset(&fd_hash[i].digest, 0, 16);
461         fd_hash[i].len = 0;
462       }
463       break;
464
465     case '?':              /* Bad options if GNU getopt */
466       switch(optopt) {
467       case'F':
468         list_capture_types();
469         break;
470       case'T':
471         list_encap_types();
472         break;
473       default:
474         usage();
475       }
476       exit(1);
477       break;
478
479     case 'h':
480       usage();
481       exit(1);
482       break;
483
484     case 'r':
485       keep_em = !keep_em;  /* Just invert */
486       break;
487
488     case 's':
489       snaplen = strtol(optarg, &p, 10);
490       if (p == optarg || *p != '\0') {
491         fprintf(stderr, "editcap: \"%s\" isn't a valid snapshot length\n",
492             optarg);
493         exit(1);
494       }
495       break;
496
497     case 't':
498       set_time_adjustment(optarg);
499       break;
500
501     case 'T':
502       out_frame_type = wtap_short_string_to_encap(optarg);
503       if (out_frame_type < 0) {
504         fprintf(stderr, "editcap: \"%s\" isn't a valid encapsulation type\n\n",
505             optarg);
506         list_encap_types();
507         exit(1);
508       }
509       break;
510
511     case 'v':
512       verbose = !verbose;  /* Just invert */
513       break;
514
515     case 'A':
516     {
517       struct tm starttm;
518
519       memset(&starttm,0,sizeof(struct tm));
520
521       if(!strptime(optarg,"%F %T",&starttm)) {
522         fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
523         exit(1);
524       }
525
526       check_startstop = TRUE;
527       starttm.tm_isdst = -1;
528
529       starttime = mktime(&starttm);
530       printf("=START=> given='%s' stoptime=%lu\n",optarg,(unsigned long)starttime);
531       break;
532     }
533
534     case 'B':
535     {
536       struct tm stoptm;
537
538       memset(&stoptm,0,sizeof(struct tm));
539
540       if(!strptime(optarg,"%F %T",&stoptm)) {
541         fprintf(stderr, "editcap: \"%s\" isn't a valid time format\n\n", optarg);
542         exit(1);
543       }
544       check_startstop = TRUE;
545       stoptm.tm_isdst = -1;
546       stoptime = mktime(&stoptm);
547       printf("=STOP=> given='%s' stoptime=%lu\n",optarg,(unsigned long)stoptime);
548       break;
549     }
550     }
551
552   }
553
554 #ifdef DEBUG
555   printf("Optind = %i, argc = %i\n", optind, argc);
556 #endif
557
558   if ((argc - optind) < 1) {
559
560     usage();
561     exit(1);
562
563   }
564
565   if (check_startstop && !stoptime) {
566     struct tm stoptm;
567     /* XXX: will work until 2035 */
568     memset(&stoptm,0,sizeof(struct tm));
569     stoptm.tm_year = 135;
570     stoptm.tm_mday = 31;
571     stoptm.tm_mon = 11;
572
573     stoptime = mktime(&stoptm);
574     printf("=STOP=NEVER=> stoptime=%lu\n",(unsigned long)stoptime);
575   }
576
577   if (starttime > stoptime) {
578     fprintf(stderr, "editcap: start time is after the stop time\n");
579     exit(1);
580   }
581   printf("==> stoptime=%lu stoptime=%lu\n",(unsigned long)starttime,(unsigned long)stoptime);
582
583   wth = wtap_open_offline(argv[optind], &err, &err_info, FALSE);
584
585   if (!wth) {
586     fprintf(stderr, "editcap: Can't open %s: %s\n", argv[optind],
587         wtap_strerror(err));
588     switch (err) {
589
590     case WTAP_ERR_UNSUPPORTED:
591     case WTAP_ERR_UNSUPPORTED_ENCAP:
592     case WTAP_ERR_BAD_RECORD:
593       fprintf(stderr, "(%s)\n", err_info);
594       g_free(err_info);
595       break;
596     }
597     exit(1);
598
599   }
600
601   if (verbose) {
602
603     fprintf(stderr, "File %s is a %s capture file.\n", argv[optind],
604             wtap_file_type_string(wtap_file_type(wth)));
605
606   }
607
608   /*
609    * Now, process the rest, if any ... we only write if there is an extra
610    * argument or so ...
611    */
612
613   if ((argc - optind) >= 2) {
614
615     if (out_frame_type == -2)
616       out_frame_type = wtap_file_encap(wth);
617
618     if (split_packet_count > 0) {
619       filename = (char *) malloc(strlen(argv[optind+1]) + 20);
620       if (!filename) {
621         exit(5);
622       }
623       sprintf(filename, "%s-%05d", argv[optind+1], 0);
624     } else {
625       filename = argv[optind+1];
626     }
627
628     pdh = wtap_dump_open(filename, out_file_type,
629                          out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
630     if (pdh == NULL) {
631
632       fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
633               wtap_strerror(err));
634       exit(1);
635
636     }
637
638     for (i = optind + 2; i < argc; i++)
639       if (add_selection(argv[i]) == FALSE)
640         break;
641
642     while (wtap_read(wth, &err, &err_info, &data_offset)) {
643
644       if (split_packet_count > 0 && (written_count % split_packet_count == 0)) {
645         if (!wtap_dump_close(pdh, &err)) {
646
647           fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
648                   wtap_strerror(err));
649           exit(1);
650         }
651
652         sprintf(filename, "%s-%05d",argv[optind+1], count / split_packet_count);
653
654         if (verbose) {
655           fprintf(stderr, "Continuing writing in file %s\n", filename);
656         }
657
658         pdh = wtap_dump_open(filename, out_file_type,
659                              out_frame_type, wtap_snapshot_length(wth), FALSE /* compressed */, &err);
660         if (pdh == NULL) {
661
662           fprintf(stderr, "editcap: Can't open or create %s: %s\n", filename,
663                   wtap_strerror(err));
664           exit(1);
665
666         }
667       }
668         
669       check_ts = check_timestamp(wth);
670                 
671       if ( ((check_startstop && check_ts) || (!check_startstop && !check_ts)) && ((!selected(count) && !keep_em) ||
672           (selected(count) && keep_em)) ) {
673
674         if (verbose)
675           printf("Packet: %u\n", count);
676
677         /* We simply write it, perhaps after truncating it; we could do other
678            things, like modify it. */
679
680         phdr = wtap_phdr(wth);
681
682         if (choplen != 0 && phdr->caplen > choplen) {
683           snap_phdr = *phdr;
684           snap_phdr.caplen -= choplen;
685           phdr = &snap_phdr;
686         }
687
688         if (snaplen != 0 && phdr->caplen > snaplen) {
689           snap_phdr = *phdr;
690           snap_phdr.caplen = snaplen;
691           phdr = &snap_phdr;
692         }
693
694         /* assume that if the frame's tv_sec is 0, then
695          * the timestamp isn't supported */
696         if (phdr->ts.secs > 0 && time_adj.tv.tv_sec != 0) {
697           snap_phdr = *phdr;
698           if (time_adj.is_negative)
699             snap_phdr.ts.secs -= time_adj.tv.tv_sec;
700           else
701             snap_phdr.ts.secs += time_adj.tv.tv_sec;
702           phdr = &snap_phdr;
703         }
704
705         /* assume that if the frame's tv_sec is 0, then
706          * the timestamp isn't supported */
707         if (phdr->ts.secs > 0 && time_adj.tv.tv_usec != 0) {
708           snap_phdr = *phdr;
709           if (time_adj.is_negative) { /* subtract */
710             if (snap_phdr.ts.nsecs/1000 < time_adj.tv.tv_usec) { /* borrow */
711               snap_phdr.ts.secs--;
712               snap_phdr.ts.nsecs += ONE_MILLION * 1000;
713             }
714             snap_phdr.ts.nsecs -= time_adj.tv.tv_usec * 1000;
715           } else {                  /* add */
716             if (snap_phdr.ts.nsecs + time_adj.tv.tv_usec * 1000 > ONE_MILLION * 1000) {
717               /* carry */
718               snap_phdr.ts.secs++;
719               snap_phdr.ts.nsecs += (time_adj.tv.tv_usec - ONE_MILLION) * 1000;
720             } else {
721               snap_phdr.ts.nsecs += time_adj.tv.tv_usec * 1000;
722             }
723           }
724           phdr = &snap_phdr;
725         }
726
727         if (dup_detect) {
728           buf = wtap_buf_ptr(wth);
729           if (is_duplicate(buf, phdr->caplen)) {
730             if (verbose)
731               printf("Skipping duplicate: %u\n", count);
732             count++;
733             continue;
734           }
735         }
736
737         if (err_prob > 0.0) {
738           buf = wtap_buf_ptr(wth);
739           for (i = 0; i < (int) phdr->caplen; i++) {
740             if (rand() <= err_prob * RAND_MAX) {
741               err_type = rand() / (RAND_MAX / ERR_WT_TOTAL + 1);
742
743               if (err_type < ERR_WT_BIT) {
744                 buf[i] ^= 1 << (rand() / (RAND_MAX / 8 + 1));
745                 err_type = ERR_WT_TOTAL;
746               } else {
747                 err_type -= ERR_WT_BYTE;
748               }
749
750               if (err_type < ERR_WT_BYTE) {
751                 buf[i] = rand() / (RAND_MAX / 255 + 1);
752                 err_type = ERR_WT_TOTAL;
753               } else {
754                 err_type -= ERR_WT_BYTE;
755               }
756
757               if (err_type < ERR_WT_ALNUM) {
758                 buf[i] = ALNUM_CHARS[rand() / (RAND_MAX / ALNUM_LEN + 1)];
759                 err_type = ERR_WT_TOTAL;
760               } else {
761                 err_type -= ERR_WT_ALNUM;
762               }
763
764               if (err_type < ERR_WT_FMT) {
765                 if ((unsigned int)i < phdr->caplen - 2)
766                   strcpy((char*) &buf[i],  "%s");
767                 err_type = ERR_WT_TOTAL;
768               } else {
769                 err_type -= ERR_WT_FMT;
770               }
771
772               if (err_type < ERR_WT_AA) {
773                 for (j = i; j < (int) phdr->caplen; j++) {
774                   buf[j] = 0xAA;
775                 }
776                 i = phdr->caplen;
777               }
778             }
779           }
780         }
781
782         if (!wtap_dump(pdh, phdr, wtap_pseudoheader(wth), wtap_buf_ptr(wth),
783                        &err)) {
784
785           fprintf(stderr, "editcap: Error writing to %s: %s\n",
786                   filename, wtap_strerror(err));
787           exit(1);
788
789         }
790
791         written_count++;
792
793       }
794
795       count++;
796
797     }
798
799     if (err != 0) {
800       /* Print a message noting that the read failed somewhere along the line. */
801       fprintf(stderr,
802               "editcap: An error occurred while reading \"%s\": %s.\n",
803               argv[optind], wtap_strerror(err));
804       switch (err) {
805
806       case WTAP_ERR_UNSUPPORTED:
807       case WTAP_ERR_UNSUPPORTED_ENCAP:
808       case WTAP_ERR_BAD_RECORD:
809         fprintf(stderr, "(%s)\n", err_info);
810         break;
811       }
812     }
813
814     if (!wtap_dump_close(pdh, &err)) {
815
816       fprintf(stderr, "editcap: Error writing to %s: %s\n", filename,
817               wtap_strerror(err));
818       exit(1);
819
820     }
821   }
822
823   return 0;
824 }
825