Use explicit casts.
[metze/wireshark/wip.git] / capinfos.c
1 /* capinfos.c
2  * Reports capture file information including # of packets, duration, others
3  *
4  * Copyright 2004 Ian Schorr
5  *
6  * $Id$
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25  */
26
27 /*
28  * 2009-09-19: jyoung
29  *
30  * New capinfos features
31  *
32  * Continue processing additional files after
33  * a wiretap open failure.  The new -C option
34  * reverts to capinfos' original behavior which
35  * is to cancel any further file processing at
36  * first file open failure.
37  *
38  * Change the behavior of how the default display
39  * of all infos is initiated.  This gets rid of a
40  * special post getopt() argument count test.
41  *
42  * Add new table output format (with related options)
43  * This feature allows outputting the various infos
44  * into a tab delimited text file, or to a comma
45  * separated variables file (*.csv) instead of the
46  * original "long" format.
47  *
48  * 2011-04-05: wmeier
49  * behaviour changed: Upon exit capinfos will return
50  *  an error status if an error occurred at any
51  *  point during "continuous" file processing.
52  *  (Previously a success status was always
53  *   returned if the -C option was not used).
54  *
55
56  */
57
58
59 #include "config.h"
60
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <stdarg.h>
65 #include <locale.h>
66 #include <errno.h>
67
68 #ifdef HAVE_UNISTD_H
69 #include <unistd.h>
70 #endif
71
72 #ifdef HAVE_SYS_TIME_H
73 #include <sys/time.h>
74 #endif
75
76 #include <glib.h>
77
78 #include <epan/packet.h>
79 #include <epan/filesystem.h>
80 #include <epan/plugins.h>
81 #include <epan/report_err.h>
82 #include "wtap.h"
83 #include <wsutil/privileges.h>
84 #include <wsutil/str_util.h>
85
86 #ifdef HAVE_LIBGCRYPT
87 #include <wsutil/wsgcrypt.h>
88 #include <wsutil/file_util.h>
89 #endif
90
91 #ifndef HAVE_GETOPT
92 #include "wsutil/wsgetopt.h"
93 #endif
94
95 #ifdef _WIN32
96 #include <wsutil/unicode-utils.h>
97 #endif /* _WIN32 */
98
99 #include "svnversion.h"
100
101 /*
102  * By default capinfos now continues processing
103  * the next filename if and when wiretap detects
104  * a problem opening a file.
105  * Use the '-C' option to revert back to original
106  * capinfos behavior which is to abort any
107  * additional file processing at first open file
108  * failure.
109  */
110
111 static gboolean continue_after_wtap_open_offline_failure = TRUE;
112
113 /*
114  * table report variables
115  */
116
117 static gboolean long_report = TRUE;         /* By default generate long report       */
118 static gchar table_report_header = TRUE;    /* Generate column header by default     */
119 static gchar field_separator = '\t';        /* Use TAB as field separator by default */
120 static gchar quote_char = '\0';             /* Do NOT quote fields by default        */
121 static gboolean machine_readable = FALSE;   /* Display machine-readable numbers      */
122
123 /*
124  * capinfos has the ability to report on a number of
125  * various characteristics ("infos") for each input file.
126  *
127  * By default reporting of all info fields is enabled.
128  *
129  * Optionally the reporting of any specific info field
130  * or combination of info fields can be enabled with
131  * individual options.
132  */
133
134 static gboolean report_all_infos = TRUE;    /* Report all infos           */
135
136 static gboolean cap_file_type = TRUE;       /* Report capture type        */
137 static gboolean cap_file_encap = TRUE;      /* Report encapsulation       */
138 static gboolean cap_snaplen = TRUE;         /* Packet size limit (snaplen)*/
139 static gboolean cap_packet_count = TRUE;    /* Report packet count        */
140 static gboolean cap_file_size = TRUE;       /* Report file size           */
141
142 static gboolean cap_data_size = TRUE;       /* Report packet byte size    */
143 static gboolean cap_duration = TRUE;        /* Report capture duration    */
144 static gboolean cap_start_time = TRUE;      /* Report capture start time  */
145 static gboolean cap_end_time = TRUE;        /* Report capture end time    */
146 static gboolean time_as_secs = FALSE;       /* Report time values as raw seconds */
147
148 static gboolean cap_data_rate_byte = TRUE;  /* Report data rate bytes/sec */
149 static gboolean cap_data_rate_bit = TRUE;   /* Report data rate bites/sec */
150 static gboolean cap_packet_size = TRUE;     /* Report average packet size */
151 static gboolean cap_packet_rate = TRUE;     /* Report average packet rate */
152 static gboolean cap_order = TRUE;           /* Report if packets are in chronological order (True/False) */
153
154 #ifdef HAVE_LIBGCRYPT
155 static gboolean cap_file_hashes = TRUE;     /* Calculate file hashes */
156 #endif
157
158 #ifdef USE_GOPTION
159 static gboolean cap_help = FALSE;
160 static gboolean table_report = FALSE;
161
162 static GOptionEntry general_entries[] =
163 {
164 /* General */
165   { "type", 't', 0, G_OPTION_ARG_NONE, &cap_file_type,
166     "display the capture file type", NULL },
167   { "Encapsulation", 'E', 0, G_OPTION_ARG_NONE, &cap_file_encap,
168     "display the capture file encapsulation", NULL },
169 #ifdef HAVE_LIBGCRYPT
170   { "Hash", 'H', 0, G_OPTION_ARG_NONE, &cap_file_hashes,
171     "display the SHA1, RMD160, and MD5 hashes of the file", NULL },
172 #endif /* HAVE_LIBGCRYPT */
173  { NULL,'\0',0,G_OPTION_ARG_NONE,NULL,NULL,NULL }
174 };
175 static GOptionEntry size_entries[] =
176 {
177 /* Size */
178   { "packets", 'c', 0, G_OPTION_ARG_NONE, &cap_packet_count,
179     "display the number of packets", NULL },
180   { "size", 's', 0, G_OPTION_ARG_NONE, &cap_file_size,
181     "display the size of the file (in bytes)", NULL },
182   { "tot-len-of-pkts", 'd', 0, G_OPTION_ARG_NONE, &cap_data_size,
183     "display the total length of all packets (in bytes)", NULL },
184   { "snap", 'l', 0, G_OPTION_ARG_NONE, &cap_snaplen,
185     "display the packet size limit (snapshot length)", NULL },
186   { NULL,'\0',0,G_OPTION_ARG_NONE,NULL,NULL,NULL }
187 };
188 static GOptionEntry time_entries[] =
189 {
190 /* Time */
191   { "duration", 'u', 0, G_OPTION_ARG_NONE, &cap_duration,
192     "display the capture duration (in seconds)", NULL },
193   { "start", 'a', 0, G_OPTION_ARG_NONE, &cap_start_time,
194     "display the capture start time", NULL },
195   { "end", 'e', 0, G_OPTION_ARG_NONE, &cap_end_time,
196     "display the capture end time", NULL },
197   { "cron", 'o', 0, G_OPTION_ARG_NONE, &cap_order,
198     "display the capture file chronological status (True/False)", NULL },
199   { "start-end-time-sec", 'S', 0, G_OPTION_ARG_NONE, &time_as_secs,
200     "display start and end times as seconds", NULL },
201   { NULL,'\0',0,G_OPTION_ARG_NONE,NULL,NULL,NULL }
202 };
203
204 static GOptionEntry stats_entries[] =
205 {
206 /* Statistics */
207   { "bytes", 'y', 0, G_OPTION_ARG_NONE, &cap_data_rate_byte,
208     "display average data rate (in bytes/s)", NULL },
209   { "bits", 'i', 0, G_OPTION_ARG_NONE, &cap_data_rate_bit,
210     "display average data rate (in bits/s)", NULL },
211   { "packet-bytes", 'z', 0, G_OPTION_ARG_NONE, &cap_packet_size,
212     "display average packet size (in bytes)", NULL },
213   { "packets", 'x', 0, G_OPTION_ARG_NONE, &cap_packet_rate,
214     "display average packet rate (in packets/s)", NULL },
215   { NULL,'\0',0,G_OPTION_ARG_NONE,NULL,NULL,NULL }
216 };
217
218 static GOptionEntry output_format_entries[] =
219 {
220 /* Output format */
221   { "long", 'L', 0, G_OPTION_ARG_NONE, &long_report,
222     "generate long report (default)", NULL },
223   { "Table", 'T', 0, G_OPTION_ARG_NONE, &table_report,
224     "generate table report", NULL },
225   { "machine-readable", 'M', 0, G_OPTION_ARG_NONE, &machine_readable,
226     "display machine-readable (unabbreviated) values in long reports", NULL },
227   { NULL,'\0',0,G_OPTION_ARG_NONE,NULL,NULL,NULL }
228 };
229
230 static GOptionEntry table_report_entries[] =
231 {
232 /* Table report */
233   { "header-rec", 'R', 0, G_OPTION_ARG_NONE, &table_report_header,
234     "generate header record (default)", NULL },
235   { "no-table", 'r', 0, G_OPTION_ARG_NONE, &table_report_header,
236     "do not generate header record", NULL },
237   { NULL,'\0',0,G_OPTION_ARG_NONE,NULL,NULL,NULL }
238 };
239
240 static GOptionEntry misc_entries[] =
241 {
242   { "helpcompat", 'h', 0, G_OPTION_ARG_NONE, &cap_help,
243     "display help", NULL },
244  { NULL,'\0',0,G_OPTION_ARG_NONE,NULL,NULL,NULL }
245 };
246
247 GOptionContext *ctx;
248 GOptionGroup *general_grp, *size_grp, *time_grp, *stats_grp, *output_grp, *table_report_grp;
249 GError *parse_err = NULL;
250
251 #endif /* USE_GOPTION */
252
253 #ifdef HAVE_LIBGCRYPT
254 #define HASH_SIZE_SHA1 20
255 #define HASH_SIZE_RMD160 20
256 #define HASH_SIZE_MD5 16
257
258 #define HASH_STR_SIZE (41) /* Max hash size * 2 + '\0' */
259 #define HASH_BUF_SIZE (1024 * 1024)
260
261
262 static gchar file_sha1[HASH_STR_SIZE];
263 static gchar file_rmd160[HASH_STR_SIZE];
264 static gchar file_md5[HASH_STR_SIZE];
265
266 #define FILE_HASH_OPT "H"
267 #else
268 #define FILE_HASH_OPT ""
269 #endif /* HAVE_LIBGCRYPT */
270
271 /*
272  * If we have at least two packets with time stamps, and they're not in
273  * order - i.e., the later packet has a time stamp older than the earlier
274  * packet - the time stamps are known not to be in order.
275  *
276  * If every packet has a time stamp, and they're all in order, the time
277  * stamp is known to be in order.
278  *
279  * Otherwise, we have no idea.
280  */
281 typedef enum {
282   IN_ORDER,
283   NOT_IN_ORDER,
284   ORDER_UNKNOWN
285 } order_t;
286
287 typedef struct _capture_info {
288   const char    *filename;
289   guint16       file_type;
290   gboolean      iscompressed;
291   int           file_encap;
292   gint64        filesize;
293
294   guint64       packet_bytes;
295   gboolean      times_known;
296   double        start_time;
297   double        stop_time;
298   guint32       packet_count;
299   gboolean      snap_set;                /* If set in capture file header      */
300   guint32       snaplen;                 /* value from the capture file header */
301   guint32       snaplen_min_inferred;    /* If caplen < len for 1 or more rcds */
302   guint32       snaplen_max_inferred;    /*  ...                               */
303   gboolean      drops_known;
304   guint32       drop_count;
305
306   double        duration;
307   double        packet_rate;
308   double        packet_size;
309   double        data_rate;              /* in bytes */
310   gboolean      know_order;
311   order_t       order;
312
313   int          *encap_counts;           /* array of per_packet encap counts; array has one entry per wtap_encap type */
314 } capture_info;
315
316
317 static void
318 enable_all_infos(void)
319 {
320   report_all_infos = TRUE;
321
322   cap_file_type = TRUE;
323   cap_file_encap = TRUE;
324   cap_snaplen = TRUE;
325   cap_packet_count = TRUE;
326   cap_file_size = TRUE;
327
328   cap_data_size = TRUE;
329   cap_duration = TRUE;
330   cap_start_time = TRUE;
331   cap_end_time = TRUE;
332   cap_order = TRUE;
333
334   cap_data_rate_byte = TRUE;
335   cap_data_rate_bit = TRUE;
336   cap_packet_size = TRUE;
337   cap_packet_rate = TRUE;
338
339 #ifdef HAVE_LIBGCRYPT
340   cap_file_hashes = TRUE;
341 #endif /* HAVE_LIBGCRYPT */
342 }
343
344 static void
345 disable_all_infos(void)
346 {
347   report_all_infos   = FALSE;
348
349   cap_file_type      = FALSE;
350   cap_file_encap     = FALSE;
351   cap_snaplen        = FALSE;
352   cap_packet_count   = FALSE;
353   cap_file_size      = FALSE;
354
355   cap_data_size      = FALSE;
356   cap_duration       = FALSE;
357   cap_start_time     = FALSE;
358   cap_end_time       = FALSE;
359   cap_order          = FALSE;
360
361   cap_data_rate_byte = FALSE;
362   cap_data_rate_bit  = FALSE;
363   cap_packet_size    = FALSE;
364   cap_packet_rate    = FALSE;
365
366 #ifdef HAVE_LIBGCRYPT
367   cap_file_hashes = FALSE;
368 #endif /* HAVE_LIBGCRYPT */
369 }
370
371 static const gchar *
372 order_string(order_t order)
373 {
374   switch (order) {
375
376   case IN_ORDER:
377     return "True";
378
379   case NOT_IN_ORDER:
380     return "False";
381
382   case ORDER_UNKNOWN:
383     return "Unknown";
384
385   default:
386     return "???";  /* "cannot happen" (the next step is "Profit!") */
387   }
388 }
389
390 static gchar *
391 time_string(time_t timer, capture_info *cf_info, gboolean want_lf)
392 {
393   const gchar *lf = want_lf ? "\n" : "";
394   static gchar time_string_buf[20];
395   char *time_string_ctime;
396
397   if (cf_info->times_known && cf_info->packet_count > 0) {
398     if (time_as_secs) {
399       /* XXX - Would it be useful to show sub-second precision? */
400       g_snprintf(time_string_buf, 20, "%lu%s", (unsigned long)timer, lf);
401       return time_string_buf;
402     } else {
403 #if (defined _WIN32) && (_MSC_VER < 1500)
404       /* calling localtime(), and thus ctime(), on MSVC 2005 with huge values causes it to crash */
405       /* XXX - find the exact value that still does work */
406       /* XXX - using _USE_32BIT_TIME_T might be another way to circumvent this problem */
407       if (timer > 2000000000) {
408         time_string_ctime = NULL;
409       } else
410 #endif
411       time_string_ctime = ctime(&timer);
412       if (time_string_ctime == NULL) {
413         g_snprintf(time_string_buf, 20, "Not representable%s", lf);
414         return time_string_buf;
415       }
416       if (!want_lf) {
417         /*
418          * The ctime() function returns a string formatted as:
419          *   "Www Mmm dd hh:mm:ss yyyy\n"
420          * The unwanted '\n' is the 24th character.
421          */
422         time_string_ctime[24] = '\0';
423       }
424       return time_string_ctime;
425     }
426   }
427
428   g_snprintf(time_string_buf, 15, "n/a%s", lf);
429   return time_string_buf;
430 }
431
432 static double
433 secs_nsecs(const struct wtap_nstime * nstime)
434 {
435   return (nstime->nsecs / 1000000000.0) + (double)nstime->secs;
436 }
437
438 static void print_value(const gchar *text_p1, gint width, const gchar *text_p2, double value) {
439   if (value > 0.0)
440     printf("%s%.*f%s\n", text_p1, width, value, text_p2);
441   else
442     printf("%sn/a\n", text_p1);
443 }
444
445 static void
446 print_stats(const gchar *filename, capture_info *cf_info)
447 {
448   const gchar           *file_type_string, *file_encap_string;
449   time_t                start_time_t;
450   time_t                stop_time_t;
451   gchar                 *size_string;
452
453   /* Build printable strings for various stats */
454   file_type_string = wtap_file_type_string(cf_info->file_type);
455   file_encap_string = wtap_encap_string(cf_info->file_encap);
456   start_time_t = (time_t)cf_info->start_time;
457   stop_time_t = (time_t)cf_info->stop_time;
458
459   if (filename)           printf     ("File name:           %s\n", filename);
460   if (cap_file_type)      printf     ("File type:           %s%s\n",
461                                       file_type_string,
462                                       cf_info->iscompressed ? " (gzip compressed)" : "");
463   if (cap_file_encap)     printf     ("File encapsulation:  %s\n", file_encap_string);
464   if (cap_file_encap && (cf_info->file_encap == WTAP_ENCAP_PER_PACKET)) {
465     int i;
466     for (i=0; i<WTAP_NUM_ENCAP_TYPES; i++) {
467       if (cf_info->encap_counts[i] > 0)
468         printf("                       %s\n", wtap_encap_string(i));
469     }
470   }
471   if (cap_snaplen && cf_info->snap_set)
472                           printf     ("Packet size limit:   file hdr: %u bytes\n", cf_info->snaplen);
473   else if(cap_snaplen && !cf_info->snap_set)
474                           printf     ("Packet size limit:   file hdr: (not set)\n");
475   if (cf_info->snaplen_max_inferred > 0) {
476     if (cf_info->snaplen_min_inferred == cf_info->snaplen_max_inferred)
477                           printf     ("Packet size limit:   inferred: %u bytes\n", cf_info->snaplen_min_inferred);
478     else
479                           printf     ("Packet size limit:   inferred: %u bytes - %u bytes (range)\n",
480                                       cf_info->snaplen_min_inferred, cf_info->snaplen_max_inferred);
481   }
482   if (cap_packet_count) {
483     printf     ("Number of packets:   ");
484     if (machine_readable) {
485       printf ("%u\n", cf_info->packet_count);
486     } else {
487       size_string = format_size(cf_info->packet_count, format_size_unit_none);
488       printf ("%s\n", size_string);
489       g_free(size_string);
490     }
491   }
492   if (cap_file_size) {
493     printf     ("File size:           ");
494     if (machine_readable) {
495       printf     ("%" G_GINT64_MODIFIER "d bytes\n", cf_info->filesize);
496     } else {
497       size_string = format_size(cf_info->filesize, format_size_unit_bytes);
498       printf ("%s\n", size_string);
499       g_free(size_string);
500     }
501   }
502   if (cap_data_size) {
503     printf     ("Data size:           ");
504     if (machine_readable) {
505       printf     ("%" G_GINT64_MODIFIER "u bytes\n", cf_info->packet_bytes);
506     } else {
507       size_string = format_size(cf_info->packet_bytes, format_size_unit_bytes);
508       printf ("%s\n", size_string);
509       g_free(size_string);
510     }
511   }
512   if (cf_info->times_known) {
513     if (cap_duration) /* XXX - shorten to hh:mm:ss */
514                           print_value("Capture duration:    ", 0, " seconds",   cf_info->duration);
515     if (cap_start_time)
516                           printf     ("Start time:          %s", time_string(start_time_t, cf_info, TRUE));
517     if (cap_end_time)
518                           printf     ("End time:            %s", time_string(stop_time_t, cf_info, TRUE));
519     if (cap_data_rate_byte) {
520                           printf     ("Data byte rate:      ");
521       if (machine_readable) {
522         print_value("", 2, " bytes/sec",   cf_info->data_rate);
523       } else {
524         size_string = format_size((gint64)cf_info->data_rate, format_size_unit_bytes_s);
525         printf ("%s\n", size_string);
526         g_free(size_string);
527       }
528     }
529     if (cap_data_rate_bit) {
530                           printf     ("Data bit rate:       ");
531       if (machine_readable) {
532         print_value("", 2, " bits/sec",    cf_info->data_rate*8);
533       } else {
534         size_string = format_size((gint64)(cf_info->data_rate*8), format_size_unit_bits_s);
535         printf ("%s\n", size_string);
536         g_free(size_string);
537       }
538     }
539   }
540   if (cap_packet_size)    printf     ("Average packet size: %.2f bytes\n",        cf_info->packet_size);
541   if (cf_info->times_known) {
542     if (cap_packet_rate) {
543                           printf     ("Average packet rate: ");
544       if (machine_readable) {
545         print_value("", 2, " packets/sec", cf_info->packet_rate);
546       } else {
547         size_string = format_size((gint64)cf_info->packet_rate, format_size_unit_none);
548         printf ("%spackets/sec\n", size_string);
549         g_free(size_string);
550       }
551     }
552   }
553 #ifdef HAVE_LIBGCRYPT
554   if (cap_file_hashes) {
555                           printf     ("SHA1:                %s\n", file_sha1);
556                           printf     ("RIPEMD160:           %s\n", file_rmd160);
557                           printf     ("MD5:                 %s\n", file_md5);
558   }
559 #endif /* HAVE_LIBGCRYPT */
560   if (cap_order)          printf     ("Strict time order:   %s\n", order_string(cf_info->order));
561 }
562
563 static void
564 putsep(void)
565 {
566   if (field_separator) putchar(field_separator);
567 }
568
569 static void
570 putquote(void)
571 {
572   if (quote_char) putchar(quote_char);
573 }
574
575 static void
576 print_stats_table_header_label(const gchar *label)
577 {
578   putsep();
579   putquote();
580   printf("%s", label);
581   putquote();
582 }
583
584 static void
585 print_stats_table_header(void)
586 {
587   putquote();
588   printf("File name");
589   putquote();
590
591   if (cap_file_type)      print_stats_table_header_label("File type");
592   if (cap_file_encap)     print_stats_table_header_label("File encapsulation");
593   if (cap_snaplen)        print_stats_table_header_label("Packet size limit");
594   if (cap_snaplen)        print_stats_table_header_label("Packet size limit min (inferred)");
595   if (cap_snaplen)        print_stats_table_header_label("Packet size limit max (inferred)");
596   if (cap_packet_count)   print_stats_table_header_label("Number of packets");
597   if (cap_file_size)      print_stats_table_header_label("File size (bytes)");
598   if (cap_data_size)      print_stats_table_header_label("Data size (bytes)");
599   if (cap_duration)       print_stats_table_header_label("Capture duration (seconds)");
600   if (cap_start_time)     print_stats_table_header_label("Start time");
601   if (cap_end_time)       print_stats_table_header_label("End time");
602   if (cap_data_rate_byte) print_stats_table_header_label("Data byte rate (bytes/sec)");
603   if (cap_data_rate_bit)  print_stats_table_header_label("Data bit rate (bits/sec)");
604   if (cap_packet_size)    print_stats_table_header_label("Average packet size (bytes)");
605   if (cap_packet_rate)    print_stats_table_header_label("Average packet rate (packets/sec)");
606 #ifdef HAVE_LIBGCRYPT
607   if (cap_file_hashes) {
608                           print_stats_table_header_label("SHA1");
609                           print_stats_table_header_label("RIPEMD160");
610                           print_stats_table_header_label("MD5");
611   }
612 #endif /* HAVE_LIBGCRYPT */
613   if (cap_order)          print_stats_table_header_label("Strict time order");
614
615   printf("\n");
616 }
617
618 static void
619 print_stats_table(const gchar *filename, capture_info *cf_info)
620 {
621   const gchar           *file_type_string, *file_encap_string;
622   time_t                start_time_t;
623   time_t                stop_time_t;
624
625   /* Build printable strings for various stats */
626   file_type_string = wtap_file_type_string(cf_info->file_type);
627   file_encap_string = wtap_encap_string(cf_info->file_encap);
628   start_time_t = (time_t)cf_info->start_time;
629   stop_time_t = (time_t)cf_info->stop_time;
630
631   if (filename) {
632     putquote();
633     printf("%s", filename);
634     putquote();
635   }
636
637   if (cap_file_type) {
638     putsep();
639     putquote();
640     printf("%s", file_type_string);
641     putquote();
642   }
643
644   /* ToDo: If WTAP_ENCAP_PER_PACKET, show the list of encapsulations encountered;
645    *       Output a line for each different encap with all fields repeated except
646    *        the encapsulation field which has "Per Packet: ..." for each
647    *        encapsulation type seen ?
648    */
649   if (cap_file_encap) {
650     putsep();
651     putquote();
652     printf("%s", file_encap_string);
653     putquote();
654   }
655
656   if (cap_snaplen) {
657     putsep();
658     putquote();
659     if(cf_info->snap_set)
660       printf("%u", cf_info->snaplen);
661     else
662       printf("(not set)");
663     putquote();
664     if (cf_info->snaplen_max_inferred > 0) {
665       putsep();
666       putquote();
667       printf("%u", cf_info->snaplen_min_inferred);
668       putquote();
669       putsep();
670       putquote();
671       printf("%u", cf_info->snaplen_max_inferred);
672       putquote();
673     }
674     else {
675       putsep();
676       putquote();
677       printf("n/a");
678       putquote();
679       putsep();
680       putquote();
681       printf("n/a");
682       putquote();
683     }
684   }
685
686   if (cap_packet_count) {
687     putsep();
688     putquote();
689     printf("%u", cf_info->packet_count);
690     putquote();
691   }
692
693   if (cap_file_size) {
694     putsep();
695     putquote();
696     printf("%" G_GINT64_MODIFIER "d", cf_info->filesize);
697     putquote();
698   }
699
700   if (cap_data_size) {
701     putsep();
702     putquote();
703     printf("%" G_GINT64_MODIFIER "u", cf_info->packet_bytes);
704     putquote();
705   }
706
707   if (cap_duration) {
708     putsep();
709     putquote();
710     if (cf_info->times_known)
711       printf("%f", cf_info->duration);
712     else
713       printf("n/a");
714     putquote();
715   }
716
717   if (cap_start_time) {
718     putsep();
719     putquote();
720     printf("%s", time_string(start_time_t, cf_info, FALSE));
721     putquote();
722   }
723
724   if (cap_end_time) {
725     putsep();
726     putquote();
727     printf("%s", time_string(stop_time_t, cf_info, FALSE));
728     putquote();
729   }
730
731   if (cap_data_rate_byte) {
732     putsep();
733     putquote();
734     if (cf_info->times_known)
735       printf("%.2f", cf_info->data_rate);
736     else
737       printf("n/a");
738     putquote();
739   }
740
741   if (cap_data_rate_bit) {
742     putsep();
743     putquote();
744     if (cf_info->times_known)
745       printf("%.2f", cf_info->data_rate*8);
746     else
747       printf("n/a");
748     putquote();
749   }
750
751   if (cap_packet_size) {
752     putsep();
753     putquote();
754     printf("%.2f", cf_info->packet_size);
755     putquote();
756   }
757
758   if (cap_packet_rate) {
759     putsep();
760     putquote();
761     if (cf_info->times_known)
762       printf("%.2f", cf_info->packet_rate);
763     else
764       printf("n/a");
765     putquote();
766   }
767
768 #ifdef HAVE_LIBGCRYPT
769   if (cap_file_hashes) {
770     putsep();
771     putquote();
772     printf("%s", file_sha1);
773     putquote();
774
775     putsep();
776     putquote();
777     printf("%s", file_rmd160);
778     putquote();
779
780     putsep();
781     putquote();
782     printf("%s", file_md5);
783     putquote();
784   }
785 #endif /* HAVE_LIBGCRYPT */
786
787   if (cap_order) {
788     putsep();
789     putquote();
790     printf("%s", order_string(cf_info->order));
791     putquote();
792   }
793
794   printf("\n");
795 }
796
797 static int
798 process_cap_file(wtap *wth, const char *filename)
799 {
800   int                   err;
801   gchar                 *err_info;
802   gint64                size;
803   gint64                data_offset;
804
805   guint32               packet = 0;
806   gint64                bytes  = 0;
807   guint32               snaplen_min_inferred = 0xffffffff;
808   guint32               snaplen_max_inferred =          0;
809   const struct wtap_pkthdr *phdr;
810   capture_info          cf_info;
811   gboolean              have_times = TRUE;
812   double                start_time = 0;
813   double                stop_time  = 0;
814   double                cur_time   = 0;
815   double                prev_time = 0;
816   gboolean              know_order = FALSE;
817   order_t               order = IN_ORDER;
818
819   cf_info.encap_counts = g_new0(int,WTAP_NUM_ENCAP_TYPES);
820
821   /* Tally up data that we need to parse through the file to find */
822   while (wtap_read(wth, &err, &err_info, &data_offset))  {
823     phdr = wtap_phdr(wth);
824     if (phdr->presence_flags & WTAP_HAS_TS) {
825       prev_time = cur_time;
826       cur_time = secs_nsecs(&phdr->ts);
827       if(packet==0) {
828         start_time = cur_time;
829         stop_time = cur_time;
830         prev_time = cur_time;
831       }
832       if (cur_time < prev_time) {
833         order = NOT_IN_ORDER;
834       }
835       if (cur_time < start_time) {
836         start_time = cur_time;
837       }
838       if (cur_time > stop_time) {
839         stop_time = cur_time;
840       }
841     } else {
842       have_times = FALSE; /* at least one packet has no time stamp */
843       if (order != NOT_IN_ORDER)
844         order = ORDER_UNKNOWN;
845     }
846
847     bytes+=phdr->len;
848     packet++;
849
850     /* If caplen < len for a rcd, then presumably           */
851     /* 'Limit packet capture length' was done for this rcd. */
852     /* Keep track as to the min/max actual snapshot lengths */
853     /*  seen for this file.                                 */
854     if (phdr->caplen < phdr->len) {
855       if (phdr->caplen < snaplen_min_inferred)
856         snaplen_min_inferred = phdr->caplen;
857       if (phdr->caplen > snaplen_max_inferred)
858         snaplen_max_inferred = phdr->caplen;
859     }
860
861     /* Per-packet encapsulation */
862     if (wtap_file_encap(wth) == WTAP_ENCAP_PER_PACKET) {
863         if ((phdr->pkt_encap > 0) && (phdr->pkt_encap < WTAP_NUM_ENCAP_TYPES)) {
864             cf_info.encap_counts[phdr->pkt_encap] += 1;
865         } else {
866             fprintf(stderr, "capinfos: Unknown per-packet encapsulation: %d [frame number: %d]\n", phdr->pkt_encap, packet);
867         }
868     }
869
870   } /* while */
871
872   if (err != 0) {
873     fprintf(stderr,
874             "capinfos: An error occurred after reading %u packets from \"%s\": %s.\n",
875             packet, filename, wtap_strerror(err));
876     switch (err) {
877
878     case WTAP_ERR_UNSUPPORTED:
879     case WTAP_ERR_UNSUPPORTED_ENCAP:
880     case WTAP_ERR_BAD_FILE:
881     case WTAP_ERR_DECOMPRESS:
882       fprintf(stderr, "(%s)\n", err_info);
883       g_free(err_info);
884       break;
885     }
886     g_free(cf_info.encap_counts);
887     return 1;
888   }
889
890   /* File size */
891   size = wtap_file_size(wth, &err);
892   if (size == -1) {
893     fprintf(stderr,
894             "capinfos: Can't get size of \"%s\": %s.\n",
895             filename, g_strerror(err));
896     g_free(cf_info.encap_counts);
897     return 1;
898   }
899
900   cf_info.filesize = size;
901
902   /* File Type */
903   cf_info.file_type = wtap_file_type(wth);
904   cf_info.iscompressed = wtap_iscompressed(wth);
905
906   /* File Encapsulation */
907   cf_info.file_encap = wtap_file_encap(wth);
908
909   /* Packet size limit (snaplen) */
910   cf_info.snaplen = wtap_snapshot_length(wth);
911   if(cf_info.snaplen > 0)
912     cf_info.snap_set = TRUE;
913   else
914     cf_info.snap_set = FALSE;
915
916   cf_info.snaplen_min_inferred = snaplen_min_inferred;
917   cf_info.snaplen_max_inferred = snaplen_max_inferred;
918
919   /* # of packets */
920   cf_info.packet_count = packet;
921
922   /* File Times */
923   cf_info.times_known = have_times;
924   cf_info.start_time = start_time;
925   cf_info.stop_time = stop_time;
926   cf_info.duration = stop_time-start_time;
927   cf_info.know_order = know_order;
928   cf_info.order = order;
929
930   /* Number of packet bytes */
931   cf_info.packet_bytes = bytes;
932
933   cf_info.data_rate   = 0.0;
934   cf_info.packet_rate = 0.0;
935   cf_info.packet_size = 0.0;
936
937   if (packet > 0) {
938     if (cf_info.duration > 0.0) {
939       cf_info.data_rate   = (double)bytes  / (stop_time-start_time); /* Data rate per second */
940       cf_info.packet_rate = (double)packet / (stop_time-start_time); /* packet rate per second */
941     }
942     cf_info.packet_size = (double)bytes / packet;                  /* Avg packet size      */
943   }
944
945   if(long_report) {
946     print_stats(filename, &cf_info);
947   } else {
948     print_stats_table(filename, &cf_info);
949   }
950
951   g_free(cf_info.encap_counts);
952
953   return 0;
954 }
955
956 static void
957 usage(gboolean is_error)
958 {
959   FILE *output;
960
961   if (!is_error) {
962     output = stdout;
963     /* XXX - add capinfos header info here */
964   }
965   else {
966     output = stderr;
967   }
968
969   fprintf(output, "Capinfos %s"
970 #ifdef SVNVERSION
971           " (" SVNVERSION " from " SVNPATH ")"
972 #endif
973           "\n", VERSION);
974   fprintf(output, "Prints various information (infos) about capture files.\n");
975   fprintf(output, "See http://www.wireshark.org for more information.\n");
976   fprintf(output, "\n");
977   fprintf(output, "Usage: capinfos [options] <infile> ...\n");
978   fprintf(output, "\n");
979   fprintf(output, "General infos:\n");
980   fprintf(output, "  -t display the capture file type\n");
981   fprintf(output, "  -E display the capture file encapsulation\n");
982 #ifdef HAVE_LIBGCRYPT
983   fprintf(output, "  -H display the SHA1, RMD160, and MD5 hashes of the file\n");
984 #endif
985   fprintf(output, "\n");
986   fprintf(output, "Size infos:\n");
987   fprintf(output, "  -c display the number of packets\n");
988   fprintf(output, "  -s display the size of the file (in bytes)\n");
989   fprintf(output, "  -d display the total length of all packets (in bytes)\n");
990   fprintf(output, "  -l display the packet size limit (snapshot length)\n");
991   fprintf(output, "\n");
992   fprintf(output, "Time infos:\n");
993   fprintf(output, "  -u display the capture duration (in seconds)\n");
994   fprintf(output, "  -a display the capture start time\n");
995   fprintf(output, "  -e display the capture end time\n");
996   fprintf(output, "  -o display the capture file chronological status (True/False)\n");
997   fprintf(output, "  -S display start and end times as seconds\n");
998   fprintf(output, "\n");
999   fprintf(output, "Statistic infos:\n");
1000   fprintf(output, "  -y display average data rate (in bytes/sec)\n");
1001   fprintf(output, "  -i display average data rate (in bits/sec)\n");
1002   fprintf(output, "  -z display average packet size (in bytes)\n");
1003   fprintf(output, "  -x display average packet rate (in packets/sec)\n");
1004   fprintf(output, "\n");
1005   fprintf(output, "Output format:\n");
1006   fprintf(output, "  -L generate long report (default)\n");
1007   fprintf(output, "  -T generate table report\n");
1008   fprintf(output, "  -M display machine-readable values in long reports\n");
1009   fprintf(output, "\n");
1010   fprintf(output, "Table report options:\n");
1011   fprintf(output, "  -R generate header record (default)\n");
1012   fprintf(output, "  -r do not generate header record\n");
1013   fprintf(output, "\n");
1014   fprintf(output, "  -B separate infos with TAB character (default)\n");
1015   fprintf(output, "  -m separate infos with comma (,) character\n");
1016   fprintf(output, "  -b separate infos with SPACE character\n");
1017   fprintf(output, "\n");
1018   fprintf(output, "  -N do not quote infos (default)\n");
1019   fprintf(output, "  -q quote infos with single quotes (')\n");
1020   fprintf(output, "  -Q quote infos with double quotes (\")\n");
1021   fprintf(output, "\n");
1022   fprintf(output, "Miscellaneous:\n");
1023   fprintf(output, "  -h display this help and exit\n");
1024   fprintf(output, "  -C cancel processing if file open fails (default is to continue)\n");
1025   fprintf(output, "  -A generate all infos (default)\n");
1026   fprintf(output, "\n");
1027   fprintf(output, "Options are processed from left to right order with later options superceeding\n");
1028   fprintf(output, "or adding to earlier options.\n");
1029   fprintf(output, "\n");
1030   fprintf(output, "If no options are given the default is to display all infos in long report\n");
1031   fprintf(output, "output format.\n");
1032 #ifndef HAVE_LIBGCRYPT
1033   fprintf(output, "\nFile hashing support (-H) is not present.\n");
1034 #endif
1035 }
1036
1037 #ifdef HAVE_PLUGINS
1038 /*
1039  *  Don't report failures to load plugins because most (non-wiretap) plugins
1040  *  *should* fail to load (because we're not linked against libwireshark and
1041  *  dissector plugins need libwireshark).
1042  */
1043 static void
1044 failure_message(const char *msg_format _U_, va_list ap _U_)
1045 {
1046   return;
1047 }
1048 #endif
1049
1050 #ifdef HAVE_LIBGCRYPT
1051 static void
1052 hash_to_str(const unsigned char *hash, size_t length, char *str) {
1053   int i;
1054
1055   for (i = 0; i < (int) length; i++) {
1056     g_snprintf(str+(i*2), 3, "%02x", hash[i]);
1057   }
1058 }
1059 #endif /* HAVE_LIBGCRYPT */
1060
1061 int
1062 main(int argc, char *argv[])
1063 {
1064   wtap  *wth;
1065   int    err;
1066   gchar *err_info;
1067   int    opt;
1068   int    overall_error_status;
1069
1070   int status = 0;
1071 #ifdef HAVE_PLUGINS
1072   char  *init_progfile_dir_error;
1073 #endif
1074 #ifdef HAVE_LIBGCRYPT
1075   FILE  *fh;
1076   char  *hash_buf = NULL;
1077   gcry_md_hd_t hd = NULL;
1078   size_t hash_bytes;
1079 #endif
1080
1081 #ifdef _WIN32
1082   arg_list_utf_16to8(argc, argv);
1083   create_app_running_mutex();
1084 #endif /* _WIN32 */
1085
1086   /*
1087    * Get credential information for later use.
1088    */
1089   init_process_policies();
1090
1091 #ifdef HAVE_PLUGINS
1092   /* Register wiretap plugins */
1093
1094   if ((init_progfile_dir_error = init_progfile_dir(argv[0], main))) {
1095     g_warning("capinfos: init_progfile_dir(): %s", init_progfile_dir_error);
1096     g_free(init_progfile_dir_error);
1097   } else {
1098     init_report_err(failure_message,NULL,NULL,NULL);
1099     init_plugins();
1100   }
1101 #endif
1102
1103   /* Process the options */
1104 #ifdef USE_GOPTION
1105   ctx = g_option_context_new(" <infile> ... - print information about capture file(s)");
1106   general_grp = g_option_group_new("gen", "General infos:",
1107                                 "Show general options", NULL, NULL);
1108   size_grp = g_option_group_new("size", "Size infos:",
1109                                "Show size options", NULL, NULL);
1110   time_grp = g_option_group_new("time", "Time infos:",
1111                                "Show time options", NULL, NULL);
1112   stats_grp = g_option_group_new("stats", "Statistics infos:",
1113                                  "Show statistics options", NULL, NULL);
1114   output_grp = g_option_group_new("output", "Output format:",
1115                                  "Show output format options", NULL, NULL);
1116   table_report_grp = g_option_group_new("table", "Table report options:",
1117                                  "Show table report options", NULL, NULL);
1118   g_option_group_add_entries(general_grp, general_entries);
1119   g_option_group_add_entries(size_grp, size_entries);
1120   g_option_group_add_entries(time_grp, time_entries);
1121   g_option_group_add_entries(stats_grp, stats_entries);
1122   g_option_group_add_entries(output_grp, output_format_entries);
1123   g_option_group_add_entries(table_report_grp, table_report_entries);
1124   g_option_context_add_main_entries(ctx, misc_entries, NULL);
1125   g_option_context_add_group(ctx, general_grp);
1126   g_option_context_add_group(ctx, size_grp);
1127   g_option_context_add_group(ctx, time_grp);
1128   g_option_context_add_group(ctx, stats_grp);
1129   g_option_context_add_group(ctx, output_grp);
1130   g_option_context_add_group(ctx, table_report_grp);
1131   /* There's probably a better way to do this, but this works for now.
1132      GOptions displays the name in argv[0] as the name of the
1133      application.  This is reasonable, but because we actually have a
1134      script wrapper that calls the executable.  The name that gets
1135      displayed is not exactly the same as the command the user used
1136      ran.
1137    */
1138   argv[0] = "capinfos";
1139   ;
1140   if( !g_option_context_parse(ctx, &argc, &argv, &parse_err) ) {
1141     if(parse_err) g_print ("option parsing failed: %s\n", parse_err->message);
1142     g_print("%s", g_option_context_get_help (ctx, TRUE, NULL));
1143     exit(1);
1144   }
1145   if( cap_help || (argc < 2) ) {
1146     g_print("%s", g_option_context_get_help (ctx, FALSE, NULL));
1147     exit(0);
1148   }
1149   g_option_context_free(ctx);
1150
1151 #endif /* USE_GOPTION */
1152   while ((opt = getopt(argc, argv, "tEcs" FILE_HASH_OPT "dluaeyizvhxoCALTMRrSNqQBmb")) !=-1) {
1153
1154     switch (opt) {
1155
1156     case 't':
1157       if (report_all_infos) disable_all_infos();
1158       cap_file_type = TRUE;
1159       break;
1160
1161     case 'E':
1162       if (report_all_infos) disable_all_infos();
1163       cap_file_encap = TRUE;
1164       break;
1165
1166     case 'l':
1167       if (report_all_infos) disable_all_infos();
1168       cap_snaplen = TRUE;
1169       break;
1170
1171     case 'c':
1172       if (report_all_infos) disable_all_infos();
1173       cap_packet_count = TRUE;
1174       break;
1175
1176     case 's':
1177       if (report_all_infos) disable_all_infos();
1178       cap_file_size = TRUE;
1179       break;
1180
1181     case 'd':
1182       if (report_all_infos) disable_all_infos();
1183       cap_data_size = TRUE;
1184       break;
1185
1186     case 'u':
1187       if (report_all_infos) disable_all_infos();
1188       cap_duration = TRUE;
1189       break;
1190
1191     case 'a':
1192       if (report_all_infos) disable_all_infos();
1193       cap_start_time = TRUE;
1194       break;
1195
1196     case 'e':
1197       if (report_all_infos) disable_all_infos();
1198       cap_end_time = TRUE;
1199       break;
1200
1201     case 'S':
1202       time_as_secs = TRUE;
1203       break;
1204
1205     case 'y':
1206       if (report_all_infos) disable_all_infos();
1207       cap_data_rate_byte = TRUE;
1208       break;
1209
1210     case 'i':
1211       if (report_all_infos) disable_all_infos();
1212       cap_data_rate_bit = TRUE;
1213       break;
1214
1215     case 'z':
1216       if (report_all_infos) disable_all_infos();
1217       cap_packet_size = TRUE;
1218       break;
1219
1220     case 'x':
1221       if (report_all_infos) disable_all_infos();
1222       cap_packet_rate = TRUE;
1223       break;
1224
1225 #ifdef HAVE_LIBGCRYPT
1226     case 'H':
1227       if (report_all_infos) disable_all_infos();
1228       cap_file_hashes = TRUE;
1229       break;
1230 #endif
1231
1232     case 'o':
1233       if (report_all_infos) disable_all_infos();
1234       cap_order = TRUE;
1235       break;
1236
1237     case 'C':
1238       continue_after_wtap_open_offline_failure = FALSE;
1239       break;
1240
1241     case 'A':
1242       enable_all_infos();
1243       break;
1244
1245     case 'L':
1246       long_report = TRUE;
1247       break;
1248
1249     case 'T':
1250       long_report = FALSE;
1251       break;
1252
1253     case 'M':
1254       machine_readable = TRUE;
1255       break;
1256
1257     case 'R':
1258       table_report_header = TRUE;
1259       break;
1260
1261     case 'r':
1262       table_report_header = FALSE;
1263       break;
1264
1265     case 'N':
1266       quote_char = '\0';
1267       break;
1268
1269     case 'q':
1270       quote_char = '\'';
1271       break;
1272
1273     case 'Q':
1274       quote_char = '"';
1275       break;
1276
1277     case 'B':
1278       field_separator = '\t';
1279       break;
1280
1281     case 'm':
1282       field_separator = ',';
1283       break;
1284
1285     case 'b':
1286       field_separator = ' ';
1287       break;
1288
1289     case 'h':
1290       usage(FALSE);
1291       exit(1);
1292       break;
1293
1294     case '?':              /* Bad flag - print usage message */
1295       usage(TRUE);
1296       exit(1);
1297       break;
1298     }
1299   }
1300
1301   /* Set the C-language locale to the native environment. */
1302   setlocale(LC_ALL, "");
1303
1304   if ((argc - optind) < 1) {
1305     usage(TRUE);
1306     exit(1);
1307   }
1308
1309   if(!long_report && table_report_header) {
1310     print_stats_table_header();
1311   }
1312
1313 #ifdef HAVE_LIBGCRYPT
1314   if (cap_file_hashes) {
1315     gcry_check_version(NULL);
1316     gcry_md_open(&hd, GCRY_MD_SHA1, 0);
1317     if (hd) {
1318       gcry_md_enable(hd, GCRY_MD_RMD160);
1319       gcry_md_enable(hd, GCRY_MD_MD5);
1320     }
1321     hash_buf = (char *)g_malloc(HASH_BUF_SIZE);
1322   }
1323 #endif
1324
1325   overall_error_status = 0;
1326
1327   for (opt = optind; opt < argc; opt++) {
1328
1329 #ifdef HAVE_LIBGCRYPT
1330     g_strlcpy(file_sha1, "<unknown>", HASH_STR_SIZE);
1331     g_strlcpy(file_rmd160, "<unknown>", HASH_STR_SIZE);
1332     g_strlcpy(file_md5, "<unknown>", HASH_STR_SIZE);
1333
1334     if (cap_file_hashes) {
1335       fh = ws_fopen(argv[opt], "rb");
1336       if (fh && hd) {
1337         while((hash_bytes = fread(hash_buf, 1, HASH_BUF_SIZE, fh)) > 0) {
1338           gcry_md_write(hd, hash_buf, hash_bytes);
1339         }
1340         gcry_md_final(hd);
1341         hash_to_str(gcry_md_read(hd, GCRY_MD_SHA1), HASH_SIZE_SHA1, file_sha1);
1342         hash_to_str(gcry_md_read(hd, GCRY_MD_RMD160), HASH_SIZE_RMD160, file_rmd160);
1343         hash_to_str(gcry_md_read(hd, GCRY_MD_MD5), HASH_SIZE_MD5, file_md5);
1344       }
1345       if (fh) fclose(fh);
1346       if (hd) gcry_md_reset(hd);
1347     }
1348 #endif /* HAVE_LIBGCRYPT */
1349
1350     wth = wtap_open_offline(argv[opt], &err, &err_info, FALSE);
1351
1352     if (!wth) {
1353       fprintf(stderr, "capinfos: Can't open %s: %s\n", argv[opt],
1354         wtap_strerror(err));
1355       switch (err) {
1356
1357       case WTAP_ERR_UNSUPPORTED:
1358       case WTAP_ERR_UNSUPPORTED_ENCAP:
1359       case WTAP_ERR_BAD_FILE:
1360         fprintf(stderr, "(%s)\n", err_info);
1361         g_free(err_info);
1362         break;
1363       }
1364       overall_error_status = 1; /* remember that an error has occurred */
1365       if(!continue_after_wtap_open_offline_failure)
1366         exit(1); /* error status */
1367     }
1368
1369     if(wth) {
1370       if ((opt > optind) && (long_report))
1371         printf("\n");
1372       status = process_cap_file(wth, argv[opt]);
1373
1374       wtap_close(wth);
1375       if (status)
1376         exit(status);
1377     }
1378   }
1379
1380   return overall_error_status;
1381 }