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