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