Suppress a bunch of cast-qual warnings.
[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_UNISTD_H
34 #include <unistd.h>
35 #endif
36
37 #ifdef HAVE_GETOPT_H
38 #include <getopt.h>
39 #endif
40
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44
45 #ifdef HAVE_LIBZ
46 #include <zlib.h>      /* to get the libz version number */
47 #endif
48
49 #include <string.h>
50 #include "wtap.h"
51
52 #ifndef HAVE_GETOPT_LONG
53 #include <wsutil/wsgetopt.h>
54 #endif
55
56 #include <wsutil/clopts_common.h>
57 #include <wsutil/cmdarg_err.h>
58 #include <wsutil/crash_info.h>
59 #include <wsutil/file_util.h>
60 #include <wsutil/strnatcmp.h>
61 #include <wsutil/ws_diag_control.h>
62 #include <wsutil/ws_version_info.h>
63
64 #include <wiretap/merge.h>
65
66 #ifdef HAVE_FCNTL_H
67 #include <fcntl.h>
68 #endif
69
70 #ifdef _WIN32
71 #include <wsutil/unicode-utils.h>
72 #endif /* _WIN32 */
73
74 /*
75  * Show the usage
76  */
77 static void
78 print_usage(FILE *output)
79 {
80   fprintf(output, "\n");
81   fprintf(output, "Usage: mergecap [options] -w <outfile>|- <infile> [<infile> ...]\n");
82   fprintf(output, "\n");
83   fprintf(output, "Output:\n");
84   fprintf(output, "  -a                concatenate rather than merge files.\n");
85   fprintf(output, "                    default is to merge based on frame timestamps.\n");
86   fprintf(output, "  -s <snaplen>      truncate packets to <snaplen> bytes of data.\n");
87   fprintf(output, "  -w <outfile>|-    set the output filename to <outfile> or '-' for stdout.\n");
88   fprintf(output, "  -F <capture type> set the output file type; default is pcapng.\n");
89   fprintf(output, "                    an empty \"-F\" option will list the file types.\n");
90   fprintf(output, "  -T <encap type>   set the output file encapsulation type;\n");
91   fprintf(output, "                    default is the same as the first input file.\n");
92   fprintf(output, "                    an empty \"-T\" option will list the encapsulation types.\n");
93   fprintf(output, "\n");
94   fprintf(output, "Miscellaneous:\n");
95   fprintf(output, "  -h                display this help and exit.\n");
96   fprintf(output, "  -v                verbose output.\n");
97 }
98
99 /*
100  * Report an error in command-line arguments.
101  */
102 static void
103 mergecap_cmdarg_err(const char *fmt, va_list ap)
104 {
105   fprintf(stderr, "mergecap: ");
106   vfprintf(stderr, fmt, ap);
107   fprintf(stderr, "\n");
108 }
109
110 /*
111  * Report additional information for an error in command-line arguments.
112  */
113 static void
114 mergecap_cmdarg_err_cont(const char *fmt, va_list ap)
115 {
116   vfprintf(stderr, fmt, ap);
117   fprintf(stderr, "\n");
118 }
119
120 struct string_elem {
121   const char *sstr;     /* The short string */
122   const char *lstr;     /* The long string */
123 };
124
125 static gint
126 string_compare(gconstpointer a, gconstpointer b)
127 {
128   return strcmp(((const struct string_elem *)a)->sstr,
129                 ((const struct string_elem *)b)->sstr);
130 }
131
132 static gint
133 string_nat_compare(gconstpointer a, gconstpointer b)
134 {
135   return ws_ascii_strnatcmp(((const struct string_elem *)a)->sstr,
136                             ((const struct string_elem *)b)->sstr);
137 }
138
139 static void
140 string_elem_print(gpointer data, gpointer not_used _U_)
141 {
142   fprintf(stderr, "    %s - %s\n", ((struct string_elem *)data)->sstr,
143           ((struct string_elem *)data)->lstr);
144 }
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_encap_types(void) {
169   int i;
170   struct string_elem *encaps;
171   GSList *list = NULL;
172
173   encaps = g_new(struct string_elem,WTAP_NUM_ENCAP_TYPES);
174   fprintf(stderr, "mergecap: The available encapsulation types for the \"-T\" flag are:\n");
175   for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
176     encaps[i].sstr = wtap_encap_short_string(i);
177     if (encaps[i].sstr != NULL) {
178       encaps[i].lstr = wtap_encap_string(i);
179       list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
180     }
181   }
182   g_slist_foreach(list, string_elem_print, NULL);
183   g_slist_free(list);
184   g_free(encaps);
185 }
186
187 static void
188 get_mergecap_compiled_info(GString *str)
189 {
190   /* LIBZ */
191   g_string_append(str, ", ");
192 #ifdef HAVE_LIBZ
193   g_string_append(str, "with libz ");
194 #ifdef ZLIB_VERSION
195   g_string_append(str, ZLIB_VERSION);
196 #else /* ZLIB_VERSION */
197   g_string_append(str, "(version unknown)");
198 #endif /* ZLIB_VERSION */
199 #else /* HAVE_LIBZ */
200   g_string_append(str, "without libz");
201 #endif /* HAVE_LIBZ */
202 }
203
204 static void
205 get_mergecap_runtime_info(GString *str)
206 {
207   /* zlib */
208 #if defined(HAVE_LIBZ) && !defined(_WIN32)
209   g_string_append_printf(str, ", with libz %s", zlibVersion());
210 #endif
211 }
212
213 int
214 main(int argc, char *argv[])
215 {
216   GString            *comp_info_str;
217   GString            *runtime_info_str;
218   int                 opt;
219 DIAG_OFF(cast-qual)
220   static const struct option long_options[] = {
221       {(char *)"help", no_argument, NULL, 'h'},
222       {(char *)"version", no_argument, NULL, 'V'},
223       {0, 0, 0, 0 }
224   };
225 DIAG_ON(cast-qual)
226   gboolean            do_append          = FALSE;
227   gboolean            verbose            = FALSE;
228   int                 in_file_count      = 0;
229   guint               snaplen            = 0;
230 #ifdef PCAP_NG_DEFAULT
231   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAPNG; /* default to pcap format */
232 #else
233   int                 file_type          = WTAP_FILE_TYPE_SUBTYPE_PCAP; /* default to pcapng format */
234 #endif
235   int                 frame_type         = -2;
236   int                 out_fd;
237   merge_in_file_t    *in_files           = NULL, *in_file;
238   int                 i;
239   struct wtap_pkthdr *phdr, snap_phdr;
240   wtap_dumper        *pdh;
241   int                 open_err, read_err = 0, write_err, close_err;
242   gchar              *err_info, *write_err_info = NULL;
243   int                 err_fileno;
244   char               *out_filename       = NULL;
245   gboolean            got_read_error     = FALSE, got_write_error = FALSE;
246   int                 count;
247
248   cmdarg_err_init(mergecap_cmdarg_err, mergecap_cmdarg_err_cont);
249
250 #ifdef _WIN32
251   arg_list_utf_16to8(argc, argv);
252   create_app_running_mutex();
253 #endif /* _WIN32 */
254
255   /* Get the compile-time version information string */
256   comp_info_str = get_compiled_version_info(NULL, get_mergecap_compiled_info);
257
258   /* Get the run-time version information string */
259   runtime_info_str = get_runtime_version_info(get_mergecap_runtime_info);
260
261   /* Add it to the information to be reported on a crash. */
262   ws_add_crash_info("Mergecap (Wireshark) %s\n"
263        "\n"
264        "%s"
265        "\n"
266        "%s",
267     get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
268
269   /* Process the options first */
270   while ((opt = getopt_long(argc, argv, "aF:hs:T:vVw:", long_options, NULL)) != -1) {
271
272     switch (opt) {
273     case 'a':
274       do_append = !do_append;
275       break;
276
277     case 'F':
278       file_type = wtap_short_string_to_file_type_subtype(optarg);
279       if (file_type < 0) {
280         fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
281                 optarg);
282         list_capture_types();
283         exit(1);
284       }
285       break;
286
287     case 'h':
288       printf("Mergecap (Wireshark) %s\n"
289              "Merge two or more capture files into one.\n"
290              "See http://www.wireshark.org for more information.\n",
291              get_ws_vcs_version_info());
292       print_usage(stdout);
293       exit(0);
294       break;
295
296     case 's':
297       snaplen = get_positive_int(optarg, "snapshot length");
298       break;
299
300     case 'T':
301       frame_type = wtap_short_string_to_encap(optarg);
302       if (frame_type < 0) {
303         fprintf(stderr, "mergecap: \"%s\" isn't a valid encapsulation type\n",
304                 optarg);
305         list_encap_types();
306         exit(1);
307       }
308       break;
309
310     case 'v':
311       verbose = TRUE;
312       break;
313
314     case 'V':
315       show_version("Mergecap (Wireshark)", comp_info_str, runtime_info_str);
316       g_string_free(comp_info_str, TRUE);
317       g_string_free(runtime_info_str, TRUE);
318       exit(0);
319       break;
320
321     case 'w':
322       out_filename = optarg;
323       break;
324
325     case '?':              /* Bad options if GNU getopt */
326       switch(optopt) {
327       case'F':
328         list_capture_types();
329         break;
330       case'T':
331         list_encap_types();
332         break;
333       default:
334         print_usage(stderr);
335       }
336       exit(1);
337       break;
338     }
339   }
340
341   /* check for proper args; at a minimum, must have an output
342    * filename and one input file
343    */
344   in_file_count = argc - optind;
345   if (!out_filename) {
346     fprintf(stderr, "mergecap: an output filename must be set with -w\n");
347     fprintf(stderr, "          run with -h for help\n");
348     return 1;
349   }
350   if (in_file_count < 1) {
351     fprintf(stderr, "mergecap: No input files were specified\n");
352     return 1;
353   }
354
355   /* open the input files */
356   if (!merge_open_in_files(in_file_count, &argv[optind], &in_files,
357                            &open_err, &err_info, &err_fileno)) {
358     fprintf(stderr, "mergecap: Can't open %s: %s\n", argv[optind + err_fileno],
359             wtap_strerror(open_err));
360     if (err_info != NULL) {
361       fprintf(stderr, "(%s)\n", err_info);
362       g_free(err_info);
363     }
364     return 2;
365   }
366
367   if (verbose) {
368     for (i = 0; i < in_file_count; i++)
369       fprintf(stderr, "mergecap: %s is type %s.\n", argv[optind + i],
370               wtap_file_type_subtype_string(wtap_file_type_subtype(in_files[i].wth)));
371   }
372
373   if (snaplen == 0) {
374     /*
375      * Snapshot length not specified - default to the maximum of the
376      * snapshot lengths of the input files.
377      */
378     snaplen = merge_max_snapshot_length(in_file_count, in_files);
379   }
380
381   /* set the outfile frame type */
382   if (frame_type == -2) {
383     /*
384      * Default to the appropriate frame type for the input files.
385      */
386     frame_type = merge_select_frame_type(in_file_count, in_files);
387     if (verbose) {
388       if (frame_type == WTAP_ENCAP_PER_PACKET) {
389         /*
390          * Find out why we had to choose WTAP_ENCAP_PER_PACKET.
391          */
392         int first_frame_type, this_frame_type;
393
394         first_frame_type = wtap_file_encap(in_files[0].wth);
395         for (i = 1; i < in_file_count; i++) {
396           this_frame_type = wtap_file_encap(in_files[i].wth);
397           if (first_frame_type != this_frame_type) {
398             fprintf(stderr, "mergecap: multiple frame encapsulation types detected\n");
399             fprintf(stderr, "          defaulting to WTAP_ENCAP_PER_PACKET\n");
400             fprintf(stderr, "          %s had type %s (%s)\n",
401                     in_files[0].filename,
402                     wtap_encap_string(first_frame_type),
403                     wtap_encap_short_string(first_frame_type));
404             fprintf(stderr, "          %s had type %s (%s)\n",
405                     in_files[i].filename,
406                     wtap_encap_string(this_frame_type),
407                     wtap_encap_short_string(this_frame_type));
408             break;
409           }
410         }
411       }
412       fprintf(stderr, "mergecap: selected frame_type %s (%s)\n",
413               wtap_encap_string(frame_type),
414               wtap_encap_short_string(frame_type));
415     }
416   }
417
418   /* open the outfile */
419   if (strncmp(out_filename, "-", 2) == 0) {
420     /* use stdout as the outfile */
421     out_fd = 1 /*stdout*/;
422   } else {
423     /* open the outfile */
424     out_fd = ws_open(out_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
425     if (out_fd == -1) {
426       fprintf(stderr, "mergecap: Couldn't open output file %s: %s\n",
427               out_filename, g_strerror(errno));
428       exit(1);
429     }
430   }
431
432   /* prepare the outfile */
433   if(file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG ){
434     wtapng_section_t *shb_hdr;
435     GString *comment_gstr;
436
437     shb_hdr = g_new(wtapng_section_t,1);
438     comment_gstr = g_string_new("File created by merging: \n");
439
440     for (i = 0; i < in_file_count; i++) {
441       g_string_append_printf(comment_gstr, "File%d: %s \n",i+1,in_files[i].filename);
442     }
443     shb_hdr->section_length = -1;
444     /* options */
445     shb_hdr->opt_comment   = comment_gstr->str; /* NULL if not available */
446     shb_hdr->shb_hardware  = NULL;              /* NULL if not available, UTF-8 string containing the description of the hardware used to create this section. */
447     shb_hdr->shb_os        = NULL;              /* NULL if not available, UTF-8 string containing the name of the operating system used to create this section. */
448     shb_hdr->shb_user_appl = g_strdup("mergecap"); /* NULL if not available, UTF-8 string containing the name of the application used to create this section. */
449
450     pdh = wtap_dump_fdopen_ng(out_fd, file_type, frame_type, snaplen,
451                               FALSE /* compressed */, shb_hdr, NULL /* wtapng_iface_descriptions_t *idb_inf */, &open_err);
452     g_string_free(comment_gstr, TRUE);
453   } else {
454     pdh = wtap_dump_fdopen(out_fd, file_type, frame_type, snaplen, FALSE /* compressed */, &open_err);
455   }
456   if (pdh == NULL) {
457     merge_close_in_files(in_file_count, in_files);
458     g_free(in_files);
459     fprintf(stderr, "mergecap: Can't open or create %s: %s\n", out_filename,
460             wtap_strerror(open_err));
461     exit(1);
462   }
463
464   /* do the merge (or append) */
465   count = 1;
466   for (;;) {
467     if (do_append)
468       in_file = merge_append_read_packet(in_file_count, in_files, &read_err,
469                                          &err_info);
470     else
471       in_file = merge_read_packet(in_file_count, in_files, &read_err,
472                                   &err_info);
473     if (in_file == NULL) {
474       /* EOF */
475       break;
476     }
477
478     if (read_err != 0) {
479       /* I/O error reading from in_file */
480       got_read_error = TRUE;
481       break;
482     }
483
484     if (verbose)
485       fprintf(stderr, "Record: %d\n", count++);
486
487     /* We simply write it, perhaps after truncating it; we could do other
488      * things, like modify it. */
489     phdr = wtap_phdr(in_file->wth);
490     if (snaplen != 0 && phdr->caplen > snaplen) {
491       snap_phdr = *phdr;
492       snap_phdr.caplen = snaplen;
493       phdr = &snap_phdr;
494     }
495
496     if (!wtap_dump(pdh, phdr, wtap_buf_ptr(in_file->wth), &write_err, &write_err_info)) {
497       got_write_error = TRUE;
498       break;
499     }
500   }
501
502   merge_close_in_files(in_file_count, in_files);
503   if (!got_write_error) {
504     if (!wtap_dump_close(pdh, &write_err))
505       got_write_error = TRUE;
506   } else {
507     /*
508      * We already got a write error; no need to report another
509      * write error on close.
510      *
511      * Don't overwrite the earlier write error.
512      */
513     (void)wtap_dump_close(pdh, &close_err);
514   }
515
516   if (got_read_error) {
517     /*
518      * Find the file on which we got the error, and report the error.
519      */
520     for (i = 0; i < in_file_count; i++) {
521       if (in_files[i].state == GOT_ERROR) {
522         fprintf(stderr, "mergecap: Error reading %s: %s\n",
523                 in_files[i].filename, wtap_strerror(read_err));
524         if (err_info != NULL) {
525           fprintf(stderr, "(%s)\n", err_info);
526           g_free(err_info);
527         }
528       }
529     }
530   }
531
532   if (got_write_error) {
533     switch (write_err) {
534
535     case WTAP_ERR_UNWRITABLE_ENCAP:
536       /*
537        * This is a problem with the particular frame we're writing and
538        * the file type and subtype we're wwriting; note that, and
539        * report the frame number and file type/subtype.
540        */
541       fprintf(stderr, "mergecap: Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
542               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
543               wtap_file_type_subtype_string(file_type));
544       break;
545
546     case WTAP_ERR_PACKET_TOO_LARGE:
547       /*
548        * This is a problem with the particular frame we're writing and
549        * the file type and subtype we're wwriting; note that, and
550        * report the frame number and file type/subtype.
551        */
552       fprintf(stderr, "mergecap: Frame %u of \"%s\" is too large for a \"%s\" file.\n",
553               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
554               wtap_file_type_subtype_string(file_type));
555       break;
556
557     case WTAP_ERR_UNWRITABLE_REC_TYPE:
558       /*
559        * This is a problem with the particular record we're writing and
560        * the file type and subtype we're wwriting; note that, and
561        * report the record number and file type/subtype.
562        */
563       fprintf(stderr, "mergecap: Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
564               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
565               wtap_file_type_subtype_string(file_type));
566       break;
567
568     case WTAP_ERR_UNWRITABLE_REC_DATA:
569       /*
570        * This is a problem with the particular record we're writing and
571        * the file type and subtype we're wwriting; note that, and
572        * report the record number and file type/subtype.
573        */
574       fprintf(stderr, "mergecap: Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
575               in_file ? in_file->packet_num : 0, in_file ? in_file->filename : "UNKNOWN",
576               wtap_file_type_subtype_string(file_type),
577               write_err_info != NULL ? write_err_info : "no information supplied");
578       g_free(write_err_info);
579       break;
580
581     default:
582       fprintf(stderr, "mergecap: Error writing to outfile: %s\n",
583               wtap_strerror(write_err));
584       break;
585     }
586   }
587
588   g_free(in_files);
589
590   return (!got_read_error && !got_write_error) ? 0 : 2;
591 }
592
593 /*
594  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
595  *
596  * Local variables:
597  * c-basic-offset: 2
598  * tab-width: 8
599  * indent-tabs-mode: nil
600  * End:
601  *
602  * vi: set shiftwidth=2 tabstop=8 expandtab:
603  * :indentSize=2:tabSize=8:noTabs=true:
604  */
605