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