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