Send error messages to the standard error, and include the program name
[metze/wireshark/wip.git] / mergecap.c
1 /* Combine two 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",
79             name);
80     exit(1);
81   }
82   if (number > INT_MAX) {
83     fprintf(stderr, "mergecap: The specified %s is too large (greater than %d)\n",
84             name, INT_MAX);
85     exit(1);
86   }
87   return (int)number;
88 }
89
90 static int
91 get_positive_int(const char *string, const char *name)
92 {
93   int number;
94
95   number = get_natural_int(string, name);
96
97   if (number == 0) {
98     fprintf(stderr, "mergecap: The specified %s is zero\n",
99             name);
100     exit(1);
101   }
102
103   return number;
104 }
105
106 /*
107  * Show the usage
108  */
109 static void
110 usage(void)
111 {
112
113   fprintf(stderr, "Mergecap %s"
114 #ifdef SVNVERSION
115           " (" SVNVERSION " from " SVNPATH ")"
116 #endif
117           "\n", VERSION);
118   fprintf(stderr, "Merge two or more capture files into one.\n");
119   fprintf(stderr, "See http://www.wireshark.org for more information.\n");
120   fprintf(stderr, "\n");
121   fprintf(stderr, "Usage: mergecap [options] -w <outfile>|- <infile> [<infile> ...]\n");
122   fprintf(stderr, "\n");
123   fprintf(stderr, "Output:\n");
124   fprintf(stderr, "  -a                concatenate rather than merge files.\n");
125   fprintf(stderr, "                    default is to merge based on frame timestamps.\n");
126   fprintf(stderr, "  -s <snaplen>      truncate packets to <snaplen> bytes of data.\n");
127   fprintf(stderr, "  -w <outfile>|-    set the output filename to <outfile> or '-' for stdout.\n");
128   fprintf(stderr, "  -F <capture type> set the output file type; default is pcapng.\n");
129   fprintf(stderr, "                    an empty \"-F\" option will list the file types.\n");
130   fprintf(stderr, "  -T <encap type>   set the output file encapsulation type;\n");
131   fprintf(stderr, "                    default is the same as the first input file.\n");
132   fprintf(stderr, "                    an empty \"-T\" option will list the encapsulation types.\n");
133   fprintf(stderr, "\n");
134   fprintf(stderr, "Miscellaneous:\n");
135   fprintf(stderr, "  -h                display this help and exit.\n");
136   fprintf(stderr, "  -v                verbose output.\n");
137 }
138
139 struct string_elem {
140     const char *sstr;   /* The short string */
141     const char *lstr;   /* The long string */
142 };
143
144 static gint
145 string_compare(gconstpointer a, gconstpointer b)
146 {
147     return strcmp(((const struct string_elem *)a)->sstr,
148         ((const struct string_elem *)b)->sstr);
149 }
150
151 static gint
152 string_nat_compare(gconstpointer a, gconstpointer b)
153 {
154     return strnatcmp(((const struct string_elem *)a)->sstr,
155         ((const struct string_elem *)b)->sstr);
156 }
157
158 static void
159 string_elem_print(gpointer data, gpointer not_used _U_)
160 {
161     fprintf(stderr, "    %s - %s\n",
162         ((struct string_elem *)data)->sstr,
163         ((struct string_elem *)data)->lstr);
164 }
165
166 static void
167 list_capture_types(void) {
168   int i;
169   struct string_elem *captypes;
170   GSList *list = NULL;
171
172   captypes = g_new(struct string_elem,WTAP_NUM_FILE_TYPES);
173
174   fprintf(stderr, "mergecap: The available capture file types for the \"-F\" flag are:\n");
175   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
176     if (wtap_dump_can_open(i)) {
177       captypes[i].sstr = wtap_file_type_short_string(i);
178       captypes[i].lstr = wtap_file_type_string(i);
179       list = g_slist_insert_sorted(list, &captypes[i], string_compare);
180     }
181   }
182   g_slist_foreach(list, string_elem_print, NULL);
183   g_slist_free(list);
184   g_free(captypes);
185 }
186
187 static void
188 list_encap_types(void) {
189     int i;
190     struct string_elem *encaps;
191     GSList *list = NULL;
192
193     encaps = g_new(struct string_elem,WTAP_NUM_ENCAP_TYPES);
194     fprintf(stderr, "mergecap: The available encapsulation types for the \"-T\" flag are:\n");
195     for (i = 0; i < WTAP_NUM_ENCAP_TYPES; i++) {
196         encaps[i].sstr = wtap_encap_short_string(i);
197         if (encaps[i].sstr != NULL) {
198             encaps[i].lstr = wtap_encap_string(i);
199             list = g_slist_insert_sorted(list, &encaps[i], string_nat_compare);
200         }
201     }
202     g_slist_foreach(list, string_elem_print, NULL);
203     g_slist_free(list);
204     g_free(encaps);
205 }
206
207 int
208 main(int argc, char *argv[])
209 {
210   int          opt;
211
212   gboolean     do_append     = FALSE;
213   gboolean     verbose       = FALSE;
214   int          in_file_count = 0;
215   guint        snaplen = 0;
216 #ifdef PCAP_NG_DEFAULT
217   int          file_type = WTAP_FILE_PCAPNG;    /* default to pcap format */
218 #else
219   int          file_type = WTAP_FILE_PCAP;      /* default to pcapng format */
220 #endif
221   int          frame_type = -2;
222   int          out_fd;
223   merge_in_file_t   *in_files      = NULL, *in_file;
224   int          i;
225   struct wtap_pkthdr *phdr, snap_phdr;
226   wtap_dumper *pdh;
227   int          open_err, read_err=0, write_err, close_err;
228   gchar       *err_info;
229   int          err_fileno;
230   char        *out_filename = NULL;
231   gboolean     got_read_error = FALSE, got_write_error = FALSE;
232   int          count;
233
234 #ifdef _WIN32
235   arg_list_utf_16to8(argc, argv);
236   create_app_running_mutex();
237 #endif /* _WIN32 */
238
239   /* Process the options first */
240   while ((opt = getopt(argc, argv, "hvas:T:F:w:")) != -1) {
241
242     switch (opt) {
243     case 'w':
244       out_filename = optarg;
245       break;
246
247     case 'a':
248       do_append = !do_append;
249       break;
250
251     case 'T':
252       frame_type = wtap_short_string_to_encap(optarg);
253       if (frame_type < 0) {
254         fprintf(stderr, "mergecap: \"%s\" isn't a valid encapsulation type\n",
255             optarg);
256         list_encap_types();
257         exit(1);
258       }
259       break;
260
261     case 'F':
262       file_type = wtap_short_string_to_file_type(optarg);
263       if (file_type < 0) {
264         fprintf(stderr, "mergecap: \"%s\" isn't a valid capture file type\n",
265             optarg);
266         list_capture_types();
267         exit(1);
268       }
269       break;
270
271     case 'v':
272       verbose = TRUE;
273       break;
274
275     case 's':
276       snaplen = get_positive_int(optarg, "snapshot length");
277       break;
278
279     case 'h':
280       usage();
281       exit(0);
282       break;
283
284     case '?':              /* Bad options if GNU getopt */
285       switch(optopt) {
286       case'F':
287         list_capture_types();
288         break;
289       case'T':
290         list_encap_types();
291         break;
292       default:
293         usage();
294       }
295       exit(1);
296       break;
297
298     }
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_string(wtap_file_type(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_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_read_error && !got_write_error) {
470     if (!wtap_dump_close(pdh, &write_err))
471       got_write_error = TRUE;
472   } else
473     wtap_dump_close(pdh, &close_err);
474
475   if (got_read_error) {
476     /*
477      * Find the file on which we got the error, and report the error.
478      */
479     for (i = 0; i < in_file_count; i++) {
480       if (in_files[i].state == GOT_ERROR) {
481         fprintf(stderr, "mergecap: Error reading %s: %s\n",
482                 in_files[i].filename, wtap_strerror(read_err));
483         switch (read_err) {
484
485         case WTAP_ERR_UNSUPPORTED:
486         case WTAP_ERR_UNSUPPORTED_ENCAP:
487         case WTAP_ERR_BAD_FILE:
488           fprintf(stderr, "(%s)\n", err_info);
489           g_free(err_info);
490           break;
491         }
492       }
493     }
494   }
495
496   if (got_write_error) {
497     switch (write_err) {
498
499     case WTAP_ERR_UNSUPPORTED_ENCAP:
500       /*
501        * This is a problem with the particular frame we're writing;
502        * note that, and give the frame number.
503        */
504       fprintf(stderr, "mergecap: Frame %u of \"%s\" has a network type that can't be saved in a file with that format\n.",
505               in_file->packet_num, in_file->filename);
506       break;
507
508     default:
509       fprintf(stderr, "mergecap: Error writing to outfile: %s\n",
510               wtap_strerror(write_err));
511       break;
512     }
513   }
514
515   g_free(in_files);
516
517   return (!got_read_error && !got_write_error) ? 0 : 2;
518 }