Qt: use data() instead of constData() in pcap_compile().
[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-or-later
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   wtap_rec             *rec;
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     rec = wtap_get_rec(wth);
1107     if (rec->presence_flags & WTAP_HAS_TS) {
1108       prev_time = cur_time;
1109       cur_time = rec->ts;
1110       if (packet == 0) {
1111         start_time = rec->ts;
1112         start_time_tsprec = rec->tsprec;
1113         stop_time  = rec->ts;
1114         stop_time_tsprec = rec->tsprec;
1115         prev_time  = rec->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 = rec->tsprec;
1123       }
1124       if (nstime_cmp(&cur_time, &stop_time) > 0) {
1125         stop_time = cur_time;
1126         stop_time_tsprec = rec->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 (rec->rec_type == REC_TYPE_PACKET) {
1135       bytes += rec->rec_header.packet_header.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 (rec->rec_header.packet_header.caplen < rec->rec_header.packet_header.len) {
1143         if (rec->rec_header.packet_header.caplen < snaplen_min_inferred)
1144           snaplen_min_inferred = rec->rec_header.packet_header.caplen;
1145         if (rec->rec_header.packet_header.caplen > snaplen_max_inferred)
1146           snaplen_max_inferred = rec->rec_header.packet_header.caplen;
1147       }
1148
1149       if ((rec->rec_header.packet_header.pkt_encap > 0) &&
1150           (rec->rec_header.packet_header.pkt_encap < WTAP_NUM_ENCAP_TYPES)) {
1151         cf_info.encap_counts[rec->rec_header.packet_header.pkt_encap] += 1;
1152       } else {
1153         fprintf(stderr, "capinfos: Unknown packet encapsulation %d in frame %u of file \"%s\"\n",
1154                 rec->rec_header.packet_header.pkt_encap, packet, filename);
1155       }
1156
1157       /* Packet interface_id info */
1158       if (rec->presence_flags & WTAP_HAS_INTERFACE_ID) {
1159         /* cf_info.num_interfaces is size, not index, so it's one more than max index */
1160         if (rec->rec_header.packet_header.interface_id >= cf_info.num_interfaces) {
1161           /*
1162            * OK, re-fetch the number of interfaces, as there might have
1163            * been an interface that was in the middle of packets, and
1164            * grow the array to be big enough for the new number of
1165            * interfaces.
1166            */
1167           idb_info = wtap_file_get_idb_info(wth);
1168
1169           cf_info.num_interfaces = idb_info->interface_data->len;
1170           g_array_set_size(cf_info.interface_packet_counts, cf_info.num_interfaces);
1171
1172           g_free(idb_info);
1173           idb_info = NULL;
1174         }
1175         if (rec->rec_header.packet_header.interface_id < cf_info.num_interfaces) {
1176           g_array_index(cf_info.interface_packet_counts, guint32,
1177                         rec->rec_header.packet_header.interface_id) += 1;
1178         }
1179         else {
1180           cf_info.pkt_interface_id_unknown += 1;
1181         }
1182       }
1183       else {
1184         /* it's for interface_id 0 */
1185         if (cf_info.num_interfaces != 0) {
1186           g_array_index(cf_info.interface_packet_counts, guint32, 0) += 1;
1187         }
1188         else {
1189           cf_info.pkt_interface_id_unknown += 1;
1190         }
1191       }
1192     }
1193
1194   } /* while */
1195
1196   /*
1197    * Get IDB info strings.
1198    * We do this at the end, so we can get information for all IDBs in
1199    * the file, even those that come after packet records.
1200    */
1201   idb_info = wtap_file_get_idb_info(wth);
1202
1203   cf_info.idb_info_strings = g_array_sized_new(FALSE, FALSE, sizeof(gchar*), cf_info.num_interfaces);
1204   cf_info.num_interfaces = idb_info->interface_data->len;
1205   for (i = 0; i < cf_info.num_interfaces; i++) {
1206     const wtap_block_t if_descr = g_array_index(idb_info->interface_data, wtap_block_t, i);
1207     gchar *s = wtap_get_debug_if_descr(if_descr, 21, "\n");
1208     g_array_append_val(cf_info.idb_info_strings, s);
1209   }
1210
1211   g_free(idb_info);
1212   idb_info = NULL;
1213
1214   if (err != 0) {
1215     fprintf(stderr,
1216         "capinfos: An error occurred after reading %u packets from \"%s\".\n",
1217         packet, filename);
1218     cfile_read_failure_message("capinfos", filename, err, err_info);
1219     if (err == WTAP_ERR_SHORT_READ) {
1220         /* Don't give up completely with this one. */
1221         status = 1;
1222         fprintf(stderr,
1223           "  (will continue anyway, checksums might be incorrect)\n");
1224     } else {
1225         cleanup_capture_info(&cf_info);
1226         return 1;
1227     }
1228   }
1229
1230   /* File size */
1231   size = wtap_file_size(wth, &err);
1232   if (size == -1) {
1233     fprintf(stderr,
1234         "capinfos: Can't get size of \"%s\": %s.\n",
1235         filename, g_strerror(err));
1236     cleanup_capture_info(&cf_info);
1237     return 1;
1238   }
1239
1240   cf_info.filesize = size;
1241
1242   /* File Type */
1243   cf_info.file_type = wtap_file_type_subtype(wth);
1244   cf_info.iscompressed = wtap_iscompressed(wth);
1245
1246   /* File Encapsulation */
1247   cf_info.file_encap = wtap_file_encap(wth);
1248
1249   cf_info.file_tsprec = wtap_file_tsprec(wth);
1250
1251   /* Packet size limit (snaplen) */
1252   cf_info.snaplen = wtap_snapshot_length(wth);
1253   if (cf_info.snaplen > 0)
1254     cf_info.snap_set = TRUE;
1255   else
1256     cf_info.snap_set = FALSE;
1257
1258   cf_info.snaplen_min_inferred = snaplen_min_inferred;
1259   cf_info.snaplen_max_inferred = snaplen_max_inferred;
1260
1261   /* # of packets */
1262   cf_info.packet_count = packet;
1263
1264   /* File Times */
1265   cf_info.times_known = have_times;
1266   cf_info.start_time = start_time;
1267   cf_info.start_time_tsprec = start_time_tsprec;
1268   cf_info.stop_time = stop_time;
1269   cf_info.stop_time_tsprec = stop_time_tsprec;
1270   nstime_delta(&cf_info.duration, &stop_time, &start_time);
1271   /* Duration precision is the higher of the start and stop time precisions. */
1272   if (cf_info.stop_time_tsprec > cf_info.start_time_tsprec)
1273     cf_info.duration_tsprec = cf_info.stop_time_tsprec;
1274   else
1275     cf_info.duration_tsprec = cf_info.start_time_tsprec;
1276   cf_info.know_order = know_order;
1277   cf_info.order = order;
1278
1279   /* Number of packet bytes */
1280   cf_info.packet_bytes = bytes;
1281
1282   cf_info.data_rate   = 0.0;
1283   cf_info.packet_rate = 0.0;
1284   cf_info.packet_size = 0.0;
1285
1286   if (packet > 0) {
1287     double delta_time = nstime_to_sec(&stop_time) - nstime_to_sec(&start_time);
1288     if (delta_time > 0.0) {
1289       cf_info.data_rate   = (double)bytes  / delta_time; /* Data rate per second */
1290       cf_info.packet_rate = (double)packet / delta_time; /* packet rate per second */
1291     }
1292     cf_info.packet_size = (double)bytes / packet;                  /* Avg packet size      */
1293   }
1294
1295   if (long_report) {
1296     print_stats(filename, &cf_info);
1297   } else {
1298     print_stats_table(filename, &cf_info);
1299   }
1300
1301   cleanup_capture_info(&cf_info);
1302
1303   return status;
1304 }
1305
1306 static void
1307 print_usage(FILE *output)
1308 {
1309   fprintf(output, "\n");
1310   fprintf(output, "Usage: capinfos [options] <infile> ...\n");
1311   fprintf(output, "\n");
1312   fprintf(output, "General infos:\n");
1313   fprintf(output, "  -t display the capture file type\n");
1314   fprintf(output, "  -E display the capture file encapsulation\n");
1315   fprintf(output, "  -I display the capture file interface information\n");
1316   fprintf(output, "  -F display additional capture file information\n");
1317   fprintf(output, "  -H display the SHA256, RMD160, and SHA1 hashes of the file\n");
1318   fprintf(output, "  -k display the capture comment\n");
1319   fprintf(output, "\n");
1320   fprintf(output, "Size infos:\n");
1321   fprintf(output, "  -c display the number of packets\n");
1322   fprintf(output, "  -s display the size of the file (in bytes)\n");
1323   fprintf(output, "  -d display the total length of all packets (in bytes)\n");
1324   fprintf(output, "  -l display the packet size limit (snapshot length)\n");
1325   fprintf(output, "\n");
1326   fprintf(output, "Time infos:\n");
1327   fprintf(output, "  -u display the capture duration (in seconds)\n");
1328   fprintf(output, "  -a display the capture start time\n");
1329   fprintf(output, "  -e display the capture end time\n");
1330   fprintf(output, "  -o display the capture file chronological status (True/False)\n");
1331   fprintf(output, "  -S display start and end times as seconds\n");
1332   fprintf(output, "\n");
1333   fprintf(output, "Statistic infos:\n");
1334   fprintf(output, "  -y display average data rate (in bytes/sec)\n");
1335   fprintf(output, "  -i display average data rate (in bits/sec)\n");
1336   fprintf(output, "  -z display average packet size (in bytes)\n");
1337   fprintf(output, "  -x display average packet rate (in packets/sec)\n");
1338   fprintf(output, "\n");
1339   fprintf(output, "Output format:\n");
1340   fprintf(output, "  -L generate long report (default)\n");
1341   fprintf(output, "  -T generate table report\n");
1342   fprintf(output, "  -M display machine-readable values in long reports\n");
1343   fprintf(output, "\n");
1344   fprintf(output, "Table report options:\n");
1345   fprintf(output, "  -R generate header record (default)\n");
1346   fprintf(output, "  -r do not generate header record\n");
1347   fprintf(output, "\n");
1348   fprintf(output, "  -B separate infos with TAB character (default)\n");
1349   fprintf(output, "  -m separate infos with comma (,) character\n");
1350   fprintf(output, "  -b separate infos with SPACE character\n");
1351   fprintf(output, "\n");
1352   fprintf(output, "  -N do not quote infos (default)\n");
1353   fprintf(output, "  -q quote infos with single quotes (')\n");
1354   fprintf(output, "  -Q quote infos with double quotes (\")\n");
1355   fprintf(output, "\n");
1356   fprintf(output, "Miscellaneous:\n");
1357   fprintf(output, "  -h display this help and exit\n");
1358   fprintf(output, "  -C cancel processing if file open fails (default is to continue)\n");
1359   fprintf(output, "  -A generate all infos (default)\n");
1360   fprintf(output, "  -K disable displaying the capture comment\n");
1361   fprintf(output, "\n");
1362   fprintf(output, "Options are processed from left to right order with later options superceding\n");
1363   fprintf(output, "or adding to earlier options.\n");
1364   fprintf(output, "\n");
1365   fprintf(output, "If no options are given the default is to display all infos in long report\n");
1366   fprintf(output, "output format.\n");
1367 }
1368
1369 /*
1370  * General errors and warnings are reported with an console message
1371  * in capinfos.
1372  */
1373 static void
1374 failure_warning_message(const char *msg_format, va_list ap)
1375 {
1376   fprintf(stderr, "capinfos: ");
1377   vfprintf(stderr, msg_format, ap);
1378   fprintf(stderr, "\n");
1379 }
1380
1381 /*
1382  * Report additional information for an error in command-line arguments.
1383  */
1384 static void
1385 failure_message_cont(const char *msg_format, va_list ap)
1386 {
1387   vfprintf(stderr, msg_format, ap);
1388   fprintf(stderr, "\n");
1389 }
1390
1391 static void
1392 hash_to_str(const unsigned char *hash, size_t length, char *str) {
1393   int i;
1394
1395   for (i = 0; i < (int) length; i++) {
1396     g_snprintf(str+(i*2), 3, "%02x", hash[i]);
1397   }
1398 }
1399
1400 int
1401 main(int argc, char *argv[])
1402 {
1403   GString *comp_info_str;
1404   GString *runtime_info_str;
1405   char  *init_progfile_dir_error;
1406   wtap  *wth;
1407   int    err;
1408   gchar *err_info;
1409   int    opt;
1410   int    overall_error_status = EXIT_SUCCESS;
1411   static const struct option long_options[] = {
1412       {"help", no_argument, NULL, 'h'},
1413       {"version", no_argument, NULL, 'v'},
1414       {0, 0, 0, 0 }
1415   };
1416
1417   int status = 0;
1418   FILE  *fh;
1419   char  *hash_buf = NULL;
1420   gcry_md_hd_t hd = NULL;
1421   size_t hash_bytes;
1422
1423   /* Set the C-language locale to the native environment. */
1424   setlocale(LC_ALL, "");
1425
1426   cmdarg_err_init(failure_warning_message, failure_message_cont);
1427
1428   /* Get the decimal point. */
1429   decimal_point = g_strdup(localeconv()->decimal_point);
1430
1431   /* Get the compile-time version information string */
1432   comp_info_str = get_compiled_version_info(NULL, NULL);
1433
1434   /* Get the run-time version information string */
1435   runtime_info_str = get_runtime_version_info(NULL);
1436
1437   /* Add it to the information to be reported on a crash. */
1438   ws_add_crash_info("Capinfos (Wireshark) %s\n"
1439          "\n"
1440          "%s"
1441          "\n"
1442          "%s",
1443       get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
1444   g_string_free(comp_info_str, TRUE);
1445   g_string_free(runtime_info_str, TRUE);
1446
1447 #ifdef _WIN32
1448   arg_list_utf_16to8(argc, argv);
1449   create_app_running_mutex();
1450 #endif /* _WIN32 */
1451
1452   /*
1453    * Get credential information for later use.
1454    */
1455   init_process_policies();
1456
1457   /*
1458    * Attempt to get the pathname of the directory containing the
1459    * executable file.
1460    */
1461   init_progfile_dir_error = init_progfile_dir(argv[0]);
1462   if (init_progfile_dir_error != NULL) {
1463     fprintf(stderr,
1464             "capinfos: Can't get pathname of directory containing the capinfos program: %s.\n",
1465             init_progfile_dir_error);
1466     g_free(init_progfile_dir_error);
1467   }
1468
1469   init_report_message(failure_warning_message, failure_warning_message,
1470                       NULL, NULL, NULL);
1471
1472   wtap_init(TRUE);
1473
1474   /* Process the options */
1475   while ((opt = getopt_long(argc, argv, "abcdehiklmoqrstuvxyzABCEFHIKLMNQRST", long_options, NULL)) !=-1) {
1476
1477     switch (opt) {
1478
1479       case 't':
1480         if (report_all_infos) disable_all_infos();
1481         cap_file_type = TRUE;
1482         break;
1483
1484       case 'E':
1485         if (report_all_infos) disable_all_infos();
1486         cap_file_encap = TRUE;
1487         break;
1488
1489       case 'l':
1490         if (report_all_infos) disable_all_infos();
1491         cap_snaplen = TRUE;
1492         break;
1493
1494       case 'c':
1495         if (report_all_infos) disable_all_infos();
1496         cap_packet_count = TRUE;
1497         break;
1498
1499       case 's':
1500         if (report_all_infos) disable_all_infos();
1501         cap_file_size = TRUE;
1502         break;
1503
1504       case 'd':
1505         if (report_all_infos) disable_all_infos();
1506         cap_data_size = TRUE;
1507         break;
1508
1509       case 'u':
1510         if (report_all_infos) disable_all_infos();
1511         cap_duration = TRUE;
1512         break;
1513
1514       case 'a':
1515         if (report_all_infos) disable_all_infos();
1516         cap_start_time = TRUE;
1517         break;
1518
1519       case 'e':
1520         if (report_all_infos) disable_all_infos();
1521         cap_end_time = TRUE;
1522         break;
1523
1524       case 'S':
1525         time_as_secs = TRUE;
1526         break;
1527
1528       case 'y':
1529         if (report_all_infos) disable_all_infos();
1530         cap_data_rate_byte = TRUE;
1531         break;
1532
1533       case 'i':
1534         if (report_all_infos) disable_all_infos();
1535         cap_data_rate_bit = TRUE;
1536         break;
1537
1538       case 'z':
1539         if (report_all_infos) disable_all_infos();
1540         cap_packet_size = TRUE;
1541         break;
1542
1543       case 'x':
1544         if (report_all_infos) disable_all_infos();
1545         cap_packet_rate = TRUE;
1546         break;
1547
1548       case 'H':
1549         if (report_all_infos) disable_all_infos();
1550         cap_file_hashes = TRUE;
1551         break;
1552
1553       case 'o':
1554         if (report_all_infos) disable_all_infos();
1555         cap_order = TRUE;
1556         break;
1557
1558       case 'k':
1559         if (report_all_infos) disable_all_infos();
1560         cap_comment = TRUE;
1561         break;
1562
1563       case 'K':
1564         cap_comment = FALSE;
1565         break;
1566
1567       case 'F':
1568         if (report_all_infos) disable_all_infos();
1569         cap_file_more_info = TRUE;
1570         break;
1571
1572       case 'I':
1573         if (report_all_infos) disable_all_infos();
1574         cap_file_idb = TRUE;
1575         break;
1576
1577       case 'C':
1578         continue_after_wtap_open_offline_failure = FALSE;
1579         break;
1580
1581       case 'A':
1582         enable_all_infos();
1583         break;
1584
1585       case 'L':
1586         long_report = TRUE;
1587         break;
1588
1589       case 'T':
1590         long_report = FALSE;
1591         break;
1592
1593       case 'M':
1594         machine_readable = TRUE;
1595         break;
1596
1597       case 'R':
1598         table_report_header = TRUE;
1599         break;
1600
1601       case 'r':
1602         table_report_header = FALSE;
1603         break;
1604
1605       case 'N':
1606         quote_char = '\0';
1607         break;
1608
1609       case 'q':
1610         quote_char = '\'';
1611         break;
1612
1613       case 'Q':
1614         quote_char = '"';
1615         break;
1616
1617       case 'B':
1618         field_separator = '\t';
1619         break;
1620
1621       case 'm':
1622         field_separator = ',';
1623         break;
1624
1625       case 'b':
1626         field_separator = ' ';
1627         break;
1628
1629       case 'h':
1630         printf("Capinfos (Wireshark) %s\n"
1631                "Print various information (infos) about capture files.\n"
1632                "See https://www.wireshark.org for more information.\n",
1633                get_ws_vcs_version_info());
1634         print_usage(stdout);
1635         goto exit;
1636         break;
1637
1638       case 'v':
1639         comp_info_str = get_compiled_version_info(NULL, NULL);
1640         runtime_info_str = get_runtime_version_info(NULL);
1641         show_version("Capinfos (Wireshark)", comp_info_str, runtime_info_str);
1642         g_string_free(comp_info_str, TRUE);
1643         g_string_free(runtime_info_str, TRUE);
1644         goto exit;
1645         break;
1646
1647       case '?':              /* Bad flag - print usage message */
1648         print_usage(stderr);
1649         overall_error_status = BAD_FLAG;
1650         goto exit;
1651         break;
1652     }
1653   }
1654
1655   if ((argc - optind) < 1) {
1656     print_usage(stderr);
1657     overall_error_status = INVALID_OPTION;
1658     goto exit;
1659   }
1660
1661   if (!long_report && table_report_header) {
1662     print_stats_table_header();
1663   }
1664
1665   if (cap_file_hashes) {
1666     gcry_check_version(NULL);
1667     gcry_md_open(&hd, GCRY_MD_SHA256, 0);
1668     if (hd) {
1669       gcry_md_enable(hd, GCRY_MD_RMD160);
1670       gcry_md_enable(hd, GCRY_MD_SHA1);
1671     }
1672     hash_buf = (char *)g_malloc(HASH_BUF_SIZE);
1673   }
1674
1675   overall_error_status = 0;
1676
1677   for (opt = optind; opt < argc; opt++) {
1678
1679     g_strlcpy(file_sha256, "<unknown>", HASH_STR_SIZE);
1680     g_strlcpy(file_rmd160, "<unknown>", HASH_STR_SIZE);
1681     g_strlcpy(file_sha1, "<unknown>", HASH_STR_SIZE);
1682
1683     if (cap_file_hashes) {
1684       fh = ws_fopen(argv[opt], "rb");
1685       if (fh && hd) {
1686         while((hash_bytes = fread(hash_buf, 1, HASH_BUF_SIZE, fh)) > 0) {
1687           gcry_md_write(hd, hash_buf, hash_bytes);
1688         }
1689         gcry_md_final(hd);
1690         hash_to_str(gcry_md_read(hd, GCRY_MD_SHA256), HASH_SIZE_SHA256, file_sha256);
1691         hash_to_str(gcry_md_read(hd, GCRY_MD_RMD160), HASH_SIZE_RMD160, file_rmd160);
1692         hash_to_str(gcry_md_read(hd, GCRY_MD_SHA1), HASH_SIZE_SHA1, file_sha1);
1693       }
1694       if (fh) fclose(fh);
1695       if (hd) gcry_md_reset(hd);
1696     }
1697
1698     wth = wtap_open_offline(argv[opt], WTAP_TYPE_AUTO, &err, &err_info, FALSE);
1699
1700     if (!wth) {
1701       cfile_open_failure_message("capinfos", argv[opt], err, err_info);
1702       overall_error_status = 2; /* remember that an error has occurred */
1703       if (!continue_after_wtap_open_offline_failure)
1704         goto exit;
1705     }
1706
1707     if (wth) {
1708       if ((opt > optind) && (long_report))
1709         printf("\n");
1710       status = process_cap_file(wth, argv[opt]);
1711
1712       wtap_close(wth);
1713       if (status) {
1714         overall_error_status = status;
1715         goto exit;
1716       }
1717     }
1718   }
1719
1720 exit:
1721   g_free(hash_buf);
1722   gcry_md_close(hd);
1723   wtap_cleanup();
1724   free_progdirs();
1725   return overall_error_status;
1726 }
1727
1728 /*
1729  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1730  *
1731  * Local variables:
1732  * c-basic-offset: 2
1733  * tab-width: 8
1734  * indent-tabs-mode: nil
1735  * End:
1736  *
1737  * vi: set shiftwidth=2 tabstop=8 expandtab:
1738  * :indentSize=2:tabSize=8:noTabs=true:
1739  */