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