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