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