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