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