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