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