[Automatic update for 2018-02-04]
[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  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * SPDX-License-Identifier: GPL-2.0+
11  */
12
13 /*
14  * 2009-09-19: jyoung
15  *
16  * New capinfos features
17  *
18  * Continue processing additional files after
19  * a wiretap open failure.  The new -C option
20  * reverts to capinfos' original behavior which
21  * is to cancel any further file processing at
22  * first file open failure.
23  *
24  * Change the behavior of how the default display
25  * of all infos is initiated.  This gets rid of a
26  * special post getopt() argument count test.
27  *
28  * Add new table output format (with related options)
29  * This feature allows outputting the various infos
30  * into a tab delimited text file, or to a comma
31  * separated variables file (*.csv) instead of the
32  * original "long" format.
33  *
34  * 2011-04-05: wmeier
35  * behaviour changed: Upon exit capinfos will return
36  *  an error status if an error occurred at any
37  *  point during "continuous" file processing.
38  *  (Previously a success status was always
39  *   returned if the -C option was not used).
40  *
41
42  */
43
44
45 #include <config.h>
46
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <stdarg.h>
51 #include <locale.h>
52 #include <errno.h>
53
54 #ifdef HAVE_GETOPT_H
55 #include <getopt.h>
56 #endif
57
58 #include <glib.h>
59
60 #include <wiretap/wtap.h>
61
62 #include <wsutil/cmdarg_err.h>
63 #include <wsutil/crash_info.h>
64 #include <wsutil/filesystem.h>
65 #include <wsutil/privileges.h>
66 #include <version_info.h>
67 #include <wiretap/wtap_opttypes.h>
68
69 #ifdef HAVE_PLUGINS
70 #include <wsutil/plugins.h>
71 #endif
72
73 #include <wsutil/report_message.h>
74 #include <wsutil/str_util.h>
75 #include <wsutil/file_util.h>
76
77 #include <wsutil/wsgcrypt.h>
78
79 #ifndef HAVE_GETOPT_LONG
80 #include "wsutil/wsgetopt.h"
81 #endif
82
83 #ifdef _WIN32
84 #include <wsutil/unicode-utils.h>
85 #endif /* _WIN32 */
86
87 #include "ui/failure_message.h"
88
89 #define INVALID_OPTION 1
90 #define BAD_FLAG 1
91
92 /*
93  * By default capinfos now continues processing
94  * the next filename if and when wiretap detects
95  * a problem opening a file.
96  * Use the '-C' option to revert back to original
97  * capinfos behavior which is to abort any
98  * additional file processing at first open file
99  * failure.
100  */
101
102 static gboolean continue_after_wtap_open_offline_failure = TRUE;
103
104 /*
105  * table report variables
106  */
107
108 static gboolean long_report        = TRUE;  /* By default generate long report       */
109 static gchar table_report_header   = TRUE;  /* Generate column header by default     */
110 static gchar field_separator       = '\t';  /* Use TAB as field separator by default */
111 static gchar quote_char            = '\0';  /* Do NOT quote fields by default        */
112 static gboolean machine_readable   = FALSE; /* Display machine-readable numbers      */
113
114 /*
115  * capinfos has the ability to report on a number of
116  * various characteristics ("infos") for each input file.
117  *
118  * By default reporting of all info fields is enabled.
119  *
120  * Optionally the reporting of any specific info field
121  * or combination of info fields can be enabled with
122  * individual options.
123  */
124
125 static gboolean report_all_infos   = TRUE;  /* Report all infos           */
126
127 static gboolean cap_file_type      = TRUE;  /* Report capture type        */
128 static gboolean cap_file_encap     = TRUE;  /* Report encapsulation       */
129 static gboolean cap_snaplen        = TRUE;  /* Packet size limit (snaplen)*/
130 static gboolean cap_packet_count   = TRUE;  /* Report packet count        */
131 static gboolean cap_file_size      = TRUE;  /* Report file size           */
132 static gboolean cap_comment        = TRUE;  /* Display the capture comment */
133 static gboolean cap_file_more_info = TRUE;  /* Report more file info      */
134 static gboolean cap_file_idb       = TRUE;  /* Report Interface info      */
135
136 static gboolean cap_data_size      = TRUE;  /* Report packet byte size    */
137 static gboolean cap_duration       = TRUE;  /* Report capture duration    */
138 static gboolean cap_start_time     = TRUE;  /* Report capture start time  */
139 static gboolean cap_end_time       = TRUE;  /* Report capture end time    */
140 static gboolean time_as_secs       = FALSE; /* Report time values as raw seconds */
141
142 static gboolean cap_data_rate_byte = TRUE;  /* Report data rate bytes/sec */
143 static gboolean cap_data_rate_bit  = TRUE;  /* Report data rate bites/sec */
144 static gboolean cap_packet_size    = TRUE;  /* Report average packet size */
145 static gboolean cap_packet_rate    = TRUE;  /* Report average packet rate */
146 static gboolean cap_order          = TRUE;  /* Report if packets are in chronological order (True/False) */
147
148 static gboolean cap_file_hashes    = TRUE;  /* Calculate file hashes */
149
150 // Strongest to weakest
151 #define HASH_SIZE_SHA256 32
152 #define HASH_SIZE_RMD160 20
153 #define HASH_SIZE_SHA1   20
154
155 #define HASH_STR_SIZE (65) /* Max hash size * 2 + '\0' */
156 #define HASH_BUF_SIZE (1024 * 1024)
157
158
159 static gchar file_sha256[HASH_STR_SIZE];
160 static gchar file_rmd160[HASH_STR_SIZE];
161 static gchar file_sha1[HASH_STR_SIZE];
162
163 /*
164  * If we have at least two packets with time stamps, and they're not in
165  * order - i.e., the later packet has a time stamp older than the earlier
166  * packet - the time stamps are known not to be in order.
167  *
168  * If every packet has a time stamp, and they're all in order, the time
169  * stamp is known to be in order.
170  *
171  * Otherwise, we have no idea.
172  */
173 typedef enum {
174   IN_ORDER,
175   NOT_IN_ORDER,
176   ORDER_UNKNOWN
177 } order_t;
178
179 typedef struct _capture_info {
180   const char    *filename;
181   guint16        file_type;
182   gboolean       iscompressed;
183   int            file_encap;
184   int            file_tsprec;
185   gint64         filesize;
186   wtap_block_t   shb;
187   guint64        packet_bytes;
188   gboolean       times_known;
189   nstime_t       start_time;
190   int            start_time_tsprec;
191   nstime_t       stop_time;
192   int            stop_time_tsprec;
193   guint32        packet_count;
194   gboolean       snap_set;                /* If set in capture file header      */
195   guint32        snaplen;                 /* value from the capture file header */
196   guint32        snaplen_min_inferred;    /* If caplen < len for 1 or more rcds */
197   guint32        snaplen_max_inferred;    /*  ...                               */
198   gboolean       drops_known;
199   guint32        drop_count;
200
201   nstime_t       duration;
202   int            duration_tsprec;
203   double         packet_rate;
204   double         packet_size;
205   double         data_rate;              /* in bytes */
206   gboolean       know_order;
207   order_t        order;
208
209   int           *encap_counts;           /* array of per_packet encap counts; array has one entry per wtap_encap type */
210
211   guint          num_interfaces;         /* number of IDBs, and thus size of interface_packet_counts array */
212   GArray        *interface_packet_counts;  /* array of per_packet interface_id counts; one entry per file IDB */
213   guint32        pkt_interface_id_unknown; /* counts if packet interface_id didn't match a known one */
214   GArray        *idb_info_strings;       /* array of IDB info strings */
215 } capture_info;
216
217 static char *decimal_point;
218
219 static void
220 enable_all_infos(void)
221 {
222   report_all_infos   = TRUE;
223
224   cap_file_type      = TRUE;
225   cap_file_encap     = TRUE;
226   cap_snaplen        = TRUE;
227   cap_packet_count   = TRUE;
228   cap_file_size      = TRUE;
229   cap_comment        = TRUE;
230   cap_file_more_info = TRUE;
231   cap_file_idb       = TRUE;
232
233   cap_data_size      = TRUE;
234   cap_duration       = TRUE;
235   cap_start_time     = TRUE;
236   cap_end_time       = TRUE;
237   cap_order          = TRUE;
238
239   cap_data_rate_byte = TRUE;
240   cap_data_rate_bit  = TRUE;
241   cap_packet_size    = TRUE;
242   cap_packet_rate    = TRUE;
243
244   cap_file_hashes    = TRUE;
245 }
246
247 static void
248 disable_all_infos(void)
249 {
250   report_all_infos   = FALSE;
251
252   cap_file_type      = FALSE;
253   cap_file_encap     = FALSE;
254   cap_snaplen        = FALSE;
255   cap_packet_count   = FALSE;
256   cap_file_size      = FALSE;
257   cap_comment        = FALSE;
258   cap_file_more_info = FALSE;
259   cap_file_idb       = FALSE;
260
261   cap_data_size      = FALSE;
262   cap_duration       = FALSE;
263   cap_start_time     = FALSE;
264   cap_end_time       = FALSE;
265   cap_order          = FALSE;
266
267   cap_data_rate_byte = FALSE;
268   cap_data_rate_bit  = FALSE;
269   cap_packet_size    = FALSE;
270   cap_packet_rate    = FALSE;
271
272   cap_file_hashes    = FALSE;
273 }
274
275 static const gchar *
276 order_string(order_t order)
277 {
278   switch (order) {
279
280     case IN_ORDER:
281       return "True";
282
283     case NOT_IN_ORDER:
284       return "False";
285
286     case ORDER_UNKNOWN:
287       return "Unknown";
288
289     default:
290       return "???";  /* "cannot happen" (the next step is "Profit!") */
291   }
292 }
293
294 static gchar *
295 absolute_time_string(nstime_t *timer, int tsprecision, capture_info *cf_info)
296 {
297   static gchar  time_string_buf[4+1+2+1+2+1+2+1+2+1+2+1+9+1+1];
298   struct tm *ti_tm;
299
300   if (cf_info->times_known && cf_info->packet_count > 0) {
301     if (time_as_secs) {
302       switch (tsprecision) {
303
304       case WTAP_TSPREC_SEC:
305         g_snprintf(time_string_buf, sizeof time_string_buf,
306                    "%lu",
307                    (unsigned long)timer->secs);
308         break;
309
310       case WTAP_TSPREC_DSEC:
311         g_snprintf(time_string_buf, sizeof time_string_buf,
312                    "%lu%s%01d",
313                    (unsigned long)timer->secs,
314                    decimal_point,
315                    timer->nsecs / 100000000);
316         break;
317
318       case WTAP_TSPREC_CSEC:
319         g_snprintf(time_string_buf, sizeof time_string_buf,
320                    "%lu%s%02d",
321                    (unsigned long)timer->secs,
322                    decimal_point,
323                    timer->nsecs / 10000000);
324         break;
325
326       case WTAP_TSPREC_MSEC:
327         g_snprintf(time_string_buf, sizeof time_string_buf,
328                    "%lu%s%03d",
329                    (unsigned long)timer->secs,
330                    decimal_point,
331                    timer->nsecs / 1000000);
332         break;
333
334       case WTAP_TSPREC_USEC:
335         g_snprintf(time_string_buf, sizeof time_string_buf,
336                    "%lu%s%06d",
337                    (unsigned long)timer->secs,
338                    decimal_point,
339                    timer->nsecs / 1000);
340         break;
341
342       case WTAP_TSPREC_NSEC:
343         g_snprintf(time_string_buf, sizeof time_string_buf,
344                    "%lu%s%09d",
345                    (unsigned long)timer->secs,
346                    decimal_point,
347                    timer->nsecs);
348         break;
349
350       default:
351         g_snprintf(time_string_buf, sizeof time_string_buf,
352                    "Unknown precision %d",
353                    tsprecision);
354         break;
355       }
356       return time_string_buf;
357     } else {
358       ti_tm = localtime(&timer->secs);
359       if (ti_tm == NULL) {
360         g_snprintf(time_string_buf, sizeof time_string_buf, "Not representable");
361         return time_string_buf;
362       }
363       switch (tsprecision) {
364
365       case WTAP_TSPREC_SEC:
366         g_snprintf(time_string_buf, sizeof time_string_buf,
367                    "%04d-%02d-%02d %02d:%02d:%02d",
368                    ti_tm->tm_year + 1900,
369                    ti_tm->tm_mon + 1,
370                    ti_tm->tm_mday,
371                    ti_tm->tm_hour,
372                    ti_tm->tm_min,
373                    ti_tm->tm_sec);
374         break;
375
376       case WTAP_TSPREC_DSEC:
377         g_snprintf(time_string_buf, sizeof time_string_buf,
378                    "%04d-%02d-%02d %02d:%02d:%02d%s%01d",
379                    ti_tm->tm_year + 1900,
380                    ti_tm->tm_mon + 1,
381                    ti_tm->tm_mday,
382                    ti_tm->tm_hour,
383                    ti_tm->tm_min,
384                    ti_tm->tm_sec,
385                    decimal_point,
386                    timer->nsecs / 100000000);
387         break;
388
389       case WTAP_TSPREC_CSEC:
390         g_snprintf(time_string_buf, sizeof time_string_buf,
391                    "%04d-%02d-%02d %02d:%02d:%02d%s%02d",
392                    ti_tm->tm_year + 1900,
393                    ti_tm->tm_mon + 1,
394                    ti_tm->tm_mday,
395                    ti_tm->tm_hour,
396                    ti_tm->tm_min,
397                    ti_tm->tm_sec,
398                    decimal_point,
399                    timer->nsecs / 10000000);
400         break;
401
402       case WTAP_TSPREC_MSEC:
403         g_snprintf(time_string_buf, sizeof time_string_buf,
404                    "%04d-%02d-%02d %02d:%02d:%02d%s%03d",
405                    ti_tm->tm_year + 1900,
406                    ti_tm->tm_mon + 1,
407                    ti_tm->tm_mday,
408                    ti_tm->tm_hour,
409                    ti_tm->tm_min,
410                    ti_tm->tm_sec,
411                    decimal_point,
412                    timer->nsecs / 1000000);
413         break;
414
415       case WTAP_TSPREC_USEC:
416         g_snprintf(time_string_buf, sizeof time_string_buf,
417                    "%04d-%02d-%02d %02d:%02d:%02d%s%06d",
418                    ti_tm->tm_year + 1900,
419                    ti_tm->tm_mon + 1,
420                    ti_tm->tm_mday,
421                    ti_tm->tm_hour,
422                    ti_tm->tm_min,
423                    ti_tm->tm_sec,
424                    decimal_point,
425                    timer->nsecs / 1000);
426         break;
427
428       case WTAP_TSPREC_NSEC:
429         g_snprintf(time_string_buf, sizeof time_string_buf,
430                    "%04d-%02d-%02d %02d:%02d:%02d%s%09d",
431                    ti_tm->tm_year + 1900,
432                    ti_tm->tm_mon + 1,
433                    ti_tm->tm_mday,
434                    ti_tm->tm_hour,
435                    ti_tm->tm_min,
436                    ti_tm->tm_sec,
437                    decimal_point,
438                    timer->nsecs);
439         break;
440
441       default:
442         g_snprintf(time_string_buf, sizeof time_string_buf,
443                    "Unknown precision %d",
444                    tsprecision);
445         break;
446       }
447       return time_string_buf;
448     }
449   }
450
451   g_snprintf(time_string_buf, sizeof time_string_buf, "n/a");
452   return time_string_buf;
453 }
454
455 static gchar *
456 relative_time_string(nstime_t *timer, int tsprecision, capture_info *cf_info, gboolean want_seconds)
457 {
458   const gchar  *second = want_seconds ? " second" : "";
459   const gchar  *plural = want_seconds ? "s" : "";
460   static gchar  time_string_buf[4+1+2+1+2+1+2+1+2+1+2+1+1];
461
462   if (cf_info->times_known && cf_info->packet_count > 0) {
463     switch (tsprecision) {
464
465     case WTAP_TSPREC_SEC:
466       g_snprintf(time_string_buf, sizeof time_string_buf,
467                  "%lu%s%s",
468                  (unsigned long)timer->secs,
469                  second,
470                  timer->secs == 1 ? "" : plural);
471       break;
472
473     case WTAP_TSPREC_DSEC:
474       g_snprintf(time_string_buf, sizeof time_string_buf,
475                  "%lu%s%01d%s%s",
476                  (unsigned long)timer->secs,
477                  decimal_point,
478                  timer->nsecs / 100000000,
479                  second,
480                  (timer->secs == 1 && timer->nsecs == 0) ? "" : plural);
481       break;
482
483     case WTAP_TSPREC_CSEC:
484       g_snprintf(time_string_buf, sizeof time_string_buf,
485                  "%lu%s%02d%s%s",
486                  (unsigned long)timer->secs,
487                  decimal_point,
488                  timer->nsecs / 10000000,
489                  second,
490                  (timer->secs == 1 && timer->nsecs == 0) ? "" : plural);
491       break;
492
493     case WTAP_TSPREC_MSEC:
494       g_snprintf(time_string_buf, sizeof time_string_buf,
495                  "%lu%s%03d%s%s",
496                  (unsigned long)timer->secs,
497                  decimal_point,
498                  timer->nsecs / 1000000,
499                  second,
500                  (timer->secs == 1 && timer->nsecs == 0) ? "" : plural);
501       break;
502
503     case WTAP_TSPREC_USEC:
504       g_snprintf(time_string_buf, sizeof time_string_buf,
505                  "%lu%s%06d%s%s",
506                  (unsigned long)timer->secs,
507                  decimal_point,
508                  timer->nsecs / 1000,
509                  second,
510                  (timer->secs == 1 && timer->nsecs == 0) ? "" : plural);
511       break;
512
513     case WTAP_TSPREC_NSEC:
514       g_snprintf(time_string_buf, sizeof time_string_buf,
515                  "%lu%s%09d%s%s",
516                  (unsigned long)timer->secs,
517                  decimal_point,
518                  timer->nsecs,
519                  second,
520                  (timer->secs == 1 && timer->nsecs == 0) ? "" : plural);
521       break;
522
523     default:
524       g_snprintf(time_string_buf, sizeof time_string_buf,
525                  "Unknown precision %d",
526                  tsprecision);
527       break;
528     }
529     return time_string_buf;
530   }
531
532   g_snprintf(time_string_buf, sizeof time_string_buf, "n/a");
533   return time_string_buf;
534 }
535
536 static void print_value(const gchar *text_p1, gint width, const gchar *text_p2, double value) {
537   if (value > 0.0)
538     printf("%s%.*f%s\n", text_p1, width, value, text_p2);
539   else
540     printf("%sn/a\n", text_p1);
541 }
542
543 /* multi-line comments would conflict with the formatting that capinfos uses
544    we replace linefeeds with spaces */
545 static void
546 string_replace_newlines(gchar *str)
547 {
548   gchar *p;
549
550   if (str) {
551     p = str;
552     while (*p != '\0') {
553       if (*p == '\n')
554         *p = ' ';
555       if (*p == '\r')
556         *p = ' ';
557       p++;
558     }
559   }
560 }
561
562 static void
563 show_option_string(const char *prefix, const char *option_str)
564 {
565   char *str;
566
567   if (option_str != NULL && option_str[0] != '\0') {
568     str = g_strdup(option_str);
569     string_replace_newlines(str);
570     printf("%s%s\n", prefix, str);
571     g_free(str);
572   }
573 }
574
575 static void
576 print_stats(const gchar *filename, capture_info *cf_info)
577 {
578   const gchar           *file_type_string, *file_encap_string;
579   gchar                 *size_string;
580
581   /* Build printable strings for various stats */
582   file_type_string = wtap_file_type_subtype_string(cf_info->file_type);
583   file_encap_string = wtap_encap_string(cf_info->file_encap);
584
585   if (filename)           printf     ("File name:           %s\n", filename);
586   if (cap_file_type)      printf     ("File type:           %s%s\n",
587       file_type_string,
588       cf_info->iscompressed ? " (gzip compressed)" : "");
589
590   if (cap_file_encap) {
591     printf      ("File encapsulation:  %s\n", file_encap_string);
592     if (cf_info->file_encap == WTAP_ENCAP_PER_PACKET) {
593       int i;
594       printf    ("Encapsulation in use by packets (# of pkts):\n");
595       for (i=0; i<WTAP_NUM_ENCAP_TYPES; i++) {
596         if (cf_info->encap_counts[i] > 0)
597           printf("                     %s (%d)\n",
598                  wtap_encap_string(i), cf_info->encap_counts[i]);
599       }
600     }
601   }
602   if (cap_file_more_info) {
603     printf      ("File timestamp precision:  %s (%d)\n",
604       wtap_tsprec_string(cf_info->file_tsprec), cf_info->file_tsprec);
605   }
606
607   if (cap_snaplen && cf_info->snap_set)
608     printf     ("Packet size limit:   file hdr: %u bytes\n", cf_info->snaplen);
609   else if (cap_snaplen && !cf_info->snap_set)
610     printf     ("Packet size limit:   file hdr: (not set)\n");
611   if (cf_info->snaplen_max_inferred > 0) {
612     if (cf_info->snaplen_min_inferred == cf_info->snaplen_max_inferred)
613       printf     ("Packet size limit:   inferred: %u bytes\n", cf_info->snaplen_min_inferred);
614     else
615       printf     ("Packet size limit:   inferred: %u bytes - %u bytes (range)\n",
616           cf_info->snaplen_min_inferred, cf_info->snaplen_max_inferred);
617   }
618   if (cap_packet_count) {
619     printf     ("Number of packets:   ");
620     if (machine_readable) {
621       printf ("%u\n", cf_info->packet_count);
622     } else {
623       size_string = format_size(cf_info->packet_count, format_size_unit_none);
624       printf ("%s\n", size_string);
625       g_free(size_string);
626     }
627   }
628   if (cap_file_size) {
629     printf     ("File size:           ");
630     if (machine_readable) {
631       printf     ("%" G_GINT64_MODIFIER "d bytes\n", cf_info->filesize);
632     } else {
633       size_string = format_size(cf_info->filesize, format_size_unit_bytes);
634       printf ("%s\n", size_string);
635       g_free(size_string);
636     }
637   }
638   if (cap_data_size) {
639     printf     ("Data size:           ");
640     if (machine_readable) {
641       printf     ("%" G_GINT64_MODIFIER "u bytes\n", cf_info->packet_bytes);
642     } else {
643       size_string = format_size(cf_info->packet_bytes, format_size_unit_bytes);
644       printf ("%s\n", size_string);
645       g_free(size_string);
646     }
647   }
648   if (cf_info->times_known) {
649     if (cap_duration) /* XXX - shorten to hh:mm:ss */
650                           printf("Capture duration:    %s\n", relative_time_string(&cf_info->duration, cf_info->duration_tsprec, cf_info, TRUE));
651     if (cap_start_time)
652                           printf("First packet time:   %s\n", absolute_time_string(&cf_info->start_time, cf_info->start_time_tsprec, cf_info));
653     if (cap_end_time)
654                           printf("Last packet time:    %s\n", absolute_time_string(&cf_info->stop_time, cf_info->stop_time_tsprec, cf_info));
655     if (cap_data_rate_byte) {
656                           printf("Data byte rate:      ");
657       if (machine_readable) {
658         print_value("", 2, " bytes/sec",   cf_info->data_rate);
659       } else {
660         size_string = format_size((gint64)cf_info->data_rate, format_size_unit_bytes_s);
661         printf ("%s\n", size_string);
662         g_free(size_string);
663       }
664     }
665     if (cap_data_rate_bit) {
666                           printf("Data bit rate:       ");
667       if (machine_readable) {
668         print_value("", 2, " bits/sec",    cf_info->data_rate*8);
669       } else {
670         size_string = format_size((gint64)(cf_info->data_rate*8), format_size_unit_bits_s);
671         printf ("%s\n", size_string);
672         g_free(size_string);
673       }
674     }
675   }
676   if (cap_packet_size)    printf("Average packet size: %.2f bytes\n",        cf_info->packet_size);
677   if (cf_info->times_known) {
678     if (cap_packet_rate) {
679                           printf("Average packet rate: ");
680       if (machine_readable) {
681         print_value("", 2, " packets/sec", cf_info->packet_rate);
682       } else {
683         size_string = format_size((gint64)cf_info->packet_rate, format_size_unit_packets_s);
684         printf ("%s\n", size_string);
685         g_free(size_string);
686       }
687     }
688   }
689   if (cap_file_hashes) {
690     printf     ("SHA256:              %s\n", file_sha256);
691     printf     ("RIPEMD160:           %s\n", file_rmd160);
692     printf     ("SHA1:                %s\n", file_sha1);
693   }
694   if (cap_order)          printf     ("Strict time order:   %s\n", order_string(cf_info->order));
695
696   if (cf_info->shb != NULL) {
697     if (cap_file_more_info) {
698       char *str;
699
700       if (wtap_block_get_string_option_value(cf_info->shb, OPT_SHB_HARDWARE, &str) == WTAP_OPTTYPE_SUCCESS)
701         show_option_string("Capture hardware:    ", str);
702       if (wtap_block_get_string_option_value(cf_info->shb, OPT_SHB_OS, &str) == WTAP_OPTTYPE_SUCCESS)
703         show_option_string("Capture oper-sys:    ", str);
704       if (wtap_block_get_string_option_value(cf_info->shb, OPT_SHB_USERAPPL, &str) == WTAP_OPTTYPE_SUCCESS)
705         show_option_string("Capture application: ", str);
706     }
707     if (cap_comment) {
708       unsigned int i;
709       char *str;
710
711       for (i = 0; wtap_block_get_nth_string_option_value(cf_info->shb, OPT_COMMENT, i, &str) == WTAP_OPTTYPE_SUCCESS; i++) {
712         show_option_string("Capture comment:     ", str);
713       }
714     }
715
716     if (cap_file_idb && cf_info->num_interfaces != 0) {
717       guint i;
718       g_assert(cf_info->num_interfaces == cf_info->idb_info_strings->len);
719       printf     ("Number of interfaces in file: %u\n", cf_info->num_interfaces);
720       for (i = 0; i < cf_info->idb_info_strings->len; i++) {
721         gchar *s = g_array_index(cf_info->idb_info_strings, gchar*, i);
722         guint32 packet_count = 0;
723         if (i < cf_info->interface_packet_counts->len)
724           packet_count = g_array_index(cf_info->interface_packet_counts, guint32, i);
725         printf   ("Interface #%u info:\n", i);
726         printf   ("%s", s);
727         printf   ("                     Number of packets = %u\n", packet_count);
728       }
729     }
730   }
731 }
732
733 static void
734 putsep(void)
735 {
736   if (field_separator) putchar(field_separator);
737 }
738
739 static void
740 putquote(void)
741 {
742   if (quote_char) putchar(quote_char);
743 }
744
745 static void
746 print_stats_table_header_label(const gchar *label)
747 {
748   putsep();
749   putquote();
750   printf("%s", label);
751   putquote();
752 }
753
754 static void
755 print_stats_table_header(void)
756 {
757   putquote();
758   printf("File name");
759   putquote();
760
761   if (cap_file_type)      print_stats_table_header_label("File type");
762   if (cap_file_encap)     print_stats_table_header_label("File encapsulation");
763   if (cap_file_more_info) print_stats_table_header_label("File time precision");
764   if (cap_snaplen)        print_stats_table_header_label("Packet size limit");
765   if (cap_snaplen)        print_stats_table_header_label("Packet size limit min (inferred)");
766   if (cap_snaplen)        print_stats_table_header_label("Packet size limit max (inferred)");
767   if (cap_packet_count)   print_stats_table_header_label("Number of packets");
768   if (cap_file_size)      print_stats_table_header_label("File size (bytes)");
769   if (cap_data_size)      print_stats_table_header_label("Data size (bytes)");
770   if (cap_duration)       print_stats_table_header_label("Capture duration (seconds)");
771   if (cap_start_time)     print_stats_table_header_label("Start time");
772   if (cap_end_time)       print_stats_table_header_label("End time");
773   if (cap_data_rate_byte) print_stats_table_header_label("Data byte rate (bytes/sec)");
774   if (cap_data_rate_bit)  print_stats_table_header_label("Data bit rate (bits/sec)");
775   if (cap_packet_size)    print_stats_table_header_label("Average packet size (bytes)");
776   if (cap_packet_rate)    print_stats_table_header_label("Average packet rate (packets/sec)");
777   if (cap_file_hashes) {
778     print_stats_table_header_label("SHA256");
779     print_stats_table_header_label("RIPEMD160");
780     print_stats_table_header_label("SHA1");
781   }
782   if (cap_order)          print_stats_table_header_label("Strict time order");
783   if (cap_file_more_info) {
784     print_stats_table_header_label("Capture hardware");
785     print_stats_table_header_label("Capture oper-sys");
786     print_stats_table_header_label("Capture application");
787   }
788   if (cap_comment)        print_stats_table_header_label("Capture comment");
789
790   printf("\n");
791 }
792
793 static void
794 print_stats_table(const gchar *filename, capture_info *cf_info)
795 {
796   const gchar           *file_type_string, *file_encap_string;
797
798   /* Build printable strings for various stats */
799   file_type_string = wtap_file_type_subtype_string(cf_info->file_type);
800   file_encap_string = wtap_encap_string(cf_info->file_encap);
801
802   if (filename) {
803     putquote();
804     printf("%s", filename);
805     putquote();
806   }
807
808   if (cap_file_type) {
809     putsep();
810     putquote();
811     printf("%s", file_type_string);
812     putquote();
813   }
814
815   /* ToDo: If WTAP_ENCAP_PER_PACKET, show the list of encapsulations encountered;
816    *       Output a line for each different encap with all fields repeated except
817    *        the encapsulation field which has "Per Packet: ..." for each
818    *        encapsulation type seen ?
819    */
820   if (cap_file_encap) {
821     putsep();
822     putquote();
823     printf("%s", file_encap_string);
824     putquote();
825   }
826
827   if (cap_file_more_info) {
828     putsep();
829     putquote();
830     printf("%s", wtap_tsprec_string(cf_info->file_tsprec));
831     putquote();
832   }
833
834   if (cap_snaplen) {
835     putsep();
836     putquote();
837     if (cf_info->snap_set)
838       printf("%u", cf_info->snaplen);
839     else
840       printf("(not set)");
841     putquote();
842     if (cf_info->snaplen_max_inferred > 0) {
843       putsep();
844       putquote();
845       printf("%u", cf_info->snaplen_min_inferred);
846       putquote();
847       putsep();
848       putquote();
849       printf("%u", cf_info->snaplen_max_inferred);
850       putquote();
851     }
852     else {
853       putsep();
854       putquote();
855       printf("n/a");
856       putquote();
857       putsep();
858       putquote();
859       printf("n/a");
860       putquote();
861     }
862   }
863
864   if (cap_packet_count) {
865     putsep();
866     putquote();
867     printf("%u", cf_info->packet_count);
868     putquote();
869   }
870
871   if (cap_file_size) {
872     putsep();
873     putquote();
874     printf("%" G_GINT64_MODIFIER "d", cf_info->filesize);
875     putquote();
876   }
877
878   if (cap_data_size) {
879     putsep();
880     putquote();
881     printf("%" G_GINT64_MODIFIER "u", cf_info->packet_bytes);
882     putquote();
883   }
884
885   if (cap_duration) {
886     putsep();
887     putquote();
888     printf("%s", relative_time_string(&cf_info->duration, cf_info->duration_tsprec, cf_info, FALSE));
889     putquote();
890   }
891
892   if (cap_start_time) {
893     putsep();
894     putquote();
895     printf("%s", absolute_time_string(&cf_info->start_time, cf_info->start_time_tsprec, cf_info));
896     putquote();
897   }
898
899   if (cap_end_time) {
900     putsep();
901     putquote();
902     printf("%s", absolute_time_string(&cf_info->stop_time, cf_info->stop_time_tsprec, cf_info));
903     putquote();
904   }
905
906   if (cap_data_rate_byte) {
907     putsep();
908     putquote();
909     if (cf_info->times_known)
910       printf("%.2f", cf_info->data_rate);
911     else
912       printf("n/a");
913     putquote();
914   }
915
916   if (cap_data_rate_bit) {
917     putsep();
918     putquote();
919     if (cf_info->times_known)
920       printf("%.2f", cf_info->data_rate*8);
921     else
922       printf("n/a");
923     putquote();
924   }
925
926   if (cap_packet_size) {
927     putsep();
928     putquote();
929     printf("%.2f", cf_info->packet_size);
930     putquote();
931   }
932
933   if (cap_packet_rate) {
934     putsep();
935     putquote();
936     if (cf_info->times_known)
937       printf("%.2f", cf_info->packet_rate);
938     else
939       printf("n/a");
940     putquote();
941   }
942
943   if (cap_file_hashes) {
944     putsep();
945     putquote();
946     printf("%s", file_sha256);
947     putquote();
948
949     putsep();
950     putquote();
951     printf("%s", file_rmd160);
952     putquote();
953
954     putsep();
955     putquote();
956     printf("%s", file_sha1);
957     putquote();
958   }
959
960   if (cap_order) {
961     putsep();
962     putquote();
963     printf("%s", order_string(cf_info->order));
964     putquote();
965   }
966
967   if (cf_info->shb != NULL) {
968     if (cap_file_more_info) {
969       char *str;
970
971       putsep();
972       putquote();
973       if (wtap_block_get_string_option_value(cf_info->shb, OPT_SHB_HARDWARE, &str) == WTAP_OPTTYPE_SUCCESS) {
974         printf("%s", str);
975       }
976       putquote();
977
978       putsep();
979       putquote();
980       if (wtap_block_get_string_option_value(cf_info->shb, OPT_SHB_OS, &str) == WTAP_OPTTYPE_SUCCESS) {
981         printf("%s", str);
982       }
983       putquote();
984
985       putsep();
986       putquote();
987       if (wtap_block_get_string_option_value(cf_info->shb, OPT_SHB_USERAPPL, &str) == WTAP_OPTTYPE_SUCCESS) {
988         printf("%s", str);
989       }
990       putquote();
991     }
992
993     /*
994      * One might argue that the following is silly to put into a table format,
995      * but oh well note that there may be *more than one* of each of these types
996      * of options.  To mitigate some of the potential silliness the if(cap_comment)
997      * block is moved AFTER the if(cap_file_more_info) block.  This will make any
998      * comments the last item(s) in each row.  We now have a new -K option to
999      * disable cap_comment to more easily manage the potential silliness.
1000      * Potential silliness includes multiple comments (therefore resulting in
1001      * more than one additional column and/or comments with embeded newlines
1002      * and/or possible delimiters).
1003      */
1004     if (cap_comment) {
1005       unsigned int i;
1006       char *opt_comment;
1007       gboolean have_cap = FALSE;
1008
1009       for (i = 0; wtap_block_get_nth_string_option_value(cf_info->shb, OPT_COMMENT, i, &opt_comment) == WTAP_OPTTYPE_SUCCESS; i++) {
1010         have_cap = TRUE;
1011         putsep();
1012         putquote();
1013         printf("%s", opt_comment);
1014         putquote();
1015       }
1016       if(!have_cap) {
1017         /* Maintain column alignment when we have no OPT_COMMENT */
1018         putsep();
1019         putquote();
1020         putquote();
1021       }
1022     }
1023
1024   }
1025
1026   printf("\n");
1027 }
1028
1029 static void
1030 cleanup_capture_info(capture_info *cf_info)
1031 {
1032   guint i;
1033   g_assert(cf_info != NULL);
1034
1035   g_free(cf_info->encap_counts);
1036   cf_info->encap_counts = NULL;
1037
1038   g_array_free(cf_info->interface_packet_counts, TRUE);
1039   cf_info->interface_packet_counts = NULL;
1040
1041   if (cf_info->idb_info_strings) {
1042     for (i = 0; i < cf_info->idb_info_strings->len; i++) {
1043       gchar *s = g_array_index(cf_info->idb_info_strings, gchar*, i);
1044       g_free(s);
1045     }
1046     g_array_free(cf_info->idb_info_strings, TRUE);
1047   }
1048   cf_info->idb_info_strings = NULL;
1049 }
1050
1051 static int
1052 process_cap_file(wtap *wth, const char *filename)
1053 {
1054   int                   status = 0;
1055   int                   err;
1056   gchar                *err_info;
1057   gint64                size;
1058   gint64                data_offset;
1059
1060   guint32               packet = 0;
1061   gint64                bytes  = 0;
1062   guint32               snaplen_min_inferred = 0xffffffff;
1063   guint32               snaplen_max_inferred =          0;
1064   const struct wtap_pkthdr *phdr;
1065   capture_info          cf_info;
1066   gboolean              have_times = TRUE;
1067   nstime_t              start_time;
1068   int                   start_time_tsprec;
1069   nstime_t              stop_time;
1070   int                   stop_time_tsprec;
1071   nstime_t              cur_time;
1072   nstime_t              prev_time;
1073   gboolean              know_order = FALSE;
1074   order_t               order = IN_ORDER;
1075   guint                 i;
1076   wtapng_iface_descriptions_t *idb_info;
1077
1078   g_assert(wth != NULL);
1079   g_assert(filename != NULL);
1080
1081   nstime_set_zero(&start_time);
1082   start_time_tsprec = WTAP_TSPREC_UNKNOWN;
1083   nstime_set_zero(&stop_time);
1084   stop_time_tsprec = WTAP_TSPREC_UNKNOWN;
1085   nstime_set_zero(&cur_time);
1086   nstime_set_zero(&prev_time);
1087
1088   cf_info.shb = wtap_file_get_shb(wth);
1089
1090   cf_info.encap_counts = g_new0(int,WTAP_NUM_ENCAP_TYPES);
1091
1092   idb_info = wtap_file_get_idb_info(wth);
1093
1094   g_assert(idb_info->interface_data != NULL);
1095
1096   cf_info.num_interfaces = idb_info->interface_data->len;
1097   cf_info.interface_packet_counts  = g_array_sized_new(FALSE, TRUE, sizeof(guint32), cf_info.num_interfaces);
1098   g_array_set_size(cf_info.interface_packet_counts, cf_info.num_interfaces);
1099   cf_info.pkt_interface_id_unknown = 0;
1100
1101   g_free(idb_info);
1102   idb_info = NULL;
1103
1104   /* Tally up data that we need to parse through the file to find */
1105   while (wtap_read(wth, &err, &err_info, &data_offset))  {
1106     phdr = wtap_phdr(wth);
1107     if (phdr->presence_flags & WTAP_HAS_TS) {
1108       prev_time = cur_time;
1109       cur_time = phdr->ts;
1110       if (packet == 0) {
1111         start_time = phdr->ts;
1112         start_time_tsprec = phdr->pkt_tsprec;
1113         stop_time  = phdr->ts;
1114         stop_time_tsprec = phdr->pkt_tsprec;
1115         prev_time  = phdr->ts;
1116       }
1117       if (nstime_cmp(&cur_time, &prev_time) < 0) {
1118         order = NOT_IN_ORDER;
1119       }
1120       if (nstime_cmp(&cur_time, &start_time) < 0) {
1121         start_time = cur_time;
1122         start_time_tsprec = phdr->pkt_tsprec;
1123       }
1124       if (nstime_cmp(&cur_time, &stop_time) > 0) {
1125         stop_time = cur_time;
1126         stop_time_tsprec = phdr->pkt_tsprec;
1127       }
1128     } else {
1129       have_times = FALSE; /* at least one packet has no time stamp */
1130       if (order != NOT_IN_ORDER)
1131         order = ORDER_UNKNOWN;
1132     }
1133
1134     if (phdr->rec_type == REC_TYPE_PACKET) {
1135       bytes+=phdr->len;
1136       packet++;
1137
1138       /* If caplen < len for a rcd, then presumably           */
1139       /* 'Limit packet capture length' was done for this rcd. */
1140       /* Keep track as to the min/max actual snapshot lengths */
1141       /*  seen for this file.                                 */
1142       if (phdr->caplen < phdr->len) {
1143         if (phdr->caplen < snaplen_min_inferred)
1144           snaplen_min_inferred = phdr->caplen;
1145         if (phdr->caplen > snaplen_max_inferred)
1146           snaplen_max_inferred = phdr->caplen;
1147       }
1148
1149       if ((phdr->pkt_encap > 0) && (phdr->pkt_encap < WTAP_NUM_ENCAP_TYPES)) {
1150         cf_info.encap_counts[phdr->pkt_encap] += 1;
1151       } else {
1152         fprintf(stderr, "capinfos: Unknown packet encapsulation %d in frame %u of file \"%s\"\n",
1153                 phdr->pkt_encap, packet, filename);
1154       }
1155
1156       /* Packet interface_id info */
1157       if (phdr->presence_flags & WTAP_HAS_INTERFACE_ID) {
1158         /* cf_info.num_interfaces is size, not index, so it's one more than max index */
1159         if (phdr->interface_id >= cf_info.num_interfaces) {
1160           /*
1161            * OK, re-fetch the number of interfaces, as there might have
1162            * been an interface that was in the middle of packets, and
1163            * grow the array to be big enough for the new number of
1164            * interfaces.
1165            */
1166           idb_info = wtap_file_get_idb_info(wth);
1167
1168           cf_info.num_interfaces = idb_info->interface_data->len;
1169           g_array_set_size(cf_info.interface_packet_counts, cf_info.num_interfaces);
1170
1171           g_free(idb_info);
1172           idb_info = NULL;
1173         }
1174         if (phdr->interface_id < cf_info.num_interfaces) {
1175           g_array_index(cf_info.interface_packet_counts, guint32, phdr->interface_id) += 1;
1176         }
1177         else {
1178           cf_info.pkt_interface_id_unknown += 1;
1179         }
1180       }
1181       else {
1182         /* it's for interface_id 0 */
1183         if (cf_info.num_interfaces != 0) {
1184           g_array_index(cf_info.interface_packet_counts, guint32, 0) += 1;
1185         }
1186         else {
1187           cf_info.pkt_interface_id_unknown += 1;
1188         }
1189       }
1190     }
1191
1192   } /* while */
1193
1194   /*
1195    * Get IDB info strings.
1196    * We do this at the end, so we can get information for all IDBs in
1197    * the file, even those that come after packet records.
1198    */
1199   idb_info = wtap_file_get_idb_info(wth);
1200
1201   cf_info.idb_info_strings = g_array_sized_new(FALSE, FALSE, sizeof(gchar*), cf_info.num_interfaces);
1202   cf_info.num_interfaces = idb_info->interface_data->len;
1203   for (i = 0; i < cf_info.num_interfaces; i++) {
1204     const wtap_block_t if_descr = g_array_index(idb_info->interface_data, wtap_block_t, i);
1205     gchar *s = wtap_get_debug_if_descr(if_descr, 21, "\n");
1206     g_array_append_val(cf_info.idb_info_strings, s);
1207   }
1208
1209   g_free(idb_info);
1210   idb_info = NULL;
1211
1212   if (err != 0) {
1213     fprintf(stderr,
1214         "capinfos: An error occurred after reading %u packets from \"%s\".\n",
1215         packet, filename);
1216     cfile_read_failure_message("capinfos", filename, err, err_info);
1217     if (err == WTAP_ERR_SHORT_READ) {
1218         /* Don't give up completely with this one. */
1219         status = 1;
1220         fprintf(stderr,
1221           "  (will continue anyway, checksums might be incorrect)\n");
1222     } else {
1223         cleanup_capture_info(&cf_info);
1224         return 1;
1225     }
1226   }
1227
1228   /* File size */
1229   size = wtap_file_size(wth, &err);
1230   if (size == -1) {
1231     fprintf(stderr,
1232         "capinfos: Can't get size of \"%s\": %s.\n",
1233         filename, g_strerror(err));
1234     cleanup_capture_info(&cf_info);
1235     return 1;
1236   }
1237
1238   cf_info.filesize = size;
1239
1240   /* File Type */
1241   cf_info.file_type = wtap_file_type_subtype(wth);
1242   cf_info.iscompressed = wtap_iscompressed(wth);
1243
1244   /* File Encapsulation */
1245   cf_info.file_encap = wtap_file_encap(wth);
1246
1247   cf_info.file_tsprec = wtap_file_tsprec(wth);
1248
1249   /* Packet size limit (snaplen) */
1250   cf_info.snaplen = wtap_snapshot_length(wth);
1251   if (cf_info.snaplen > 0)
1252     cf_info.snap_set = TRUE;
1253   else
1254     cf_info.snap_set = FALSE;
1255
1256   cf_info.snaplen_min_inferred = snaplen_min_inferred;
1257   cf_info.snaplen_max_inferred = snaplen_max_inferred;
1258
1259   /* # of packets */
1260   cf_info.packet_count = packet;
1261
1262   /* File Times */
1263   cf_info.times_known = have_times;
1264   cf_info.start_time = start_time;
1265   cf_info.start_time_tsprec = start_time_tsprec;
1266   cf_info.stop_time = stop_time;
1267   cf_info.stop_time_tsprec = stop_time_tsprec;
1268   nstime_delta(&cf_info.duration, &stop_time, &start_time);
1269   /* Duration precision is the higher of the start and stop time precisions. */
1270   if (cf_info.stop_time_tsprec > cf_info.start_time_tsprec)
1271     cf_info.duration_tsprec = cf_info.stop_time_tsprec;
1272   else
1273     cf_info.duration_tsprec = cf_info.start_time_tsprec;
1274   cf_info.know_order = know_order;
1275   cf_info.order = order;
1276
1277   /* Number of packet bytes */
1278   cf_info.packet_bytes = bytes;
1279
1280   cf_info.data_rate   = 0.0;
1281   cf_info.packet_rate = 0.0;
1282   cf_info.packet_size = 0.0;
1283
1284   if (packet > 0) {
1285     double delta_time = nstime_to_sec(&stop_time) - nstime_to_sec(&start_time);
1286     if (delta_time > 0.0) {
1287       cf_info.data_rate   = (double)bytes  / delta_time; /* Data rate per second */
1288       cf_info.packet_rate = (double)packet / delta_time; /* packet rate per second */
1289     }
1290     cf_info.packet_size = (double)bytes / packet;                  /* Avg packet size      */
1291   }
1292
1293   if (long_report) {
1294     print_stats(filename, &cf_info);
1295   } else {
1296     print_stats_table(filename, &cf_info);
1297   }
1298
1299   cleanup_capture_info(&cf_info);
1300
1301   return status;
1302 }
1303
1304 static void
1305 print_usage(FILE *output)
1306 {
1307   fprintf(output, "\n");
1308   fprintf(output, "Usage: capinfos [options] <infile> ...\n");
1309   fprintf(output, "\n");
1310   fprintf(output, "General infos:\n");
1311   fprintf(output, "  -t display the capture file type\n");
1312   fprintf(output, "  -E display the capture file encapsulation\n");
1313   fprintf(output, "  -I display the capture file interface information\n");
1314   fprintf(output, "  -F display additional capture file information\n");
1315   fprintf(output, "  -H display the SHA256, RMD160, and SHA1 hashes of the file\n");
1316   fprintf(output, "  -k display the capture comment\n");
1317   fprintf(output, "\n");
1318   fprintf(output, "Size infos:\n");
1319   fprintf(output, "  -c display the number of packets\n");
1320   fprintf(output, "  -s display the size of the file (in bytes)\n");
1321   fprintf(output, "  -d display the total length of all packets (in bytes)\n");
1322   fprintf(output, "  -l display the packet size limit (snapshot length)\n");
1323   fprintf(output, "\n");
1324   fprintf(output, "Time infos:\n");
1325   fprintf(output, "  -u display the capture duration (in seconds)\n");
1326   fprintf(output, "  -a display the capture start time\n");
1327   fprintf(output, "  -e display the capture end time\n");
1328   fprintf(output, "  -o display the capture file chronological status (True/False)\n");
1329   fprintf(output, "  -S display start and end times as seconds\n");
1330   fprintf(output, "\n");
1331   fprintf(output, "Statistic infos:\n");
1332   fprintf(output, "  -y display average data rate (in bytes/sec)\n");
1333   fprintf(output, "  -i display average data rate (in bits/sec)\n");
1334   fprintf(output, "  -z display average packet size (in bytes)\n");
1335   fprintf(output, "  -x display average packet rate (in packets/sec)\n");
1336   fprintf(output, "\n");
1337   fprintf(output, "Output format:\n");
1338   fprintf(output, "  -L generate long report (default)\n");
1339   fprintf(output, "  -T generate table report\n");
1340   fprintf(output, "  -M display machine-readable values in long reports\n");
1341   fprintf(output, "\n");
1342   fprintf(output, "Table report options:\n");
1343   fprintf(output, "  -R generate header record (default)\n");
1344   fprintf(output, "  -r do not generate header record\n");
1345   fprintf(output, "\n");
1346   fprintf(output, "  -B separate infos with TAB character (default)\n");
1347   fprintf(output, "  -m separate infos with comma (,) character\n");
1348   fprintf(output, "  -b separate infos with SPACE character\n");
1349   fprintf(output, "\n");
1350   fprintf(output, "  -N do not quote infos (default)\n");
1351   fprintf(output, "  -q quote infos with single quotes (')\n");
1352   fprintf(output, "  -Q quote infos with double quotes (\")\n");
1353   fprintf(output, "\n");
1354   fprintf(output, "Miscellaneous:\n");
1355   fprintf(output, "  -h display this help and exit\n");
1356   fprintf(output, "  -C cancel processing if file open fails (default is to continue)\n");
1357   fprintf(output, "  -A generate all infos (default)\n");
1358   fprintf(output, "  -K disable displaying the capture comment\n");
1359   fprintf(output, "\n");
1360   fprintf(output, "Options are processed from left to right order with later options superceding\n");
1361   fprintf(output, "or adding to earlier options.\n");
1362   fprintf(output, "\n");
1363   fprintf(output, "If no options are given the default is to display all infos in long report\n");
1364   fprintf(output, "output format.\n");
1365 }
1366
1367 /*
1368  * General errors and warnings are reported with an console message
1369  * in capinfos.
1370  */
1371 static void
1372 failure_warning_message(const char *msg_format, va_list ap)
1373 {
1374   fprintf(stderr, "capinfos: ");
1375   vfprintf(stderr, msg_format, ap);
1376   fprintf(stderr, "\n");
1377 }
1378
1379 /*
1380  * Report additional information for an error in command-line arguments.
1381  */
1382 static void
1383 failure_message_cont(const char *msg_format, va_list ap)
1384 {
1385   vfprintf(stderr, msg_format, ap);
1386   fprintf(stderr, "\n");
1387 }
1388
1389 static void
1390 hash_to_str(const unsigned char *hash, size_t length, char *str) {
1391   int i;
1392
1393   for (i = 0; i < (int) length; i++) {
1394     g_snprintf(str+(i*2), 3, "%02x", hash[i]);
1395   }
1396 }
1397
1398 int
1399 main(int argc, char *argv[])
1400 {
1401   GString *comp_info_str;
1402   GString *runtime_info_str;
1403   char  *init_progfile_dir_error;
1404   wtap  *wth;
1405   int    err;
1406   gchar *err_info;
1407   int    opt;
1408   int    overall_error_status = EXIT_SUCCESS;
1409   static const struct option long_options[] = {
1410       {"help", no_argument, NULL, 'h'},
1411       {"version", no_argument, NULL, 'v'},
1412       {0, 0, 0, 0 }
1413   };
1414
1415   int status = 0;
1416   FILE  *fh;
1417   char  *hash_buf = NULL;
1418   gcry_md_hd_t hd = NULL;
1419   size_t hash_bytes;
1420
1421   /* Set the C-language locale to the native environment. */
1422   setlocale(LC_ALL, "");
1423
1424   cmdarg_err_init(failure_warning_message, failure_message_cont);
1425
1426   /* Get the decimal point. */
1427   decimal_point = g_strdup(localeconv()->decimal_point);
1428
1429   /* Get the compile-time version information string */
1430   comp_info_str = get_compiled_version_info(NULL, NULL);
1431
1432   /* Get the run-time version information string */
1433   runtime_info_str = get_runtime_version_info(NULL);
1434
1435   /* Add it to the information to be reported on a crash. */
1436   ws_add_crash_info("Capinfos (Wireshark) %s\n"
1437          "\n"
1438          "%s"
1439          "\n"
1440          "%s",
1441       get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
1442   g_string_free(comp_info_str, TRUE);
1443   g_string_free(runtime_info_str, TRUE);
1444
1445 #ifdef _WIN32
1446   arg_list_utf_16to8(argc, argv);
1447   create_app_running_mutex();
1448 #endif /* _WIN32 */
1449
1450   /*
1451    * Get credential information for later use.
1452    */
1453   init_process_policies();
1454
1455   /*
1456    * Attempt to get the pathname of the directory containing the
1457    * executable file.
1458    */
1459   init_progfile_dir_error = init_progfile_dir(argv[0], main);
1460   if (init_progfile_dir_error != NULL) {
1461     fprintf(stderr,
1462             "capinfos: Can't get pathname of directory containing the capinfos program: %s.\n",
1463             init_progfile_dir_error);
1464     g_free(init_progfile_dir_error);
1465   }
1466
1467   init_report_message(failure_warning_message, failure_warning_message,
1468                       NULL, NULL, NULL);
1469
1470   wtap_init(TRUE);
1471
1472   /* Process the options */
1473   while ((opt = getopt_long(argc, argv, "abcdehiklmoqrstuvxyzABCEFHIKLMNQRST", long_options, NULL)) !=-1) {
1474
1475     switch (opt) {
1476
1477       case 't':
1478         if (report_all_infos) disable_all_infos();
1479         cap_file_type = TRUE;
1480         break;
1481
1482       case 'E':
1483         if (report_all_infos) disable_all_infos();
1484         cap_file_encap = TRUE;
1485         break;
1486
1487       case 'l':
1488         if (report_all_infos) disable_all_infos();
1489         cap_snaplen = TRUE;
1490         break;
1491
1492       case 'c':
1493         if (report_all_infos) disable_all_infos();
1494         cap_packet_count = TRUE;
1495         break;
1496
1497       case 's':
1498         if (report_all_infos) disable_all_infos();
1499         cap_file_size = TRUE;
1500         break;
1501
1502       case 'd':
1503         if (report_all_infos) disable_all_infos();
1504         cap_data_size = TRUE;
1505         break;
1506
1507       case 'u':
1508         if (report_all_infos) disable_all_infos();
1509         cap_duration = TRUE;
1510         break;
1511
1512       case 'a':
1513         if (report_all_infos) disable_all_infos();
1514         cap_start_time = TRUE;
1515         break;
1516
1517       case 'e':
1518         if (report_all_infos) disable_all_infos();
1519         cap_end_time = TRUE;
1520         break;
1521
1522       case 'S':
1523         time_as_secs = TRUE;
1524         break;
1525
1526       case 'y':
1527         if (report_all_infos) disable_all_infos();
1528         cap_data_rate_byte = TRUE;
1529         break;
1530
1531       case 'i':
1532         if (report_all_infos) disable_all_infos();
1533         cap_data_rate_bit = TRUE;
1534         break;
1535
1536       case 'z':
1537         if (report_all_infos) disable_all_infos();
1538         cap_packet_size = TRUE;
1539         break;
1540
1541       case 'x':
1542         if (report_all_infos) disable_all_infos();
1543         cap_packet_rate = TRUE;
1544         break;
1545
1546       case 'H':
1547         if (report_all_infos) disable_all_infos();
1548         cap_file_hashes = TRUE;
1549         break;
1550
1551       case 'o':
1552         if (report_all_infos) disable_all_infos();
1553         cap_order = TRUE;
1554         break;
1555
1556       case 'k':
1557         if (report_all_infos) disable_all_infos();
1558         cap_comment = TRUE;
1559         break;
1560
1561       case 'K':
1562         cap_comment = FALSE;
1563         break;
1564
1565       case 'F':
1566         if (report_all_infos) disable_all_infos();
1567         cap_file_more_info = TRUE;
1568         break;
1569
1570       case 'I':
1571         if (report_all_infos) disable_all_infos();
1572         cap_file_idb = TRUE;
1573         break;
1574
1575       case 'C':
1576         continue_after_wtap_open_offline_failure = FALSE;
1577         break;
1578
1579       case 'A':
1580         enable_all_infos();
1581         break;
1582
1583       case 'L':
1584         long_report = TRUE;
1585         break;
1586
1587       case 'T':
1588         long_report = FALSE;
1589         break;
1590
1591       case 'M':
1592         machine_readable = TRUE;
1593         break;
1594
1595       case 'R':
1596         table_report_header = TRUE;
1597         break;
1598
1599       case 'r':
1600         table_report_header = FALSE;
1601         break;
1602
1603       case 'N':
1604         quote_char = '\0';
1605         break;
1606
1607       case 'q':
1608         quote_char = '\'';
1609         break;
1610
1611       case 'Q':
1612         quote_char = '"';
1613         break;
1614
1615       case 'B':
1616         field_separator = '\t';
1617         break;
1618
1619       case 'm':
1620         field_separator = ',';
1621         break;
1622
1623       case 'b':
1624         field_separator = ' ';
1625         break;
1626
1627       case 'h':
1628         printf("Capinfos (Wireshark) %s\n"
1629                "Print various information (infos) about capture files.\n"
1630                "See https://www.wireshark.org for more information.\n",
1631                get_ws_vcs_version_info());
1632         print_usage(stdout);
1633         goto exit;
1634         break;
1635
1636       case 'v':
1637         comp_info_str = get_compiled_version_info(NULL, NULL);
1638         runtime_info_str = get_runtime_version_info(NULL);
1639         show_version("Capinfos (Wireshark)", comp_info_str, runtime_info_str);
1640         g_string_free(comp_info_str, TRUE);
1641         g_string_free(runtime_info_str, TRUE);
1642         goto exit;
1643         break;
1644
1645       case '?':              /* Bad flag - print usage message */
1646         print_usage(stderr);
1647         overall_error_status = BAD_FLAG;
1648         goto exit;
1649         break;
1650     }
1651   }
1652
1653   if ((argc - optind) < 1) {
1654     print_usage(stderr);
1655     overall_error_status = INVALID_OPTION;
1656     goto exit;
1657   }
1658
1659   if (!long_report && table_report_header) {
1660     print_stats_table_header();
1661   }
1662
1663   if (cap_file_hashes) {
1664     gcry_check_version(NULL);
1665     gcry_md_open(&hd, GCRY_MD_SHA256, 0);
1666     if (hd) {
1667       gcry_md_enable(hd, GCRY_MD_RMD160);
1668       gcry_md_enable(hd, GCRY_MD_SHA1);
1669     }
1670     hash_buf = (char *)g_malloc(HASH_BUF_SIZE);
1671   }
1672
1673   overall_error_status = 0;
1674
1675   for (opt = optind; opt < argc; opt++) {
1676
1677     g_strlcpy(file_sha256, "<unknown>", HASH_STR_SIZE);
1678     g_strlcpy(file_rmd160, "<unknown>", HASH_STR_SIZE);
1679     g_strlcpy(file_sha1, "<unknown>", HASH_STR_SIZE);
1680
1681     if (cap_file_hashes) {
1682       fh = ws_fopen(argv[opt], "rb");
1683       if (fh && hd) {
1684         while((hash_bytes = fread(hash_buf, 1, HASH_BUF_SIZE, fh)) > 0) {
1685           gcry_md_write(hd, hash_buf, hash_bytes);
1686         }
1687         gcry_md_final(hd);
1688         hash_to_str(gcry_md_read(hd, GCRY_MD_SHA256), HASH_SIZE_SHA256, file_sha256);
1689         hash_to_str(gcry_md_read(hd, GCRY_MD_RMD160), HASH_SIZE_RMD160, file_rmd160);
1690         hash_to_str(gcry_md_read(hd, GCRY_MD_SHA1), HASH_SIZE_SHA1, file_sha1);
1691       }
1692       if (fh) fclose(fh);
1693       if (hd) gcry_md_reset(hd);
1694     }
1695
1696     wth = wtap_open_offline(argv[opt], WTAP_TYPE_AUTO, &err, &err_info, FALSE);
1697
1698     if (!wth) {
1699       cfile_open_failure_message("capinfos", argv[opt], err, err_info);
1700       overall_error_status = 2; /* remember that an error has occurred */
1701       if (!continue_after_wtap_open_offline_failure)
1702         goto exit;
1703     }
1704
1705     if (wth) {
1706       if ((opt > optind) && (long_report))
1707         printf("\n");
1708       status = process_cap_file(wth, argv[opt]);
1709
1710       wtap_close(wth);
1711       if (status) {
1712         overall_error_status = status;
1713         goto exit;
1714       }
1715     }
1716   }
1717
1718 exit:
1719   g_free(hash_buf);
1720   wtap_cleanup();
1721   free_progdirs();
1722   return overall_error_status;
1723 }
1724
1725 /*
1726  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1727  *
1728  * Local variables:
1729  * c-basic-offset: 2
1730  * tab-width: 8
1731  * indent-tabs-mode: nil
1732  * End:
1733  *
1734  * vi: set shiftwidth=2 tabstop=8 expandtab:
1735  * :indentSize=2:tabSize=8:noTabs=true:
1736  */