[Automatic update for 2016-10-30]
[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_GETOPT_H
34 #include <getopt.h>
35 #endif
36
37 #include <string.h>
38
39 #include <wiretap/wtap.h>
40
41 #ifndef HAVE_GETOPT_LONG
42 #include <wsutil/wsgetopt.h>
43 #endif
44
45 #include <wsutil/clopts_common.h>
46 #include <wsutil/cmdarg_err.h>
47 #include <wsutil/crash_info.h>
48 #include <wsutil/filesystem.h>
49 #include <wsutil/file_util.h>
50 #include <wsutil/privileges.h>
51 #include <wsutil/strnatcmp.h>
52 #include <ws_version_info.h>
53
54 #ifdef HAVE_PLUGINS
55 #include <wsutil/plugins.h>
56 #endif
57
58 #include <wsutil/report_err.h>
59
60 #include <wiretap/merge.h>
61
62 #ifdef _WIN32
63 #include <wsutil/unicode-utils.h>
64 #endif /* _WIN32 */
65
66 /*
67  * Show the usage
68  */
69 static void
70 print_usage(FILE *output)
71 {
72   fprintf(output, "\n");
73   fprintf(output, "Usage: mergecap [options] -w <outfile>|- <infile> [<infile> ...]\n");
74   fprintf(output, "\n");
75   fprintf(output, "Output:\n");
76   fprintf(output, "  -a                concatenate rather than merge files.\n");
77   fprintf(output, "                    default is to merge based on frame timestamps.\n");
78   fprintf(output, "  -s <snaplen>      truncate packets to <snaplen> bytes of data.\n");
79   fprintf(output, "  -w <outfile>|-    set the output filename to <outfile> or '-' for stdout.\n");
80   fprintf(output, "  -F <capture type> set the output file type; default is pcapng.\n");
81   fprintf(output, "                    an empty \"-F\" option will list the file types.\n");
82   fprintf(output, "  -I <IDB merge mode> set the merge mode for Interface Description Blocks; default is 'all'.\n");
83   fprintf(output, "                    an empty \"-I\" option will list the merge modes.\n");
84   fprintf(output, "\n");
85   fprintf(output, "Miscellaneous:\n");
86   fprintf(output, "  -h                display this help and exit.\n");
87   fprintf(output, "  -v                verbose output.\n");
88 }
89
90 /*
91  * Report an error in command-line arguments.
92  */
93 static void
94 mergecap_cmdarg_err(const char *fmt, va_list ap)
95 {
96   fprintf(stderr, "mergecap: ");
97   vfprintf(stderr, fmt, ap);
98   fprintf(stderr, "\n");
99 }
100
101 /*
102  * Report additional information for an error in command-line arguments.
103  */
104 static void
105 mergecap_cmdarg_err_cont(const char *fmt, va_list ap)
106 {
107   vfprintf(stderr, fmt, ap);
108   fprintf(stderr, "\n");
109 }
110
111 struct string_elem {
112   const char *sstr;     /* The short string */
113   const char *lstr;     /* The long string */
114 };
115
116 static gint
117 string_compare(gconstpointer a, gconstpointer b)
118 {
119   return strcmp(((const struct string_elem *)a)->sstr,
120                 ((const struct string_elem *)b)->sstr);
121 }
122
123 static void
124 string_elem_print(gpointer data, gpointer not_used _U_)
125 {
126   fprintf(stderr, "    %s - %s\n", ((struct string_elem *)data)->sstr,
127           ((struct string_elem *)data)->lstr);
128 }
129
130 #ifdef HAVE_PLUGINS
131 /*
132  * General errors are reported with an console message in mergecap.
133  */
134 static void
135 failure_message(const char *msg_format, va_list ap)
136 {
137   fprintf(stderr, "mergecap: ");
138   vfprintf(stderr, msg_format, ap);
139   fprintf(stderr, "\n");
140 }
141 #endif
142
143 static void
144 list_capture_types(void) {
145   int i;
146   struct string_elem *captypes;
147   GSList *list = NULL;
148
149   captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES_SUBTYPES);
150
151   fprintf(stderr, "mergecap: The available capture file types for the \"-F\" flag are:\n");
152   for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
153     if (wtap_dump_can_open(i)) {
154       captypes[i].sstr = wtap_file_type_subtype_short_string(i);
155       captypes[i].lstr = wtap_file_type_subtype_string(i);
156       list = g_slist_insert_sorted(list, &captypes[i], string_compare);
157     }
158   }
159   g_slist_foreach(list, string_elem_print, NULL);
160   g_slist_free(list);
161   g_free(captypes);
162 }
163
164 static void
165 list_idb_merge_modes(void) {
166   int i;
167
168   fprintf(stderr, "mergecap: The available IDB merge modes for the \"-I\" flag are:\n");
169   for (i = 0; i < IDB_MERGE_MODE_MAX; i++) {
170     fprintf(stderr, "    %s\n", merge_idb_merge_mode_to_string(i));
171   }
172 }
173
174 static gboolean
175 merge_callback(merge_event event, int num,
176                const merge_in_file_t in_files[], const guint in_file_count,
177                void *data _U_)
178 {
179   guint i;
180
181   switch (event) {
182
183     case MERGE_EVENT_INPUT_FILES_OPENED:
184       for (i = 0; i < in_file_count; i++) {
185         fprintf(stderr, "mergecap: %s is type %s.\n", in_files[i].filename,
186                 wtap_file_type_subtype_string(wtap_file_type_subtype(in_files[i].wth)));
187       }
188       break;
189
190     case MERGE_EVENT_FRAME_TYPE_SELECTED:
191       /* for this event, num = frame_type */
192       if (num == WTAP_ENCAP_PER_PACKET) {
193         /*
194          * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
195          */
196         int first_frame_type, this_frame_type;
197
198         first_frame_type = wtap_file_encap(in_files[0].wth);
199         for (i = 1; i < in_file_count; i++) {
200           this_frame_type = wtap_file_encap(in_files[i].wth);
201           if (first_frame_type != this_frame_type) {
202             fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
203             fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
204             fprintf(stderr, "          %s had type %s (%s)\n",
205                     in_files[0].filename,
206                     wtap_encap_string(first_frame_type),
207                     wtap_encap_short_string(first_frame_type));
208             fprintf(stderr, "          %s had type %s (%s)\n",
209                     in_files[i].filename,
210                     wtap_encap_string(this_frame_type),
211                     wtap_encap_short_string(this_frame_type));
212             break;
213           }
214         }
215       }
216       fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
217               wtap_encap_string(num),
218               wtap_encap_short_string(num));
219       break;
220
221     case MERGE_EVENT_READY_TO_MERGE:
222       fprintf(stderr, "mergecap: ready to merge records\n");
223       break;
224
225     case MERGE_EVENT_PACKET_WAS_READ:
226       /* for this event, num = count */
227       fprintf(stderr, "Record: %d\n", num);
228       break;
229
230     case MERGE_EVENT_DONE:
231       fprintf(stderr, "mergecap: merging complete\n");
232       break;
233   }
234
235   /* false = do not stop merging */
236   return FALSE;
237 }
238
239
240 int
241 main(int argc, char *argv[])
242 {
243   GString            *comp_info_str;
244   GString            *runtime_info_str;
245   int                 opt;
246   static const struct option long_options[] = {
247       {"help", no_argument, NULL, 'h'},
248       {"version", no_argument, NULL, 'V'},
249       {0, 0, 0, 0 }
250   };
251   gboolean            do_append          = FALSE;
252   gboolean            verbose            = FALSE;
253   int                 in_file_count      = 0;
254   guint32             snaplen            = 0;
255 #ifdef PCAP_NG_DEFAULT
256   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcap format */
257 #else
258   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcapng format */
259 #endif
260   int                 out_fd;
261   int                 err                = 0;
262   gchar              *err_info           = NULL;
263   int                 err_fileno;
264   char               *out_filename       = NULL;
265   merge_result        status;
266   idb_merge_mode      mode               = IDB_MERGE_MODE_MAX;
267   gboolean            use_stdout         = FALSE;
268   merge_progress_callback_t cb;
269
270 #ifdef HAVE_PLUGINS
271   char  *init_progfile_dir_error;
272 #endif
273
274   cmdarg_err_init(mergecap_cmdarg_err, mergecap_cmdarg_err_cont);
275
276 #ifdef _WIN32
277   arg_list_utf_16to8(argc, argv);
278   create_app_running_mutex();
279 #endif /* _WIN32 */
280
281   /* Get the compile-time version information string */
282   comp_info_str = get_compiled_version_info(NULL, NULL);
283
284   /* Get the run-time version information string */
285   runtime_info_str = get_runtime_version_info(NULL);
286
287   /* Add it to the information to be reported on a crash. */
288   ws_add_crash_info("Mergecap (Wireshark) %s\n"
289        "\n"
290        "%s"
291        "\n"
292        "%s",
293     get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
294   g_string_free(comp_info_str, TRUE);
295   g_string_free(runtime_info_str, TRUE);
296
297   /*
298    * Get credential information for later use.
299    */
300   init_process_policies();
301   init_open_routines();
302
303 #ifdef HAVE_PLUGINS
304   /* Register wiretap plugins */
305   if ((init_progfile_dir_error = init_progfile_dir(argv[0], main))) {
306     g_warning("mergecap: init_progfile_dir(): %s", init_progfile_dir_error);
307     g_free(init_progfile_dir_error);
308   } else {
309     /* Register all the plugin types we have. */
310     wtap_register_plugin_types(); /* Types known to libwiretap */
311
312     init_report_err(failure_message,NULL,NULL,NULL);
313
314     /* Scan for plugins.  This does *not* call their registration routines;
315        that's done later.
316
317        Don't report failures to load plugins because most (non-wiretap)
318        plugins *should* fail to load (because we're not linked against
319        libwireshark and dissector plugins need libwireshark).*/
320     scan_plugins(DONT_REPORT_LOAD_FAILURE);
321
322     /* Register all libwiretap plugin modules. */
323     register_all_wiretap_modules();
324   }
325 #endif
326
327   /* Process the options first */
328   while ((opt = getopt_long(argc, argv, "aF:hI:s:vVw:", long_options, NULL)) != -1) {
329
330     switch (opt) {
331     case 'a':
332       do_append = !do_append;
333       break;
334
335     case 'F':
336       file_type = wtap_short_string_to_file_type_subtype(optarg);
337       if (file_type < 0) {
338         fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
339                 optarg);
340         list_capture_types();
341         exit(1);
342       }
343       break;
344
345     case 'h':
346       printf("Mergecap (Wireshark) %s\n"
347              "Merge two or more capture files into one.\n"
348              "See https://www.wireshark.org for more information.\n",
349              get_ws_vcs_version_info());
350       print_usage(stdout);
351       exit(0);
352       break;
353
354     case 'I':
355       mode = merge_string_to_idb_merge_mode(optarg);
356       if (mode == IDB_MERGE_MODE_MAX) {
357         fprintf(stderr, "mergecap: \"%s\" isn't a valid IDB merge mode\n",
358                 optarg);
359         list_idb_merge_modes();
360         exit(1);
361       }
362       break;
363
364     case 's':
365       snaplen = get_nonzero_guint32(optarg, "snapshot length");
366       break;
367
368     case 'v':
369       verbose = TRUE;
370       break;
371
372     case 'V':
373       comp_info_str = get_compiled_version_info(NULL, NULL);
374       runtime_info_str = get_runtime_version_info(NULL);
375       show_version("Mergecap (Wireshark)", comp_info_str, runtime_info_str);
376       g_string_free(comp_info_str, TRUE);
377       g_string_free(runtime_info_str, TRUE);
378       exit(0);
379       break;
380
381     case 'w':
382       out_filename = optarg;
383       break;
384
385     case '?':              /* Bad options if GNU getopt */
386       switch(optopt) {
387       case'F':
388         list_capture_types();
389         break;
390       case'I':
391         list_idb_merge_modes();
392         break;
393       default:
394         print_usage(stderr);
395       }
396       exit(1);
397       break;
398     }
399   }
400
401   cb.callback_func = merge_callback;
402   cb.data = NULL;
403
404   /* check for proper args; at a minimum, must have an output
405    * filename and one input file
406    */
407   in_file_count = argc - optind;
408   if (!out_filename) {
409     fprintf(stderr, "mergecap: an output filename must be set with -w\n");
410     fprintf(stderr, "          run with -h for help\n");
411     return 1;
412   }
413   if (in_file_count < 1) {
414     fprintf(stderr, "mergecap: No input files were specified\n");
415     return 1;
416   }
417
418   /* setting IDB merge mode must use PCAPNG output */
419   if (mode != IDB_MERGE_MODE_MAX && file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
420     fprintf(stderr, "The IDB merge mode can only be used with PCAPNG output format\n");
421     return 1;
422   }
423
424   /* if they didn't set IDB merge mode, set it to our default */
425   if (mode == IDB_MERGE_MODE_MAX) {
426     mode = IDB_MERGE_MODE_ALL_SAME;
427   }
428
429   /* open the outfile */
430   if (strcmp(out_filename, "-") == 0) {
431     /* use stdout as the outfile */
432     use_stdout = TRUE;
433     out_fd = 1 /*stdout*/;
434   } else {
435     /* open the outfile */
436     out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
437     if (out_fd == -1) {
438       fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
439               out_filename, g_strerror(errno));
440       exit(1);
441     }
442   }
443
444   /* merge the files */
445   status = merge_files(out_fd, out_filename, file_type,
446                        (const char *const *) &argv[optind], in_file_count,
447                        do_append, mode, snaplen, "mergecap", verbose ? &cb : NULL,
448                        &err, &err_info, &err_fileno);
449
450   switch (status) {
451     case MERGE_OK:
452       break;
453
454     case MERGE_USER_ABORTED:
455       /* we don't catch SIGINT/SIGTERM (yet?), so we couldn't have aborted */
456       g_assert(FALSE);
457       break;
458
459     case MERGE_ERR_CANT_OPEN_INFILE:
460       fprintf(stderr, "mergecap: Can't open %s: %s (%s)\n", argv[optind + err_fileno],
461               wtap_strerror(err), err_info ? err_info : "no more information");
462       break;
463
464     case MERGE_ERR_CANT_OPEN_OUTFILE:
465       fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
466                   wtap_strerror(err));
467       if (!use_stdout)
468         ws_close(out_fd);
469       break;
470
471     case MERGE_ERR_CANT_READ_INFILE:      /* fall through */
472     case MERGE_ERR_BAD_PHDR_INTERFACE_ID:
473     case MERGE_ERR_CANT_WRITE_OUTFILE:
474     case MERGE_ERR_CANT_CLOSE_OUTFILE:
475     default:
476       fprintf(stderr, "mergecap: %s\n", err_info ? err_info : "unknown error");
477       break;
478   }
479
480   g_free(err_info);
481
482   return (status == MERGE_OK) ? 0 : 2;
483 }
484
485 /*
486  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
487  *
488  * Local variables:
489  * c-basic-offset: 2
490  * tab-width: 8
491  * indent-tabs-mode: nil
492  * End:
493  *
494  * vi: set shiftwidth=2 tabstop=8 expandtab:
495  * :indentSize=2:tabSize=8:noTabs=true:
496  */
497