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