Add API to expose "expert info" summary.
[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 #include <wiretap/pcap-encap.h>
62
63 #ifdef HAVE_FCNTL_H
64 #include <fcntl.h>
65 #endif
66
67 #ifdef _WIN32
68 #include <wsutil/unicode-utils.h>
69 #endif /* _WIN32 */
70
71 /*
72  * Show the usage
73  */
74 static void
75 print_usage(FILE *output)
76 {
77   fprintf(output, "\n");
78   fprintf(output, "Usage: mergecap [options] -w <outfile>|- <infile> [<infile> ...]\n");
79   fprintf(output, "\n");
80   fprintf(output, "Output:\n");
81   fprintf(output, "  -a                concatenate rather than merge files.\n");
82   fprintf(output, "                    default is to merge based on frame timestamps.\n");
83   fprintf(output, "  -s <snaplen>      truncate packets to <snaplen> bytes of data.\n");
84   fprintf(output, "  -w <outfile>|-    set the output filename to <outfile> or '-' for stdout.\n");
85   fprintf(output, "  -F <capture type> set the output file type; default is pcapng.\n");
86   fprintf(output, "                    an empty \"-F\" option will list the file types.\n");
87   fprintf(output, "  -I <IDB merge mode> set the merge mode for Interface Description Blocks; default is 'all'.\n");
88   fprintf(output, "                    an empty \"-I\" option will list the merge modes.\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 void
129 string_elem_print(gpointer data, gpointer not_used _U_)
130 {
131   fprintf(stderr, "    %s - %s\n", ((struct string_elem *)data)->sstr,
132           ((struct string_elem *)data)->lstr);
133 }
134
135 static void
136 list_capture_types(void) {
137   int i;
138   struct string_elem *captypes;
139   GSList *list = NULL;
140
141   captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES_SUBTYPES);
142
143   fprintf(stderr, "mergecap: The available capture file types for the \"-F\" flag are:\n");
144   for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
145     if (wtap_dump_can_open(i)) {
146       captypes[i].sstr = wtap_file_type_subtype_short_string(i);
147       captypes[i].lstr = wtap_file_type_subtype_string(i);
148       list = g_slist_insert_sorted(list, &captypes[i], string_compare);
149     }
150   }
151   g_slist_foreach(list, string_elem_print, NULL);
152   g_slist_free(list);
153   g_free(captypes);
154 }
155
156 static void
157 list_idb_merge_modes(void) {
158   int i;
159
160   fprintf(stderr, "mergecap: The available IDB merge modes for the \"-I\" flag are:\n");
161   for (i = 0; i < IDB_MERGE_MODE_MAX; i++) {
162     fprintf(stderr, "    %s\n", merge_idb_merge_mode_to_string(i));
163   }
164 }
165
166 static void
167 get_mergecap_compiled_info(GString *str)
168 {
169   /* LIBZ */
170   g_string_append(str, ", ");
171 #ifdef HAVE_LIBZ
172   g_string_append(str, "with libz ");
173 #ifdef ZLIB_VERSION
174   g_string_append(str, ZLIB_VERSION);
175 #else /* ZLIB_VERSION */
176   g_string_append(str, "(version unknown)");
177 #endif /* ZLIB_VERSION */
178 #else /* HAVE_LIBZ */
179   g_string_append(str, "without libz");
180 #endif /* HAVE_LIBZ */
181 }
182
183 static void
184 get_mergecap_runtime_info(GString *str)
185 {
186   /* zlib */
187 #if defined(HAVE_LIBZ) && !defined(_WIN32)
188   g_string_append_printf(str, ", with libz %s", zlibVersion());
189 #endif
190 }
191
192
193 static gboolean
194 merge_callback(merge_event event, int num,
195                const merge_in_file_t in_files[], const guint in_file_count,
196                void *data _U_)
197 {
198   guint i;
199
200   switch (event) {
201
202     case MERGE_EVENT_INPUT_FILES_OPENED:
203       for (i = 0; i < in_file_count; i++) {
204         fprintf(stderr, "mergecap: %s is type %s.\n", in_files[i].filename,
205                 wtap_file_type_subtype_string(wtap_file_type_subtype(in_files[i].wth)));
206       }
207       break;
208
209     case MERGE_EVENT_FRAME_TYPE_SELECTED:
210       /* for this event, num = frame_type */
211       if (num == WTAP_ENCAP_PER_PACKET) {
212         /*
213          * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
214          */
215         int first_frame_type, this_frame_type;
216
217         first_frame_type = wtap_file_encap(in_files[0].wth);
218         for (i = 1; i < in_file_count; i++) {
219           this_frame_type = wtap_file_encap(in_files[i].wth);
220           if (first_frame_type != this_frame_type) {
221             fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
222             fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
223             fprintf(stderr, "          %s had type %s (%s)\n",
224                     in_files[0].filename,
225                     wtap_encap_string(first_frame_type),
226                     wtap_encap_short_string(first_frame_type));
227             fprintf(stderr, "          %s had type %s (%s)\n",
228                     in_files[i].filename,
229                     wtap_encap_string(this_frame_type),
230                     wtap_encap_short_string(this_frame_type));
231             break;
232           }
233         }
234       }
235       fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
236               wtap_encap_string(num),
237               wtap_encap_short_string(num));
238       break;
239
240     case MERGE_EVENT_READY_TO_MERGE:
241       fprintf(stderr, "mergecap: ready to merge records\n");
242       break;
243
244     case MERGE_EVENT_PACKET_WAS_READ:
245       /* for this event, num = count */
246       fprintf(stderr, "Record: %d\n", num);
247       break;
248
249     case MERGE_EVENT_DONE:
250       fprintf(stderr, "mergecap: merging complete\n");
251       break;
252   }
253
254   /* false = do not stop merging */
255   return FALSE;
256 }
257
258
259 int
260 main(int argc, char *argv[])
261 {
262   GString            *comp_info_str;
263   GString            *runtime_info_str;
264   int                 opt;
265 DIAG_OFF(cast-qual)
266   static const struct option long_options[] = {
267       {(char *)"help", no_argument, NULL, 'h'},
268       {(char *)"version", no_argument, NULL, 'V'},
269       {0, 0, 0, 0 }
270   };
271 DIAG_ON(cast-qual)
272   gboolean            do_append          = FALSE;
273   gboolean            verbose            = FALSE;
274   int                 in_file_count      = 0;
275   guint               snaplen            = 0;
276 #ifdef PCAP_NG_DEFAULT
277   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcap format */
278 #else
279   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcapng format */
280 #endif
281   int                 out_fd;
282   int                 err                = 0;
283   gchar              *err_info           = NULL;
284   int                 err_fileno;
285   char               *out_filename       = NULL;
286   merge_result        status;
287   idb_merge_mode      mode               = IDB_MERGE_MODE_MAX;
288   gboolean            use_stdout         = FALSE;
289   merge_progress_callback_t cb;
290
291   cmdarg_err_init(mergecap_cmdarg_err, mergecap_cmdarg_err_cont);
292
293 #ifdef _WIN32
294   arg_list_utf_16to8(argc, argv);
295   create_app_running_mutex();
296 #endif /* _WIN32 */
297
298   /* Get the compile-time version information string */
299   comp_info_str = get_compiled_version_info(NULL, get_mergecap_compiled_info);
300
301   /* Get the run-time version information string */
302   runtime_info_str = get_runtime_version_info(get_mergecap_runtime_info);
303
304   /* Add it to the information to be reported on a crash. */
305   ws_add_crash_info("Mergecap (Wireshark) %s\n"
306        "\n"
307        "%s"
308        "\n"
309        "%s",
310     get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
311
312   /* Process the options first */
313   while ((opt = getopt_long(argc, argv, "aF:hI:s:vVw:", long_options, NULL)) != -1) {
314
315     switch (opt) {
316     case 'a':
317       do_append = !do_append;
318       break;
319
320     case 'F':
321       file_type = wtap_short_string_to_file_type_subtype(optarg);
322       if (file_type < 0) {
323         fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
324                 optarg);
325         list_capture_types();
326         exit(1);
327       }
328       break;
329
330     case 'h':
331       printf("Mergecap (Wireshark) %s\n"
332              "Merge two or more capture files into one.\n"
333              "See http://www.wireshark.org for more information.\n",
334              get_ws_vcs_version_info());
335       print_usage(stdout);
336       exit(0);
337       break;
338
339     case 'I':
340       mode = merge_string_to_idb_merge_mode(optarg);
341       if (mode == IDB_MERGE_MODE_MAX) {
342         fprintf(stderr, "mergecap: \"%s\" isn't a valid IDB merge mode\n",
343                 optarg);
344         list_idb_merge_modes();
345         exit(1);
346       }
347       break;
348
349     case 's':
350       snaplen = get_positive_int(optarg, "snapshot length");
351       break;
352
353     case 'v':
354       verbose = TRUE;
355       break;
356
357     case 'V':
358       show_version("Mergecap (Wireshark)", comp_info_str, runtime_info_str);
359       g_string_free(comp_info_str, TRUE);
360       g_string_free(runtime_info_str, TRUE);
361       exit(0);
362       break;
363
364     case 'w':
365       out_filename = optarg;
366       break;
367
368     case '?':              /* Bad options if GNU getopt */
369       switch(optopt) {
370       case'F':
371         list_capture_types();
372         break;
373       case'I':
374         list_idb_merge_modes();
375         break;
376       default:
377         print_usage(stderr);
378       }
379       exit(1);
380       break;
381     }
382   }
383
384   cb.callback_func = merge_callback;
385   cb.data = NULL;
386
387   /* check for proper args; at a minimum, must have an output
388    * filename and one input file
389    */
390   in_file_count = argc - optind;
391   if (!out_filename) {
392     fprintf(stderr, "mergecap: an output filename must be set with -w\n");
393     fprintf(stderr, "          run with -h for help\n");
394     return 1;
395   }
396   if (in_file_count < 1) {
397     fprintf(stderr, "mergecap: No input files were specified\n");
398     return 1;
399   }
400
401   /* setting IDB merge mode must use PCAPNG output */
402   if (mode != IDB_MERGE_MODE_MAX && file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
403     fprintf(stderr, "The IDB merge mode can only be used with PCAPNG output format\n");
404     return 1;
405   }
406
407   /* if they didn't set IDB merge mode, set it to our default */
408   if (mode == IDB_MERGE_MODE_MAX) {
409     mode = IDB_MERGE_MODE_ALL_SAME;
410   }
411
412   /* open the outfile */
413   if (strncmp(out_filename, "-", 2) == 0) {
414     /* use stdout as the outfile */
415     use_stdout = TRUE;
416     out_fd = 1 /*stdout*/;
417   } else {
418     /* open the outfile */
419     out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
420     if (out_fd == -1) {
421       fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
422               out_filename, g_strerror(errno));
423       exit(1);
424     }
425   }
426
427   /* merge the files */
428   status = merge_files(out_fd, out_filename, file_type,
429                        (const char *const *) &argv[optind], in_file_count,
430                        do_append, mode, snaplen, "mergecap", verbose ? &cb : NULL,
431                        &err, &err_info, &err_fileno);
432
433   switch (status) {
434     case MERGE_OK:
435       break;
436
437     case MERGE_USER_ABORTED:
438       /* we don't catch SIGINT/SIGTERM (yet?), so we couldn't have aborted */
439       g_assert(FALSE);
440       break;
441
442     case MERGE_ERR_CANT_OPEN_INFILE:
443       fprintf(stderr, "mergecap: Can't open %s: %s (%s)\n", argv[optind + err_fileno],
444               wtap_strerror(err), err_info ? err_info : "no more information");
445       break;
446
447     case MERGE_ERR_CANT_OPEN_OUTFILE:
448       fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
449                   wtap_strerror(err));
450       if (!use_stdout)
451         ws_close(out_fd);
452       break;
453
454     case MERGE_ERR_CANT_READ_INFILE:      /* fall through */
455     case MERGE_ERR_BAD_PHDR_INTERFACE_ID:
456     case MERGE_ERR_CANT_WRITE_OUTFILE:
457     case MERGE_ERR_CANT_CLOSE_OUTFILE:
458     default:
459       fprintf(stderr, "mergecap: %s\n", err_info ? err_info : "unknown error");
460       break;
461   }
462
463   g_free(err_info);
464
465   return (status == MERGE_OK) ? 0 : 2;
466 }
467
468 /*
469  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
470  *
471  * Local variables:
472  * c-basic-offset: 2
473  * tab-width: 8
474  * indent-tabs-mode: nil
475  * End:
476  *
477  * vi: set shiftwidth=2 tabstop=8 expandtab:
478  * :indentSize=2:tabSize=8:noTabs=true:
479  */
480