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