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