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