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