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