Have the Wiretap open, read, and seek-and-read routines return, in
[obnox/wireshark/wip.git] / mergecap.c
1 /* Combine two dump files, either by appending or by merging by timestamp
2  *
3  * $Id: mergecap.c,v 1.16 2004/01/25 21:55:10 guy Exp $
4  *
5  * Written by Scott Renfro <scott@renfro.org> based on
6  * editcap by Richard Sharpe and Guy Harris
7  *
8  */
9
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <glib.h>
17
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21
22 #ifdef HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25
26 #include <string.h>
27 #include "wtap.h"
28
29 #ifdef NEED_GETOPT_H
30 #include "getopt.h"
31 #endif
32
33 #include "cvsversion.h"
34
35 /*
36  * Global variables
37  */
38 static int verbose = 0;                      /* Not so verbose         */
39
40 /*
41  * Structures to manage our files
42  */
43 typedef struct in_file_t {
44   const char *filename;
45   wtap       *wth;
46   int         err;
47   gchar      *err_info;
48   long        data_offset;
49   gboolean    ok;
50 } in_file_t;
51
52 typedef struct out_file_t {
53   const char  *filename;
54   wtap_dumper *pdh;
55   int          file_type;
56   int          frame_type;
57   unsigned int snaplen;
58   int          count;
59 } out_file_t;
60 static out_file_t out_file;
61
62 /*
63  * Routine to write frame to output file
64  */
65 static void
66 write_frame(guchar *user, const struct wtap_pkthdr *phdr, long offset _U_,
67             union wtap_pseudo_header *pseudo_header, const guchar *buf)
68 {
69   wtap_dumper *pdh = (wtap_dumper*)user;
70   int err;
71   struct wtap_pkthdr snap_phdr;
72
73   if (verbose)
74     printf("Record: %u\n", out_file.count++);
75
76   /* We simply write it, perhaps after truncating it; we could do other
77    * things, like modify it. */
78   if (out_file.snaplen != 0 && phdr->caplen > out_file.snaplen) {
79     snap_phdr = *phdr;
80     snap_phdr.caplen = out_file.snaplen;
81     phdr = &snap_phdr;
82   }
83
84   if (!wtap_dump(pdh, phdr, pseudo_header, buf, &err)) {
85     fprintf(stderr, "mergecap: Error writing to %s: %s\n",
86             out_file.filename, wtap_strerror(err));
87     exit(1);
88   }
89 }
90
91
92 /*
93  * routine to concatenate files
94  */
95 static void
96 append(int count, in_file_t in_files[], out_file_t *out_file)
97 {
98   int i;
99   int err;
100   gchar *err_info;
101
102   for (i = 0; i < count; i++) {
103     if (!wtap_loop(in_files[i].wth, 0, write_frame,
104                    (guchar*)out_file->pdh, &err, &err_info)) {
105       fprintf(stderr, "mergecap: Error reading %s to append to %s: %s\n",
106               in_files[i].filename, out_file->filename, wtap_strerror(err));
107       switch (err) {
108
109       case WTAP_ERR_UNSUPPORTED:
110       case WTAP_ERR_UNSUPPORTED_ENCAP:
111       case WTAP_ERR_BAD_RECORD:
112         fprintf(stderr, "(%s)\n", err_info);
113         break;
114       }
115     }
116   }
117 }
118
119
120 /*
121  * returns TRUE if first argument is earlier than second
122  */
123 static gboolean
124 is_earlier(struct timeval *l, struct timeval *r) {
125   if (l->tv_sec > r->tv_sec) {  /* left is later */
126     return FALSE;
127   } else if (l->tv_sec < r->tv_sec) { /* left is earlier */
128     return TRUE;
129   } else if (l->tv_usec > r->tv_usec) { /* tv_sec equal, l.usec later */
130     return FALSE;
131   }
132   /* either one < two or one == two
133    * either way, return one
134    */
135   return TRUE;
136 }
137
138
139 /*
140  * returns index of earliest timestamp in set of input files
141  * or -1 if no valid files remain
142  */
143 static int
144 earliest(int count, in_file_t in_files[]) {
145   int i;
146   int ei = -1;
147   struct timeval tv = {LONG_MAX, LONG_MAX};
148
149   for (i = 0; i < count; i++) {
150     struct wtap_pkthdr *phdr = wtap_phdr(in_files[i].wth);
151
152     if (in_files[i].ok && is_earlier(&(phdr->ts), &tv)) {
153       tv = phdr->ts;
154       ei = i;
155     }
156   }
157   return ei;
158 }
159
160 /*
161  * actually merge the files
162  */
163 static void
164 merge(int count, in_file_t in_files[], out_file_t *out_file)
165 {
166   int i;
167
168   /* prime the pump (read in first frame from each file) */
169   for (i = 0; i < count; i++) {
170     in_files[i].ok = wtap_read(in_files[i].wth, &(in_files[i].err),
171                                &(in_files[i].err_info),
172                                &(in_files[i].data_offset));
173   }
174
175   /* now keep writing the earliest frame until we're out of frames */
176   while ( -1 != (i = earliest(count, in_files))) {
177
178     /* write out earliest frame, and fetch another from its
179      * input file
180      */
181     write_frame((guchar*)out_file->pdh,
182                 wtap_phdr(in_files[i].wth),
183                 in_files[i].data_offset,
184                 wtap_pseudoheader(in_files[i].wth),
185                 wtap_buf_ptr(in_files[i].wth));
186     in_files[i].ok = wtap_read(in_files[i].wth, &(in_files[i].err),
187                                &(in_files[i].err_info),
188                                &(in_files[i].data_offset));
189   }
190 }
191
192
193 /*
194  * Select an output frame type based on the input files
195  * From Guy: If all files have the same frame type, then use that.
196  *           Otherwise select WTAP_ENCAP_PER_PACKET.  If the selected
197  *           output file type doesn't support per packet frame types,
198  *           then the wtap_dump_open call will fail with a reasonable
199  *           error condition.
200  */
201 static int
202 select_frame_type(int count, in_file_t files[])
203 {
204   int i;
205   int selected_frame_type;
206
207   selected_frame_type = wtap_file_encap(files[0].wth);
208
209   for (i = 1; i < count; i++) {
210     int this_frame_type = wtap_file_encap(files[i].wth);
211     if (selected_frame_type != this_frame_type) {
212       selected_frame_type = WTAP_ENCAP_PER_PACKET;
213       if (verbose) {
214         fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
215         fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
216         fprintf(stderr, "          %s had type %s (%s)\n",
217                 files[0].filename,
218                 wtap_encap_string(selected_frame_type),
219                 wtap_encap_short_string(selected_frame_type));
220         fprintf(stderr, "          %s had type %s (%s)\n",
221                 files[i].filename,
222                 wtap_encap_string(this_frame_type),
223                 wtap_encap_short_string(this_frame_type));
224       }
225       break;
226     }
227   }
228
229   if (verbose) {
230       fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
231               wtap_encap_string(selected_frame_type),
232               wtap_encap_short_string(selected_frame_type));
233   }
234
235   return selected_frame_type;
236 }
237
238
239 /*
240  * Close the output file
241  */
242 static void
243 close_outfile(out_file_t *out_file)
244 {
245   int err;
246   if (!wtap_dump_close(out_file->pdh, &err)) {
247     fprintf(stderr, "mergecap: Error closing file %s: %s\n",
248             out_file->filename, wtap_strerror(err));
249     exit(1);
250   }
251 }
252
253
254 /*
255  * Open the output file
256  *
257  * Return FALSE if file cannot be opened (so caller can clean up)
258  */
259 static gboolean
260 open_outfile(out_file_t *out_file, int snapshot_len)
261 {
262   int err;
263   if (!out_file) {
264     fprintf(stderr, "mergecap: internal error (null out_file)\n");
265     exit(1);
266   }
267
268   out_file->pdh = wtap_dump_open(out_file->filename, out_file->file_type,
269                                  out_file->frame_type, snapshot_len, &err);
270   if (!out_file->pdh) {
271     fprintf(stderr, "mergecap: Can't open/create %s:\n", out_file->filename);
272     fprintf(stderr, "          %s\n", wtap_strerror(err));
273     return FALSE;
274   }
275   return TRUE;
276 }
277
278
279 /*
280  * Scan through input files and find maximum snapshot length
281  */
282 static int
283 max_snapshot_length(int count, in_file_t in_files[])
284 {
285   int i;
286   int max_snapshot = 0;
287   int snapshot_length;
288
289   for (i = 0; i < count; i++) {
290     snapshot_length = wtap_snapshot_length(in_files[i].wth);
291     if (snapshot_length == 0) {
292       /* Snapshot length of input file not known. */
293       snapshot_length = WTAP_MAX_PACKET_SIZE;
294     }
295     if (snapshot_length > max_snapshot)
296       max_snapshot = snapshot_length;
297   }
298   return max_snapshot;
299 }
300
301
302 /*
303  * Scan through and close each input file
304  */
305 static void
306 close_in_files(int count, in_file_t in_files[])
307 {
308   int i;
309   for (i = 0; i < count; i++) {
310     wtap_close(in_files[i].wth);
311   }
312 }
313
314
315 /*
316  * Scan through the arguments and open the input files
317  */
318 static int
319 open_in_files(int argc, char *argv[], in_file_t *in_files[])
320 {
321   int i;
322   int count = 0;
323   int err;
324   gchar *err_info;
325   in_file_t *files;
326   int files_size = argc * sizeof(in_file_t);
327
328
329   files = malloc(files_size);
330   if (!files) {
331     fprintf(stderr, "mergecap: error allocating %d bytes of memory\n",
332             files_size);
333     exit(1);
334   }
335   *in_files = files;
336
337   for (i = 0; i < argc; i++) {
338     files[count].filename    = argv[i];
339     files[count].wth         = wtap_open_offline(argv[i], &err, &err_info, FALSE);
340     files[count].err         = 0;
341     files[count].data_offset = 0;
342     files[count].ok          = TRUE;
343     if (!files[count].wth) {
344       fprintf(stderr, "mergecap: skipping %s: %s\n", argv[i],
345               wtap_strerror(err));
346       switch (err) {
347
348       case WTAP_ERR_UNSUPPORTED:
349       case WTAP_ERR_UNSUPPORTED_ENCAP:
350       case WTAP_ERR_BAD_RECORD:
351         fprintf(stderr, "(%s)\n", err_info);
352         break;
353       }
354     } else {
355       if (verbose) {
356         fprintf(stderr, "mergecap: %s is type %s.\n", argv[i],
357                 wtap_file_type_string(wtap_file_type(files[count].wth)));
358       }
359       count++;
360     }
361   }
362   if (verbose)
363     fprintf(stderr, "mergecap: opened %d of %d input files\n", count,
364     argc);
365
366   return count;
367 }
368
369
370 /*
371  * Show the usage
372  */
373 static void
374 usage(void)
375 {
376   int i;
377   const char *string;
378
379   printf("Usage: mergecap [-hva] [-s <snaplen>] [-T <encap type>]\n");
380   printf("          [-F <capture type>] -w <outfile> <infile> [...]\n\n");
381   printf("  where\t-h produces this help listing.\n");
382   printf("       \t-v verbose operation, default is silent\n");
383   printf("       \t-a files should be concatenated, not merged\n");
384   printf("       \t     Default merges based on frame timestamps\n");
385   printf("       \t-s <snaplen>: truncate packets to <snaplen> bytes of data\n");
386   printf("       \t-w <outfile>: sets output filename to <outfile>\n");
387   printf("       \t-T <encap type> encapsulation type to use:\n");
388   for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
389       string = wtap_encap_short_string(i);
390       if (string != NULL)
391         printf("       \t     %s - %s\n",
392           string, wtap_encap_string(i));
393   }
394   printf("       \t     default is the same as the first input file\n");
395   printf("       \t-F <capture type> capture file type to write:\n");
396   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
397     if (wtap_dump_can_open(i))
398       printf("       \t     %s - %s\n",
399         wtap_file_type_short_string(i), wtap_file_type_string(i));
400   }
401   printf("       \t     default is libpcap\n");
402 }
403
404
405
406 int
407 main(int argc, char *argv[])
408 {
409   extern char *optarg;
410   extern int   optind;
411   int          opt;
412   char        *p;
413   gboolean     do_append     = FALSE;
414   int          in_file_count = 0;
415   in_file_t   *in_files      = NULL;
416
417   /* initialize out_file */
418   out_file.filename   = NULL;
419   out_file.pdh        = NULL;              /* wiretap dumpfile */
420   out_file.file_type  = WTAP_FILE_PCAP;    /* default to "libpcap" */
421   out_file.frame_type = -2;                /* leave type alone */
422   out_file.snaplen    = 0;                 /* no limit */
423   out_file.count      = 1;                 /* frames output */
424
425   /* Process the options first */
426   while ((opt = getopt(argc, argv, "hvas:T:F:w:")) != -1) {
427
428     switch (opt) {
429     case 'w':
430       out_file.filename = optarg;
431       break;
432
433     case 'a':
434       do_append = !do_append;
435       break;
436
437     case 'T':
438       out_file.frame_type = wtap_short_string_to_encap(optarg);
439       if (out_file.frame_type < 0) {
440         fprintf(stderr, "mergecap: \"%s\" is not a valid encapsulation type\n",
441             optarg);
442         exit(1);
443       }
444       break;
445
446     case 'F':
447       out_file.file_type = wtap_short_string_to_file_type(optarg);
448       if (out_file.file_type < 0) {
449         fprintf(stderr, "mergecap: \"%s\" is not a valid capture file type\n",
450             optarg);
451         exit(1);
452       }
453       break;
454
455     case 'v':
456       verbose = !verbose;  /* Just invert */
457       break;
458
459     case 's':
460       out_file.snaplen = strtol(optarg, &p, 10);
461       if (p == optarg || *p != '\0') {
462         fprintf(stderr, "mergecap: \"%s\" is not a valid snapshot length\n",
463             optarg);
464         exit(1);
465       }
466       break;
467
468     case 'h':
469       printf("mergecap version %s"
470 #ifdef CVSVERSION
471           " (cvs " CVSVERSION ")"
472 #endif
473           "\n", VERSION);
474       usage();
475       exit(0);
476       break;
477
478     case '?':              /* Bad options if GNU getopt */
479       usage();
480       exit(1);
481       break;
482
483     }
484
485   }
486
487   /* check for proper args; at a minimum, must have an output
488    * filename and one input file
489    */
490   in_file_count = argc - optind;
491   if (!out_file.filename) {
492     fprintf(stderr, "mergecap: an output filename must be set with -w\n");
493     fprintf(stderr, "          run with -h for help\n");
494     exit(1);
495   }
496
497   /* open the input files */
498   in_file_count = open_in_files(in_file_count, &argv[optind], &in_files);
499   if (in_file_count < 1) {
500     fprintf(stderr, "mergecap: No valid input files\n");
501     exit(1);
502   }
503
504   /* set the outfile frame type */
505   if (out_file.frame_type == -2)
506     out_file.frame_type = select_frame_type(in_file_count, in_files);
507
508   /* open the outfile */
509   if (!open_outfile(&out_file, max_snapshot_length(in_file_count, in_files))) {
510     close_in_files(in_file_count, in_files);
511     exit(1);
512   }
513
514   /* do the merge (or append) */
515   if (do_append)
516     append(in_file_count, in_files, &out_file);
517   else
518     merge(in_file_count, in_files, &out_file);
519
520   close_in_files(in_file_count, in_files);
521   close_outfile(&out_file);
522
523   free(in_files);
524
525   return 0;
526 }