0eb9bebca2eba1b3395567d23fc0bb159e3be108
[metze/wireshark/wip.git] / mergecap.c
1 /* Combine dump files, either by appending or by merging by timestamp
2  *
3  * Wireshark - Network traffic analyzer
4  * By Gerald Combs <gerald@wireshark.org>
5  * Copyright 1998 Gerald Combs
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Mergecap written by Scott Renfro <scott@renfro.org> based on
22  * editcap by Richard Sharpe and Guy Harris
23  *
24  */
25
26 #include <config.h>
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <errno.h>
31 #include <glib.h>
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 #ifdef HAVE_GETOPT_H
38 #include <getopt.h>
39 #endif
40
41 #ifdef HAVE_LIBZ
42 #include <zlib.h>      /* to get the libz version number */
43 #endif
44
45 #include <string.h>
46 #include "wtap.h"
47
48 #ifndef HAVE_GETOPT_LONG
49 #include <wsutil/wsgetopt.h>
50 #endif
51
52 #include <wsutil/clopts_common.h>
53 #include <wsutil/cmdarg_err.h>
54 #include <wsutil/crash_info.h>
55 #include <wsutil/file_util.h>
56 #include <wsutil/strnatcmp.h>
57 #include <wsutil/ws_diag_control.h>
58 #include <wsutil/ws_version_info.h>
59
60 #include <wiretap/merge.h>
61
62 #ifdef HAVE_FCNTL_H
63 #include <fcntl.h>
64 #endif
65
66 #ifdef _WIN32
67 #include <wsutil/unicode-utils.h>
68 #endif /* _WIN32 */
69
70 /*
71  * Show the usage
72  */
73 static void
74 print_usage(FILE *output)
75 {
76   fprintf(output, "\n");
77   fprintf(output, "Usage: mergecap [options] -w <outfile>|- <infile> [<infile> ...]\n");
78   fprintf(output, "\n");
79   fprintf(output, "Output:\n");
80   fprintf(output, "  -a                concatenate rather than merge files.\n");
81   fprintf(output, "                    default is to merge based on frame timestamps.\n");
82   fprintf(output, "  -s <snaplen>      truncate packets to <snaplen> bytes of data.\n");
83   fprintf(output, "  -w <outfile>|-    set the output filename to <outfile> or '-' for stdout.\n");
84   fprintf(output, "  -F <capture type> set the output file type; default is pcapng.\n");
85   fprintf(output, "                    an empty \"-F\" option will list the file types.\n");
86   fprintf(output, "  -T <encap type>   set the output file encapsulation type;\n");
87   fprintf(output, "                    default is the same as the first input file.\n");
88   fprintf(output, "                    an empty \"-T\" option will list the encapsulation types.\n");
89   fprintf(output, "\n");
90   fprintf(output, "Miscellaneous:\n");
91   fprintf(output, "  -h                display this help and exit.\n");
92   fprintf(output, "  -v                verbose output.\n");
93 }
94
95 /*
96  * Report an error in command-line arguments.
97  */
98 static void
99 mergecap_cmdarg_err(const char *fmt, va_list ap)
100 {
101   fprintf(stderr, "mergecap: ");
102   vfprintf(stderr, fmt, ap);
103   fprintf(stderr, "\n");
104 }
105
106 /*
107  * Report additional information for an error in command-line arguments.
108  */
109 static void
110 mergecap_cmdarg_err_cont(const char *fmt, va_list ap)
111 {
112   vfprintf(stderr, fmt, ap);
113   fprintf(stderr, "\n");
114 }
115
116 struct string_elem {
117   const char *sstr;     /* The short string */
118   const char *lstr;     /* The long string */
119 };
120
121 static gint
122 string_compare(gconstpointer a, gconstpointer b)
123 {
124   return strcmp(((const struct string_elem *)a)->sstr,
125                 ((const struct string_elem *)b)->sstr);
126 }
127
128 static gint
129 string_nat_compare(gconstpointer a, gconstpointer b)
130 {
131   return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
132                             ((const struct string_elem *)b)->sstr);
133 }
134
135 static void
136 string_elem_print(gpointer data, gpointer not_used _U_)
137 {
138   fprintf(stderr, "    %s - %s\n", ((struct string_elem *)data)->sstr,
139           ((struct string_elem *)data)->lstr);
140 }
141
142 static void
143 list_capture_types(void) {
144   int i;
145   struct string_elem *captypes;
146   GSList *list = NULL;
147
148   captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES_SUBTYPES);
149
150   fprintf(stderr, "mergecap: The available capture file types for the \"-F\" flag are:\n");
151   for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
152     if (wtap_dump_can_open(i)) {
153       captypes[i].sstr = wtap_file_type_subtype_short_string(i);
154       captypes[i].lstr = wtap_file_type_subtype_string(i);
155       list = g_slist_insert_sorted(list, &captypes[i], string_compare);
156     }
157   }
158   g_slist_foreach(list, string_elem_print, NULL);
159   g_slist_free(list);
160   g_free(captypes);
161 }
162
163 static void
164 list_encap_types(void) {
165   int i;
166   struct string_elem *encaps;
167   GSList *list = NULL;
168
169   encaps = g_new(struct string_elem,WTAP_NUM_ENCAP_TYPES);
170   fprintf(stderr, "mergecap: The available encapsulation types for the \"-T\" flag are:\n");
171   for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
172     encaps[i].sstr = wtap_encap_short_string(i);
173     if (encaps[i].sstr != NULL) {
174       encaps[i].lstr = wtap_encap_string(i);
175       list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
176     }
177   }
178   g_slist_foreach(list, string_elem_print, NULL);
179   g_slist_free(list);
180   g_free(encaps);
181 }
182
183 static void
184 get_mergecap_compiled_info(GString *str)
185 {
186   /* LIBZ */
187   g_string_append(str, ", ");
188 #ifdef HAVE_LIBZ
189   g_string_append(str, "with libz ");
190 #ifdef ZLIB_VERSION
191   g_string_append(str, ZLIB_VERSION);
192 #else /* ZLIB_VERSION */
193   g_string_append(str, "(version unknown)");
194 #endif /* ZLIB_VERSION */
195 #else /* HAVE_LIBZ */
196   g_string_append(str, "without libz");
197 #endif /* HAVE_LIBZ */
198 }
199
200 static void
201 get_mergecap_runtime_info(GString *str)
202 {
203   /* zlib */
204 #if defined(HAVE_LIBZ) && !defined(_WIN32)
205   g_string_append_printf(str, ", with libz %s", zlibVersion());
206 #endif
207 }
208
209 int
210 main(int argc, char *argv[])
211 {
212   GString            *comp_info_str;
213   GString            *runtime_info_str;
214   int                 opt;
215 DIAG_OFF(cast-qual)
216   static const struct option long_options[] = {
217       {(char *)"help", no_argument, NULL, 'h'},
218       {(char *)"version", no_argument, NULL, 'V'},
219       {0, 0, 0, 0 }
220   };
221 DIAG_ON(cast-qual)
222   gboolean            do_append          = FALSE;
223   gboolean            verbose            = FALSE;
224   int                 in_file_count      = 0;
225   guint               snaplen            = 0;
226 #ifdef PCAP_NG_DEFAULT
227   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcap format */
228 #else
229   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcapng format */
230 #endif
231   int                 frame_type         = -2;
232   int                 out_fd;
233   merge_in_file_t    *in_files           = NULL, *in_file;
234   int                 i;
235   struct wtap_pkthdr *phdr, snap_phdr;
236   wtap_dumper        *pdh;
237   int                 open_err, read_err = 0, write_err, close_err;
238   gchar              *err_info, *write_err_info = NULL;
239   int                 err_fileno;
240   char               *out_filename       = NULL;
241   gboolean            got_read_error     = FALSE, got_write_error = FALSE;
242   int                 count;
243
244   cmdarg_err_init(mergecap_cmdarg_err, mergecap_cmdarg_err_cont);
245
246 #ifdef _WIN32
247   arg_list_utf_16to8(argc, argv);
248   create_app_running_mutex();
249 #endif /* _WIN32 */
250
251   /* Get the compile-time version information string */
252   comp_info_str = get_compiled_version_info(NULL, get_mergecap_compiled_info);
253
254   /* Get the run-time version information string */
255   runtime_info_str = get_runtime_version_info(get_mergecap_runtime_info);
256
257   /* Add it to the information to be reported on a crash. */
258   ws_add_crash_info("Mergecap (Wireshark) %s\n"
259        "\n"
260        "%s"
261        "\n"
262        "%s",
263     get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
264
265   /* Process the options first */
266   while ((opt = getopt_long(argc, argv, "aF:hs:T:vVw:", long_options, NULL)) != -1) {
267
268     switch (opt) {
269     case 'a':
270       do_append = !do_append;
271       break;
272
273     case 'F':
274       file_type = wtap_short_string_to_file_type_subtype(optarg);
275       if (file_type < 0) {
276         fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
277                 optarg);
278         list_capture_types();
279         exit(1);
280       }
281       break;
282
283     case 'h':
284       printf("Mergecap (Wireshark) %s\n"
285              "Merge two or more capture files into one.\n"
286              "See http://www.wireshark.org for more information.\n",
287              get_ws_vcs_version_info());
288       print_usage(stdout);
289       exit(0);
290       break;
291
292     case 's':
293       snaplen = get_positive_int(optarg, "snapshot length");
294       break;
295
296     case 'T':
297       frame_type = wtap_short_string_to_encap(optarg);
298       if (frame_type < 0) {
299         fprintf(stderr, "mergecap: \"%s\" isn't a valid encapsulation type\n",
300                 optarg);
301         list_encap_types();
302         exit(1);
303       }
304       break;
305
306     case 'v':
307       verbose = TRUE;
308       break;
309
310     case 'V':
311       show_version("Mergecap (Wireshark)", comp_info_str, runtime_info_str);
312       g_string_free(comp_info_str, TRUE);
313       g_string_free(runtime_info_str, TRUE);
314       exit(0);
315       break;
316
317     case 'w':
318       out_filename = optarg;
319       break;
320
321     case '?':              /* Bad options if GNU getopt */
322       switch(optopt) {
323       case'F':
324         list_capture_types();
325         break;
326       case'T':
327         list_encap_types();
328         break;
329       default:
330         print_usage(stderr);
331       }
332       exit(1);
333       break;
334     }
335   }
336
337   /* check for proper args; at a minimum, must have an output
338    * filename and one input file
339    */
340   in_file_count = argc - optind;
341   if (!out_filename) {
342     fprintf(stderr, "mergecap: an output filename must be set with -w\n");
343     fprintf(stderr, "          run with -h for help\n");
344     return 1;
345   }
346   if (in_file_count < 1) {
347     fprintf(stderr, "mergecap: No input files were specified\n");
348     return 1;
349   }
350
351   /* open the input files */
352   if (!merge_open_in_files(in_file_count, &argv[optind], &in_files,
353                            &open_err, &err_info, &err_fileno)) {
354     fprintf(stderr, "mergecap: Can't open %s: %s\n", argv[optind + err_fileno],
355             wtap_strerror(open_err));
356     if (err_info != NULL) {
357       fprintf(stderr, "(%s)\n", err_info);
358       g_free(err_info);
359     }
360     return 2;
361   }
362
363   if (verbose) {
364     for (i = 0; i < in_file_count; i++)
365       fprintf(stderr, "mergecap: %s is type %s.\n", argv[optind + i],
366               wtap_file_type_subtype_string(wtap_file_type_subtype(in_files[i].wth)));
367   }
368
369   if (snaplen == 0) {
370     /*
371      * Snapshot length not specified - default to the maximum of the
372      * snapshot lengths of the input files.
373      */
374     snaplen = merge_max_snapshot_length(in_file_count, in_files);
375   }
376
377   /* set the outfile frame type */
378   if (frame_type == -2) {
379     /*
380      * Default to the appropriate frame type for the input files.
381      */
382     frame_type = merge_select_frame_type(in_file_count, in_files);
383     if (verbose) {
384       if (frame_type == WTAP_ENCAP_PER_PACKET) {
385         /*
386          * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
387          */
388         int first_frame_type, this_frame_type;
389
390         first_frame_type = wtap_file_encap(in_files[0].wth);
391         for (i = 1; i < in_file_count; i++) {
392           this_frame_type = wtap_file_encap(in_files[i].wth);
393           if (first_frame_type != this_frame_type) {
394             fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
395             fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
396             fprintf(stderr, "          %s had type %s (%s)\n",
397                     in_files[0].filename,
398                     wtap_encap_string(first_frame_type),
399                     wtap_encap_short_string(first_frame_type));
400             fprintf(stderr, "          %s had type %s (%s)\n",
401                     in_files[i].filename,
402                     wtap_encap_string(this_frame_type),
403                     wtap_encap_short_string(this_frame_type));
404             break;
405           }
406         }
407       }
408       fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
409               wtap_encap_string(frame_type),
410               wtap_encap_short_string(frame_type));
411     }
412   }
413
414   /* open the outfile */
415   if (strncmp(out_filename, "-", 2) == 0) {
416     /* use stdout as the outfile */
417     out_fd = 1 /*stdout*/;
418   } else {
419     /* open the outfile */
420     out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
421     if (out_fd == -1) {
422       fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
423               out_filename, g_strerror(errno));
424       exit(1);
425     }
426   }
427
428   /* prepare the outfile */
429   if(file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG ){
430     wtapng_section_t *shb_hdr;
431     GString *comment_gstr;
432     wtapng_iface_descriptions_t *idb_inf = NULL, *idb_inf_merge_file;
433     wtapng_if_descr_t int_data, *file_int_data;
434     guint itf_count, itf_id = 0;
435
436     shb_hdr = g_new(wtapng_section_t,1);
437     comment_gstr = g_string_new("File created by merging: \n");
438
439     for (i = 0; i < in_file_count; i++) {
440       g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
441     }
442     shb_hdr->section_length = -1;
443     /* options */
444     shb_hdr->opt_comment   = comment_gstr->str; /* NULL if not available */
445     shb_hdr->shb_hardware  = NULL;              /* NULL if not available, UTF-8 string containing the description of the hardware used to create this section. */
446     shb_hdr->shb_os        = NULL;              /* NULL if not available, UTF-8 string containing the name of the operating system used to create this section. */
447     shb_hdr->shb_user_appl = g_strdup("mergecap"); /* NULL if not available, UTF-8 string containing the name of the application used to create this section. */
448
449     if (frame_type == WTAP_ENCAP_PER_PACKET) {
450       /* create fake IDB info */
451       idb_inf = g_new(wtapng_iface_descriptions_t,1);
452       /* TODO make this the number of DIFFERENT encapsulation types
453        * check that snaplength is the same too?
454        */
455       idb_inf->interface_data = g_array_new(FALSE, FALSE, sizeof(wtapng_if_descr_t));
456
457       for (i = 0; i < in_file_count; i++) {
458         idb_inf_merge_file               = wtap_file_get_idb_info(in_files[i].wth);
459         for (itf_count = 0; itf_count < idb_inf_merge_file->interface_data->len; itf_count++) {
460         /* read the interface data from the in file to our combined interface data */
461           file_int_data = &g_array_index (idb_inf_merge_file->interface_data, wtapng_if_descr_t, itf_count);
462           int_data.wtap_encap            = file_int_data->wtap_encap;
463           int_data.time_units_per_second = file_int_data->time_units_per_second;
464           int_data.link_type             = file_int_data->link_type;
465           int_data.snap_len              = file_int_data->snap_len;
466           int_data.if_name               = g_strdup(file_int_data->if_name);
467           int_data.opt_comment           = NULL;
468           int_data.if_description        = NULL;
469           int_data.if_speed              = 0;
470           int_data.if_tsresol            = 6;
471           int_data.if_filter_str         = NULL;
472           int_data.bpf_filter_len        = 0;
473           int_data.if_filter_bpf_bytes   = NULL;
474           int_data.if_os                 = NULL;
475           int_data.if_fcslen             = -1;
476           int_data.num_stat_entries      = 0;          /* Number of ISB:s */
477           int_data.interface_statistics  = NULL;
478
479           g_array_append_val(idb_inf->interface_data, int_data);
480         }
481         g_free(idb_inf_merge_file);
482
483         /* Set fake interface Id in per file data */
484         in_files[i].interface_id = itf_id;
485         itf_id += itf_count;
486       }
487     }
488
489     pdh = wtap_dump_fdopen_ng(out_fd, file_type, frame_type, snaplen,
490                               FALSE /* compressed */, shb_hdr, idb_inf, &open_err);
491     g_string_free(comment_gstr, TRUE);
492   } else {
493     pdh = wtap_dump_fdopen(out_fd, file_type, frame_type, snaplen, FALSE /* compressed */, &open_err);
494   }
495   if (pdh == NULL) {
496     merge_close_in_files(in_file_count, in_files);
497     g_free(in_files);
498     fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
499             wtap_strerror(open_err));
500     exit(1);
501   }
502
503   /* do the merge (or append) */
504   count = 1;
505   for (;;) {
506     if (do_append)
507       in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
508                                          &err_info);
509     else
510       in_file = merge_read_packet(in_file_count, in_files, &read_err,
511                                   &err_info);
512     if (in_file == NULL) {
513       /* EOF */
514       break;
515     }
516
517     if (read_err != 0) {
518       /* I/O error reading from in_file */
519       got_read_error = TRUE;
520       break;
521     }
522
523     if (verbose)
524       fprintf(stderr, "Record: %d\n", count++);
525
526     /* We simply write it, perhaps after truncating it; we could do other
527      * things, like modify it. */
528     phdr = wtap_phdr(in_file->wth);
529     if (snaplen != 0 && phdr->caplen > snaplen) {
530       snap_phdr = *phdr;
531       snap_phdr.caplen = snaplen;
532       phdr = &snap_phdr;
533     }
534     if ((file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) && (frame_type == WTAP_ENCAP_PER_PACKET)) {
535       if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID) {
536         phdr->interface_id += in_file->interface_id;
537       } else {
538         phdr->interface_id = in_file->interface_id;
539         phdr->presence_flags = phdr->presence_flags | WTAP_HAS_INTERFACE_ID;
540       }
541     }
542
543     if (!wtap_dump(pdh, phdr, wtap_buf_ptr(in_file->wth), &write_err, &write_err_info)) {
544       got_write_error = TRUE;
545       break;
546     }
547   }
548
549   merge_close_in_files(in_file_count, in_files);
550   if (!got_write_error) {
551     if (!wtap_dump_close(pdh, &write_err))
552       got_write_error = TRUE;
553   } else {
554     /*
555      * We already got a write error; no need to report another
556      * write error on close.
557      *
558      * Don't overwrite the earlier write error.
559      */
560     (void)wtap_dump_close(pdh, &close_err);
561   }
562
563   if (got_read_error) {
564     /*
565      * Find the file on which we got the error, and report the error.
566      */
567     for (i = 0; i < in_file_count; i++) {
568       if (in_files[i].state == GOT_ERROR) {
569         fprintf(stderr, "mergecap: Error reading %s: %s\n",
570                 in_files[i].filename, wtap_strerror(read_err));
571         if (err_info != NULL) {
572           fprintf(stderr, "(%s)\n", err_info);
573           g_free(err_info);
574         }
575       }
576     }
577   }
578
579   if (got_write_error) {
580     switch (write_err) {
581
582     case WTAP_ERR_UNWRITABLE_ENCAP:
583       /*
584        * This is a problem with the particular frame we're writing and
585        * the file type and subtype we're wwriting; note that, and
586        * report the frame number and file type/subtype.
587        */
588       fprintf(stderr, "mergecap: Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
589               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
590               wtap_file_type_subtype_string(file_type));
591       break;
592
593     case WTAP_ERR_PACKET_TOO_LARGE:
594       /*
595        * This is a problem with the particular frame we're writing and
596        * the file type and subtype we're wwriting; note that, and
597        * report the frame number and file type/subtype.
598        */
599       fprintf(stderr, "mergecap: Frame %u of \"%s\" is too large for a \"%s\" file.\n",
600               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
601               wtap_file_type_subtype_string(file_type));
602       break;
603
604     case WTAP_ERR_UNWRITABLE_REC_TYPE:
605       /*
606        * This is a problem with the particular record we're writing and
607        * the file type and subtype we're wwriting; note that, and
608        * report the record number and file type/subtype.
609        */
610       fprintf(stderr, "mergecap: Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
611               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
612               wtap_file_type_subtype_string(file_type));
613       break;
614
615     case WTAP_ERR_UNWRITABLE_REC_DATA:
616       /*
617        * This is a problem with the particular record we're writing and
618        * the file type and subtype we're wwriting; note that, and
619        * report the record number and file type/subtype.
620        */
621       fprintf(stderr, "mergecap: Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
622               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
623               wtap_file_type_subtype_string(file_type),
624               write_err_info != NULL ? write_err_info : "no information supplied");
625       g_free(write_err_info);
626       break;
627
628     default:
629       fprintf(stderr, "mergecap: Error writing to outfile: %s\n",
630               wtap_strerror(write_err));
631       break;
632     }
633   }
634
635   g_free(in_files);
636
637   return (!got_read_error && !got_write_error) ? 0 : 2;
638 }
639
640 /*
641  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
642  *
643  * Local variables:
644  * c-basic-offset: 2
645  * tab-width: 8
646  * indent-tabs-mode: nil
647  * End:
648  *
649  * vi: set shiftwidth=2 tabstop=8 expandtab:
650  * :indentSize=2:tabSize=8:noTabs=true:
651  */
652