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