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