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