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