- Write ISB(s) at start and end of capture.
[obnox/wireshark/wip.git] / mergecap.c
1 /* Combine two dump files, either by appending or by merging by timestamp
2  *
3  * $Id$
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  *
23  * Mergecap written by Scott Renfro <scott@renfro.org> based on
24  * editcap by Richard Sharpe and Guy Harris
25  *
26  */
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <glib.h>
36
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44
45 #include <string.h>
46 #include "wtap.h"
47
48 #ifndef HAVE_GETOPT
49 #include "wsutil/wsgetopt.h"
50 #endif
51
52 #include "svnversion.h"
53 #include "merge.h"
54 #include "wsutil/file_util.h"
55
56 #ifdef HAVE_FCNTL_H
57 #include <fcntl.h>
58 #endif
59
60 #ifdef _WIN32
61 #include <wsutil/unicode-utils.h>
62 #endif /* _WIN32 */
63
64 static int
65 get_natural_int(const char *string, const char *name)
66 {
67   int number;
68   char *p;
69
70   number = (int) strtol(string, &p, 10);
71   if (p == string || *p != '\0') {
72     fprintf(stderr, "mergecap: The specified %s \"%s\" isn't a decimal number\n",
73             name, string);
74     exit(1);
75   }
76   if (number < 0) {
77     fprintf(stderr, "mergecap: The specified %s is a negative number\n",
78             name);
79     exit(1);
80   }
81   if (number > INT_MAX) {
82     fprintf(stderr, "mergecap: The specified %s is too large (greater than %d)\n",
83             name, INT_MAX);
84     exit(1);
85   }
86   return number;
87 }
88
89 static int
90 get_positive_int(const char *string, const char *name)
91 {
92   int number;
93
94   number = get_natural_int(string, name);
95
96   if (number == 0) {
97     fprintf(stderr, "mergecap: The specified %s is zero\n",
98             name);
99     exit(1);
100   }
101
102   return number;
103 }
104
105 /*
106  * Show the usage
107  */
108 static void
109 usage(void)
110 {
111
112   fprintf(stderr, "Mergecap %s"
113 #ifdef SVNVERSION
114           " (" SVNVERSION " from " SVNPATH ")"
115 #endif
116           "\n", VERSION);
117   fprintf(stderr, "Merge two or more capture files into one.\n");
118   fprintf(stderr, "See http://www.wireshark.org for more information.\n");
119   fprintf(stderr, "\n");
120   fprintf(stderr, "Usage: mergecap [options] -w <outfile>|- <infile> [<infile> ...]\n");
121   fprintf(stderr, "\n");
122   fprintf(stderr, "Output:\n");
123   fprintf(stderr, "  -a                concatenate rather than merge files.\n");
124   fprintf(stderr, "                    default is to merge based on frame timestamps.\n");
125   fprintf(stderr, "  -s <snaplen>      truncate packets to <snaplen> bytes of data.\n");
126   fprintf(stderr, "  -w <outfile>|-    set the output filename to <outfile> or '-' for stdout.\n");
127   fprintf(stderr, "  -F <capture type> set the output file type; default is pcapng.\n");
128   fprintf(stderr, "                    an empty \"-F\" option will list the file types.\n");
129   fprintf(stderr, "  -T <encap type>   set the output file encapsulation type;\n");
130   fprintf(stderr, "                    default is the same as the first input file.\n");
131   fprintf(stderr, "                    an empty \"-T\" option will list the encapsulation types.\n");
132   fprintf(stderr, "\n");
133   fprintf(stderr, "Miscellaneous:\n");
134   fprintf(stderr, "  -h                display this help and exit.\n");
135   fprintf(stderr, "  -v                verbose output.\n");
136 }
137
138 struct string_elem {
139     const char *sstr;   /* The short string */
140     const char *lstr;   /* The long string */
141 };
142
143 static gint
144 string_compare(gconstpointer a, gconstpointer b)
145 {
146     return strcmp(((const struct string_elem *)a)->sstr,
147         ((const struct string_elem *)b)->sstr);
148 }
149
150 static void
151 string_elem_print(gpointer data, gpointer not_used _U_)
152 {
153     fprintf(stderr, "    %s - %s\n",
154         ((struct string_elem *)data)->sstr,
155         ((struct string_elem *)data)->lstr);
156 }
157
158 static void
159 list_capture_types(void) {
160   int i;
161   struct string_elem *captypes;
162   GSList *list = NULL;
163
164   captypes = g_malloc(sizeof(struct string_elem) * WTAP_NUM_FILE_TYPES);
165
166   fprintf(stderr, "mergecap: The available capture file types for the \"-F\" flag are:\n");
167   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
168     if (wtap_dump_can_open(i)) {
169       captypes[i].sstr = wtap_file_type_short_string(i);
170       captypes[i].lstr = wtap_file_type_string(i);
171       list = g_slist_insert_sorted(list, &captypes[i], string_compare);
172     }
173   }
174   g_slist_foreach(list, string_elem_print, NULL);
175   g_slist_free(list);
176   g_free(captypes);
177 }
178
179 static void
180 list_encap_types(void) {
181     int i;
182     struct string_elem *encaps;
183     GSList *list = NULL;
184
185     encaps = g_malloc(sizeof(struct string_elem) * WTAP_NUM_ENCAP_TYPES);
186     fprintf(stderr, "mergecap: The available encapsulation types for the \"-T\" flag are:\n");
187     for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
188         encaps[i].sstr = wtap_encap_short_string(i);
189         if (encaps[i].sstr != NULL) {
190             encaps[i].lstr = wtap_encap_string(i);
191             list = g_slist_insert_sorted(list, &encaps[i], string_compare);
192         }
193     }
194     g_slist_foreach(list, string_elem_print, NULL);
195     g_slist_free(list);
196     g_free(encaps);
197 }
198
199 int
200 main(int argc, char *argv[])
201 {
202   int          opt;
203
204   gboolean     do_append     = FALSE;
205   gboolean     verbose       = FALSE;
206   int          in_file_count = 0;
207   guint        snaplen = 0;
208 #ifdef PCAP_NG_DEFAULT
209   int          file_type = WTAP_FILE_PCAPNG;    /* default to pcap format */
210 #else
211   int          file_type = WTAP_FILE_PCAP;      /* default to pcapng format */
212 #endif
213   int          frame_type = -2;
214   int          out_fd;
215   merge_in_file_t   *in_files      = NULL, *in_file;
216   int          i;
217   struct wtap_pkthdr *phdr, snap_phdr;
218   wtap_dumper *pdh;
219   int          open_err, read_err=0, write_err, close_err;
220   gchar       *err_info;
221   int          err_fileno;
222   char        *out_filename = NULL;
223   gboolean     got_read_error = FALSE, got_write_error = FALSE;
224   int          count;
225
226 #ifdef _WIN32
227   arg_list_utf_16to8(argc, argv);
228 #endif /* _WIN32 */
229
230   /* Process the options first */
231   while ((opt = getopt(argc, argv, "hvas:T:F:w:")) != -1) {
232
233     switch (opt) {
234     case 'w':
235       out_filename = optarg;
236       break;
237
238     case 'a':
239       do_append = !do_append;
240       break;
241
242     case 'T':
243       frame_type = wtap_short_string_to_encap(optarg);
244       if (frame_type < 0) {
245         fprintf(stderr, "mergecap: \"%s\" isn't a valid encapsulation type\n",
246             optarg);
247         list_encap_types();
248         exit(1);
249       }
250       break;
251
252     case 'F':
253       file_type = wtap_short_string_to_file_type(optarg);
254       if (file_type < 0) {
255         fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
256             optarg);
257         list_capture_types();
258         exit(1);
259       }
260       break;
261
262     case 'v':
263       verbose = TRUE;
264       break;
265
266     case 's':
267       snaplen = get_positive_int(optarg, "snapshot length");
268       break;
269
270     case 'h':
271       usage();
272       exit(0);
273       break;
274
275     case '?':              /* Bad options if GNU getopt */
276       switch(optopt) {
277       case'F':
278         list_capture_types();
279         break;
280       case'T':
281         list_encap_types();
282         break;
283       default:
284         usage();
285       }
286       exit(1);
287       break;
288
289     }
290
291   }
292
293   /* check for proper args; at a minimum, must have an output
294    * filename and one input file
295    */
296   in_file_count = argc - optind;
297   if (!out_filename) {
298     fprintf(stderr, "mergecap: an output filename must be set with -w\n");
299     fprintf(stderr, "          run with -h for help\n");
300     return 1;
301   }
302   if (in_file_count < 1) {
303     fprintf(stderr, "mergecap: No input files were specified\n");
304     return 1;
305   }
306
307   /* open the input files */
308   if (!merge_open_in_files(in_file_count, &argv[optind], &in_files,
309                            &open_err, &err_info, &err_fileno)) {
310     fprintf(stderr, "mergecap: Can't open %s: %s\n", argv[optind + err_fileno],
311         wtap_strerror(open_err));
312     switch (open_err) {
313
314     case WTAP_ERR_UNSUPPORTED:
315     case WTAP_ERR_UNSUPPORTED_ENCAP:
316     case WTAP_ERR_BAD_FILE:
317       fprintf(stderr, "(%s)\n", err_info);
318       g_free(err_info);
319       break;
320     }
321     return 2;
322   }
323
324   if (verbose) {
325     for (i = 0; i < in_file_count; i++)
326       fprintf(stderr, "mergecap: %s is type %s.\n", argv[optind + i],
327               wtap_file_type_string(wtap_file_type(in_files[i].wth)));
328   }
329
330   if (snaplen == 0) {
331     /*
332      * Snapshot length not specified - default to the maximum of the
333      * snapshot lengths of the input files.
334      */
335     snaplen = merge_max_snapshot_length(in_file_count, in_files);
336   }
337
338   /* set the outfile frame type */
339   if (frame_type == -2) {
340     /*
341      * Default to the appropriate frame type for the input files.
342      */
343     frame_type = merge_select_frame_type(in_file_count, in_files);
344     if (verbose) {
345       if (frame_type == WTAP_ENCAP_PER_PACKET) {
346         /*
347          * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
348          */
349         int first_frame_type, this_frame_type;
350
351         first_frame_type = wtap_file_encap(in_files[0].wth);
352         for (i = 1; i < in_file_count; i++) {
353           this_frame_type = wtap_file_encap(in_files[i].wth);
354           if (first_frame_type != this_frame_type) {
355             fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
356             fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
357             fprintf(stderr, "          %s had type %s (%s)\n",
358                     in_files[0].filename,
359                     wtap_encap_string(first_frame_type),
360                     wtap_encap_short_string(first_frame_type));
361             fprintf(stderr, "          %s had type %s (%s)\n",
362                     in_files[i].filename,
363                     wtap_encap_string(this_frame_type),
364                     wtap_encap_short_string(this_frame_type));
365             break;
366           }
367         }
368       }
369       fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
370               wtap_encap_string(frame_type),
371               wtap_encap_short_string(frame_type));
372     }
373   }
374
375   /* open the outfile */
376   if (strncmp(out_filename, "-", 2) == 0) {
377     /* use stdout as the outfile */
378     out_fd = 1 /*stdout*/;
379   } else {
380     /* open the outfile */
381     out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
382     if (out_fd == -1) {
383       fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
384               out_filename, g_strerror(errno));
385       exit(1);
386     }
387   }
388
389   /* prepare the outfile */
390   pdh = wtap_dump_fdopen(out_fd, file_type, frame_type, snaplen, FALSE /* compressed */, &open_err);
391   if (pdh == NULL) {
392     merge_close_in_files(in_file_count, in_files);
393     g_free(in_files);
394     fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
395             wtap_strerror(open_err));
396     exit(1);
397   }
398
399   /* do the merge (or append) */
400   count = 1;
401   for (;;) {
402     if (do_append)
403       in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
404                                          &err_info);
405     else
406       in_file = merge_read_packet(in_file_count, in_files, &read_err,
407                                   &err_info);
408     if (in_file == NULL) {
409       /* EOF */
410       break;
411     }
412
413     if (read_err != 0) {
414       /* I/O error reading from in_file */
415       got_read_error = TRUE;
416       break;
417     }
418
419     if (verbose)
420       fprintf(stderr, "Record: %u\n", count++);
421
422     /* We simply write it, perhaps after truncating it; we could do other
423      * things, like modify it. */
424     phdr = wtap_phdr(in_file->wth);
425     if (snaplen != 0 && phdr->caplen > snaplen) {
426       snap_phdr = *phdr;
427       snap_phdr.caplen = snaplen;
428       phdr = &snap_phdr;
429     }
430
431     if (!wtap_dump(pdh, phdr, wtap_pseudoheader(in_file->wth),
432          wtap_buf_ptr(in_file->wth), &write_err)) {
433       got_write_error = TRUE;
434       break;
435     }
436   }
437
438   merge_close_in_files(in_file_count, in_files);
439   if (!got_read_error && !got_write_error) {
440     if (!wtap_dump_close(pdh, &write_err))
441       got_write_error = TRUE;
442   } else
443     wtap_dump_close(pdh, &close_err);
444
445   if (got_read_error) {
446     /*
447      * Find the file on which we got the error, and report the error.
448      */
449     for (i = 0; i < in_file_count; i++) {
450       if (in_files[i].state == GOT_ERROR) {
451         fprintf(stderr, "mergecap: Error reading %s: %s\n",
452                 in_files[i].filename, wtap_strerror(read_err));
453         switch (read_err) {
454
455         case WTAP_ERR_UNSUPPORTED:
456         case WTAP_ERR_UNSUPPORTED_ENCAP:
457         case WTAP_ERR_BAD_FILE:
458           fprintf(stderr, "(%s)\n", err_info);
459           g_free(err_info);
460           break;
461         }
462       }
463     }
464   }
465
466   if (got_write_error) {
467     switch (write_err) {
468
469     case WTAP_ERR_UNSUPPORTED_ENCAP:
470       /*
471        * This is a problem with the particular frame we're writing;
472        * note that, and give the frame number.
473        */
474       fprintf(stderr, "mergecap: Frame %u of \"%s\" has a network type that can't be saved in a file with that format\n.",
475               in_file->packet_num, in_file->filename);
476       break;
477
478     default:
479       fprintf(stderr, "mergecap: Error writing to outfile: %s\n",
480               wtap_strerror(write_err));
481       break;
482     }
483   }
484
485   g_free(in_files);
486
487   return (!got_read_error && !got_write_error) ? 0 : 2;
488 }