Fix "disable this protocol by default".
[jlayton/wireshark.git] / tshark.c
1 /* tshark.c
2  *
3  * Text-mode variant of Wireshark, along the lines of tcpdump and snoop,
4  * by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris <guy@alum.mit.edu>.
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 #include <config.h>
26
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <locale.h>
31 #include <limits.h>
32
33 #ifdef HAVE_GETOPT_H
34 #include <getopt.h>
35 #endif
36
37 #include <errno.h>
38
39 #ifndef _WIN32
40 #include <signal.h>
41 #endif
42
43 #ifdef HAVE_LIBCAP
44 # include <sys/capability.h>
45 #endif
46
47 #ifndef HAVE_GETOPT_LONG
48 #include "wsutil/wsgetopt.h"
49 #endif
50
51 #include <glib.h>
52
53 #include <epan/exceptions.h>
54 #include <epan/epan-int.h>
55 #include <epan/epan.h>
56
57 #include <wsutil/clopts_common.h>
58 #include <wsutil/cmdarg_err.h>
59 #include <wsutil/crash_info.h>
60 #include <wsutil/filesystem.h>
61 #include <wsutil/file_util.h>
62 #include <wsutil/privileges.h>
63 #include <wsutil/report_err.h>
64 #include <ws_version_info.h>
65 #include <wiretap/wtap_opttypes.h>
66 #include <wiretap/pcapng.h>
67
68 #include "globals.h"
69 #include <epan/timestamp.h>
70 #include <epan/packet.h>
71 #ifdef HAVE_LUA
72 #include <epan/wslua/init_wslua.h>
73 #endif
74 #include "frame_tvbuff.h"
75 #include <epan/disabled_protos.h>
76 #include <epan/prefs.h>
77 #include <epan/column.h>
78 #include <epan/print.h>
79 #include <epan/addr_resolv.h>
80 #ifdef HAVE_LIBPCAP
81 #include "ui/capture_ui_utils.h"
82 #endif
83 #include "ui/util.h"
84 #include "ui/ui_util.h"
85 #include "ui/decode_as_utils.h"
86 #include "ui/cli/tshark-tap.h"
87 #include "ui/tap_export_pdu.h"
88 #include "register.h"
89 #include "filter_files.h"
90 #include <epan/epan_dissect.h>
91 #include <epan/tap.h>
92 #include <epan/stat_tap_ui.h>
93 #include <epan/conversation_table.h>
94 #include <epan/srt_table.h>
95 #include <epan/rtd_table.h>
96 #include <epan/ex-opt.h>
97 #include <epan/exported_pdu.h>
98
99 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
100 #include <epan/asn1.h>
101 #include <epan/dissectors/packet-kerberos.h>
102 #endif
103
104 #include "capture_opts.h"
105
106 #include "caputils/capture-pcap-util.h"
107
108 #ifdef HAVE_LIBPCAP
109 #include "caputils/capture_ifinfo.h"
110 #ifdef _WIN32
111 #include "caputils/capture-wpcap.h"
112 #include <wsutil/os_version_info.h>
113 #include <wsutil/unicode-utils.h>
114 #endif /* _WIN32 */
115 #include <capchild/capture_session.h>
116 #include <capchild/capture_sync.h>
117 #include <capture_info.h>
118 #endif /* HAVE_LIBPCAP */
119 #include "log.h"
120 #include <epan/funnel.h>
121
122 #include <wsutil/str_util.h>
123 #include <wsutil/utf8_entities.h>
124
125 #ifdef HAVE_PLUGINS
126 #include <wsutil/plugins.h>
127 #endif
128
129
130 #if 0
131 #define tshark_debug(...) g_warning(__VA_ARGS__)
132 #else
133 #define tshark_debug(...)
134 #endif
135
136 static guint32 cum_bytes;
137 static const frame_data *ref;
138 static frame_data ref_frame;
139 static frame_data *prev_dis;
140 static frame_data prev_dis_frame;
141 static frame_data *prev_cap;
142 static frame_data prev_cap_frame;
143
144 static gboolean perform_two_pass_analysis;
145
146 /*
147  * The way the packet decode is to be written.
148  */
149 typedef enum {
150   WRITE_TEXT,   /* summary or detail text */
151   WRITE_XML,    /* PDML or PSML */
152   WRITE_FIELDS, /* User defined list of fields */
153   WRITE_JSON,    /* JSON */
154   WRITE_EK      /* JSON bulk insert to Elasticsearch */
155   /* Add CSV and the like here */
156 } output_action_e;
157
158 static output_action_e output_action;
159 static gboolean do_dissection;     /* TRUE if we have to dissect each packet */
160 static gboolean print_packet_info; /* TRUE if we're to print packet information */
161 static gint print_summary = -1;    /* TRUE if we're to print packet summary information */
162 static gboolean print_details;     /* TRUE if we're to print packet details information */
163 static gboolean print_hex;         /* TRUE if we're to print hex/ascci information */
164 static gboolean line_buffered;
165 static gboolean really_quiet = FALSE;
166
167 static print_format_e print_format = PR_FMT_TEXT;
168 static print_stream_t *print_stream;
169
170 static output_fields_t* output_fields  = NULL;
171 static gchar **protocolfilter = NULL;
172
173 /* The line separator used between packets, changeable via the -S option */
174 static const char *separator = "";
175
176 #ifdef HAVE_LIBPCAP
177 /*
178  * TRUE if we're to print packet counts to keep track of captured packets.
179  */
180 static gboolean print_packet_counts;
181
182 static capture_options global_capture_opts;
183 static capture_session global_capture_session;
184 static info_data_t global_info_data;
185
186 #ifdef SIGINFO
187 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
188 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
189 #endif /* SIGINFO */
190
191 static gboolean capture(void);
192 static void report_counts(void);
193 #ifdef _WIN32
194 static BOOL WINAPI capture_cleanup(DWORD);
195 #else /* _WIN32 */
196 static void capture_cleanup(int);
197 #ifdef SIGINFO
198 static void report_counts_siginfo(int);
199 #endif /* SIGINFO */
200 #endif /* _WIN32 */
201
202 #else /* HAVE_LIBPCAP */
203
204 static char *output_file_name;
205
206 #endif /* HAVE_LIBPCAP */
207
208 static int load_cap_file(capture_file *, char *, int, gboolean, int, gint64);
209 static gboolean process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset,
210     struct wtap_pkthdr *whdr, const guchar *pd,
211     guint tap_flags);
212 static void show_capture_file_io_error(const char *, int, gboolean);
213 static void show_print_file_io_error(int err);
214 static gboolean write_preamble(capture_file *cf);
215 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
216 static gboolean write_finale(void);
217 static const char *cf_open_error_message(int err, gchar *err_info,
218     gboolean for_writing, int file_type);
219
220 static void open_failure_message(const char *filename, int err,
221     gboolean for_writing);
222 static void failure_message(const char *msg_format, va_list ap);
223 static void read_failure_message(const char *filename, int err);
224 static void write_failure_message(const char *filename, int err);
225 static void failure_message_cont(const char *msg_format, va_list ap);
226
227 capture_file cfile;
228
229 static GHashTable *output_only_tables = NULL;
230
231 struct string_elem {
232   const char *sstr;   /* The short string */
233   const char *lstr;   /* The long string */
234 };
235
236 static gint
237 string_compare(gconstpointer a, gconstpointer b)
238 {
239   return strcmp(((const struct string_elem *)a)->sstr,
240                 ((const struct string_elem *)b)->sstr);
241 }
242
243 static void
244 string_elem_print(gpointer data, gpointer not_used _U_)
245 {
246   fprintf(stderr, "    %s - %s\n",
247           ((struct string_elem *)data)->sstr,
248           ((struct string_elem *)data)->lstr);
249 }
250
251 static void
252 list_capture_types(void) {
253   int                 i;
254   struct string_elem *captypes;
255   GSList             *list = NULL;
256
257   captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
258
259   fprintf(stderr, "tshark: The available capture file types for the \"-F\" flag are:\n");
260   for (i = 0; i < WTAP_NUM_FILE_TYPES_SUBTYPES; i++) {
261     if (wtap_dump_can_open(i)) {
262       captypes[i].sstr = wtap_file_type_subtype_short_string(i);
263       captypes[i].lstr = wtap_file_type_subtype_string(i);
264       list = g_slist_insert_sorted(list, &captypes[i], string_compare);
265     }
266   }
267   g_slist_foreach(list, string_elem_print, NULL);
268   g_slist_free(list);
269   g_free(captypes);
270 }
271
272 static void
273 list_read_capture_types(void) {
274   int                 i;
275   struct string_elem *captypes;
276   GSList             *list = NULL;
277   const char *magic = "Magic-value-based";
278   const char *heuristic = "Heuristics-based";
279
280   /* this is a hack, but WTAP_NUM_FILE_TYPES_SUBTYPES is always >= number of open routines so we're safe */
281   captypes = g_new(struct string_elem, WTAP_NUM_FILE_TYPES_SUBTYPES);
282
283   fprintf(stderr, "tshark: The available read file types for the \"-X read_format:\" option are:\n");
284   for (i = 0; open_routines[i].name != NULL; i++) {
285     captypes[i].sstr = open_routines[i].name;
286     captypes[i].lstr = (open_routines[i].type == OPEN_INFO_MAGIC) ? magic : heuristic;
287     list = g_slist_insert_sorted(list, &captypes[i], string_compare);
288   }
289   g_slist_foreach(list, string_elem_print, NULL);
290   g_slist_free(list);
291   g_free(captypes);
292 }
293
294 static void
295 print_usage(FILE *output)
296 {
297   fprintf(output, "\n");
298   fprintf(output, "Usage: tshark [options] ...\n");
299   fprintf(output, "\n");
300
301 #ifdef HAVE_LIBPCAP
302   fprintf(output, "Capture interface:\n");
303   fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback)\n");
304   fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
305   fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
306   fprintf(output, "  -p                       don't capture in promiscuous mode\n");
307 #ifdef HAVE_PCAP_CREATE
308   fprintf(output, "  -I                       capture in monitor mode, if available\n");
309 #endif
310 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
311   fprintf(output, "  -B <buffer size>         size of kernel buffer (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
312 #endif
313   fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
314   fprintf(output, "  -D                       print list of interfaces and exit\n");
315   fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
316   fprintf(output, "\n");
317   fprintf(output, "Capture stop conditions:\n");
318   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
319   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
320   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
321   fprintf(output, "                              files:NUM - stop after NUM files\n");
322   /*fprintf(output, "\n");*/
323   fprintf(output, "Capture output:\n");
324   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
325   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
326   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
327 #endif  /* HAVE_LIBPCAP */
328 #ifdef HAVE_PCAP_REMOTE
329   fprintf(output, "RPCAP options:\n");
330   fprintf(output, "  -A <user>:<password>     use RPCAP password authentication\n");
331 #endif
332   /*fprintf(output, "\n");*/
333   fprintf(output, "Input file:\n");
334   fprintf(output, "  -r <infile>              set the filename to read from (- to read from stdin)\n");
335
336   fprintf(output, "\n");
337   fprintf(output, "Processing:\n");
338   fprintf(output, "  -2                       perform a two-pass analysis\n");
339   fprintf(output, "  -R <read filter>         packet Read filter in Wireshark display filter syntax\n");
340   fprintf(output, "  -Y <display filter>      packet displaY filter in Wireshark display filter\n");
341   fprintf(output, "                           syntax\n");
342   fprintf(output, "  -n                       disable all name resolutions (def: all enabled)\n");
343   fprintf(output, "  -N <name resolve flags>  enable specific name resolution(s): \"mnNtCd\"\n");
344   fprintf(output, "  -d %s ...\n", DECODE_AS_ARG_TEMPLATE);
345   fprintf(output, "                           \"Decode As\", see the man page for details\n");
346   fprintf(output, "                           Example: tcp.port==8888,http\n");
347   fprintf(output, "  -H <hosts file>          read a list of entries from a hosts file, which will\n");
348   fprintf(output, "                           then be written to a capture file. (Implies -W n)\n");
349   fprintf(output, "  --disable-protocol <proto_name>\n");
350   fprintf(output, "                           disable dissection of proto_name\n");
351   fprintf(output, "  --enable-heuristic <short_name>\n");
352   fprintf(output, "                           enable dissection of heuristic protocol\n");
353   fprintf(output, "  --disable-heuristic <short_name>\n");
354   fprintf(output, "                           disable dissection of heuristic protocol\n");
355
356   /*fprintf(output, "\n");*/
357   fprintf(output, "Output:\n");
358   fprintf(output, "  -w <outfile|->           write packets to a pcap-format file named \"outfile\"\n");
359   fprintf(output, "                           (or to the standard output for \"-\")\n");
360   fprintf(output, "  -C <config profile>      start with specified configuration profile\n");
361   fprintf(output, "  -F <output file type>    set the output file type, default is pcapng\n");
362   fprintf(output, "                           an empty \"-F\" option will list the file types\n");
363   fprintf(output, "  -V                       add output of packet tree        (Packet Details)\n");
364   fprintf(output, "  -O <protocols>           Only show packet details of these protocols, comma\n");
365   fprintf(output, "                           separated\n");
366   fprintf(output, "  -P                       print packet summary even when writing to a file\n");
367   fprintf(output, "  -S <separator>           the line separator to print between packets\n");
368   fprintf(output, "  -x                       add output of hex and ASCII dump (Packet Bytes)\n");
369   fprintf(output, "  -T pdml|ps|psml|json|ek|text|fields\n");
370   fprintf(output, "                           format of text output (def: text)\n");
371   fprintf(output, "  -j <protocolfilter>      protocols layers filter if -T ek|pdml|json selected,\n");
372   fprintf(output, "                           (e.g. \"http tcp ip\",\n");
373   fprintf(output, "  -e <field>               field to print if -Tfields selected (e.g. tcp.port,\n");
374   fprintf(output, "                           _ws.col.Info)\n");
375   fprintf(output, "                           this option can be repeated to print multiple fields\n");
376   fprintf(output, "  -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
377   fprintf(output, "     bom=y|n               print a UTF-8 BOM\n");
378   fprintf(output, "     header=y|n            switch headers on and off\n");
379   fprintf(output, "     separator=/t|/s|<char> select tab, space, printable character as separator\n");
380   fprintf(output, "     occurrence=f|l|a      print first, last or all occurrences of each field\n");
381   fprintf(output, "     aggregator=,|/s|<char> select comma, space, printable character as\n");
382   fprintf(output, "                           aggregator\n");
383   fprintf(output, "     quote=d|s|n           select double, single, no quotes for values\n");
384   fprintf(output, "  -t a|ad|d|dd|e|r|u|ud    output format of time stamps (def: r: rel. to first)\n");
385   fprintf(output, "  -u s|hms                 output format of seconds (def: s: seconds)\n");
386   fprintf(output, "  -l                       flush standard output after each packet\n");
387   fprintf(output, "  -q                       be more quiet on stdout (e.g. when using statistics)\n");
388   fprintf(output, "  -Q                       only log true errors to stderr (quieter than -q)\n");
389   fprintf(output, "  -g                       enable group read access on the output file(s)\n");
390   fprintf(output, "  -W n                     Save extra information in the file, if supported.\n");
391   fprintf(output, "                           n = write network address resolution information\n");
392   fprintf(output, "  -X <key>:<value>         eXtension options, see the man page for details\n");
393   fprintf(output, "  -U tap_name              PDUs export mode, see the man page for details\n");
394   fprintf(output, "  -z <statistics>          various statistics, see the man page for details\n");
395   fprintf(output, "  --capture-comment <comment>\n");
396   fprintf(output, "                           add a capture comment to the newly created\n");
397   fprintf(output, "                           output file (only for pcapng)\n");
398
399   fprintf(output, "\n");
400   fprintf(output, "Miscellaneous:\n");
401   fprintf(output, "  -h                       display this help and exit\n");
402   fprintf(output, "  -v                       display version info and exit\n");
403   fprintf(output, "  -o <name>:<value> ...    override preference setting\n");
404   fprintf(output, "  -K <keytab>              keytab file to use for kerberos decryption\n");
405   fprintf(output, "  -G [report]              dump one of several available reports and exit\n");
406   fprintf(output, "                           default report=\"fields\"\n");
407   fprintf(output, "                           use \"-G ?\" for more help\n");
408 #ifdef __linux__
409   fprintf(output, "\n");
410   fprintf(output, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
411   fprintf(output, "You might want to reset it\n");
412   fprintf(output, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
413   fprintf(output, "\n");
414 #endif
415
416 }
417
418 static void
419 glossary_option_help(void)
420 {
421   FILE *output;
422
423   output = stdout;
424
425   fprintf(output, "TShark (Wireshark) %s\n", get_ws_vcs_version_info());
426
427   fprintf(output, "\n");
428   fprintf(output, "Usage: tshark -G [report]\n");
429   fprintf(output, "\n");
430   fprintf(output, "Glossary table reports:\n");
431   fprintf(output, "  -G column-formats        dump column format codes and exit\n");
432   fprintf(output, "  -G decodes               dump \"layer type\"/\"decode as\" associations and exit\n");
433   fprintf(output, "  -G dissector-tables      dump dissector table names, types, and properties\n");
434   fprintf(output, "  -G fieldcount            dump count of header fields and exit\n");
435   fprintf(output, "  -G fields                dump fields glossary and exit\n");
436   fprintf(output, "  -G ftypes                dump field type basic and descriptive names\n");
437   fprintf(output, "  -G heuristic-decodes     dump heuristic dissector tables\n");
438   fprintf(output, "  -G plugins               dump installed plugins and exit\n");
439   fprintf(output, "  -G protocols             dump protocols in registration database and exit\n");
440   fprintf(output, "  -G values                dump value, range, true/false strings and exit\n");
441   fprintf(output, "\n");
442   fprintf(output, "Preference reports:\n");
443   fprintf(output, "  -G currentprefs          dump current preferences and exit\n");
444   fprintf(output, "  -G defaultprefs          dump default preferences and exit\n");
445   fprintf(output, "\n");
446 }
447
448 static void
449 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
450     const gchar *message, gpointer user_data)
451 {
452   /* ignore log message, if log_level isn't interesting based
453      upon the console log preferences.
454      If the preferences haven't been loaded loaded yet, display the
455      message anyway.
456
457      The default console_log_level preference value is such that only
458        ERROR, CRITICAL and WARNING level messages are processed;
459        MESSAGE, INFO and DEBUG level messages are ignored.
460
461      XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
462            ERROR and CRITICAL level messages so the current code is a behavioral
463            change.  The current behavior is the same as in Wireshark.
464   */
465   if ((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
466      prefs.console_log_level != 0) {
467     return;
468   }
469
470   g_log_default_handler(log_domain, log_level, message, user_data);
471
472 }
473
474 static char *
475 output_file_description(const char *fname)
476 {
477   char *save_file_string;
478
479   /* Get a string that describes what we're writing to */
480   if (strcmp(fname, "-") == 0) {
481     /* We're writing to the standard output */
482     save_file_string = g_strdup("standard output");
483   } else {
484     /* We're writing to a file with the name in save_file */
485     save_file_string = g_strdup_printf("file \"%s\"", fname);
486   }
487   return save_file_string;
488 }
489
490 static void
491 print_current_user(void) {
492   gchar *cur_user, *cur_group;
493
494   if (started_with_special_privs()) {
495     cur_user = get_cur_username();
496     cur_group = get_cur_groupname();
497     fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
498       cur_user, cur_group);
499     g_free(cur_user);
500     g_free(cur_group);
501     if (running_with_special_privs()) {
502       fprintf(stderr, " This could be dangerous.");
503     }
504     fprintf(stderr, "\n");
505   }
506 }
507
508 static void
509 get_tshark_compiled_version_info(GString *str)
510 {
511   /* Capture libraries */
512   get_compiled_caplibs_version(str);
513 }
514
515 static void
516 get_tshark_runtime_version_info(GString *str)
517 {
518 #ifdef HAVE_LIBPCAP
519     /* Capture libraries */
520     g_string_append(str, ", ");
521     get_runtime_caplibs_version(str);
522 #endif
523
524     /* stuff used by libwireshark */
525     epan_get_runtime_version_info(str);
526 }
527
528 int
529 main(int argc, char *argv[])
530 {
531   GString             *comp_info_str;
532   GString             *runtime_info_str;
533   char                *init_progfile_dir_error;
534   int                  opt;
535   static const struct option long_options[] = {
536     {"help", no_argument, NULL, 'h'},
537     {"version", no_argument, NULL, 'v'},
538     LONGOPT_CAPTURE_COMMON
539     {0, 0, 0, 0 }
540   };
541   gboolean             arg_error = FALSE;
542
543 #ifdef _WIN32
544   WSADATA              wsaData;
545 #endif  /* _WIN32 */
546
547   char                *gpf_path, *pf_path;
548   char                *gdp_path, *dp_path;
549   char                *cf_path;
550   int                  gpf_open_errno, gpf_read_errno;
551   int                  pf_open_errno, pf_read_errno;
552   int                  gdp_open_errno, gdp_read_errno;
553   int                  dp_open_errno, dp_read_errno;
554   int                  cf_open_errno;
555   int                  err;
556   volatile int         exit_status = 0;
557 #ifdef HAVE_LIBPCAP
558   gboolean             list_link_layer_types = FALSE;
559   gboolean             start_capture = FALSE;
560   int                  status;
561   GList               *if_list;
562   gchar               *err_str;
563 #else
564   gboolean             capture_option_specified = FALSE;
565 #endif
566   gboolean             quiet = FALSE;
567 #ifdef PCAP_NG_DEFAULT
568   volatile int         out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAPNG;
569 #else
570   volatile int         out_file_type = WTAP_FILE_TYPE_SUBTYPE_PCAP;
571 #endif
572   volatile gboolean    out_file_name_res = FALSE;
573   volatile int         in_file_type = WTAP_TYPE_AUTO;
574   gchar               *volatile cf_name = NULL;
575   gchar               *rfilter = NULL;
576   gchar               *dfilter = NULL;
577 #ifdef HAVE_PCAP_OPEN_DEAD
578   struct bpf_program   fcode;
579 #endif
580   dfilter_t           *rfcode = NULL;
581   dfilter_t           *dfcode = NULL;
582   gchar               *err_msg;
583   e_prefs             *prefs_p;
584   char                 badopt;
585   int                  log_flags;
586   gchar               *output_only = NULL;
587   GSList              *disable_protocol_slist = NULL;
588   GSList              *enable_heur_slist = NULL;
589   GSList              *disable_heur_slist = NULL;
590   gchar               *volatile pdu_export_arg = NULL;
591   exp_pdu_t            exp_pdu_tap_data;
592
593 /*
594  * The leading + ensures that getopt_long() does not permute the argv[]
595  * entries.
596  *
597  * We have to make sure that the first getopt_long() preserves the content
598  * of argv[] for the subsequent getopt_long() call.
599  *
600  * We use getopt_long() in both cases to ensure that we're using a routine
601  * whose permutation behavior we can control in the same fashion on all
602  * platforms, and so that, if we ever need to process a long argument before
603  * doing further initialization, we can do so.
604  *
605  * Glibc and Solaris libc document that a leading + disables permutation
606  * of options, regardless of whether POSIXLY_CORRECT is set or not; *BSD
607  * and OS X don't document it, but do so anyway.
608  *
609  * We do *not* use a leading - because the behavior of a leading - is
610  * platform-dependent.
611  */
612 #define OPTSTRING "+2" OPTSTRING_CAPTURE_COMMON "C:d:e:E:F:gG:hH:j:" "K:lnN:o:O:PqQr:R:S:t:T:u:U:vVw:W:xX:Y:z:"
613
614   static const char    optstring[] = OPTSTRING;
615
616   tshark_debug("tshark started with %d args", argc);
617
618   /* Set the C-language locale to the native environment. */
619   setlocale(LC_ALL, "");
620
621   cmdarg_err_init(failure_message, failure_message_cont);
622
623 #ifdef _WIN32
624   arg_list_utf_16to8(argc, argv);
625   create_app_running_mutex();
626 #if !GLIB_CHECK_VERSION(2,31,0)
627   g_thread_init(NULL);
628 #endif
629 #endif /* _WIN32 */
630
631   /*
632    * Get credential information for later use, and drop privileges
633    * before doing anything else.
634    * Let the user know if anything happened.
635    */
636   init_process_policies();
637   relinquish_special_privs_perm();
638   print_current_user();
639
640   /*
641    * Attempt to get the pathname of the executable file.
642    */
643   init_progfile_dir_error = init_progfile_dir(argv[0], main);
644   if (init_progfile_dir_error != NULL) {
645     fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
646             init_progfile_dir_error);
647   }
648
649   initialize_funnel_ops();
650
651 #ifdef _WIN32
652   ws_init_dll_search_path();
653   /* Load wpcap if possible. Do this before collecting the run-time version information */
654   load_wpcap();
655
656   /* Warn the user if npf.sys isn't loaded. */
657   if (!npf_sys_is_running() && get_windows_major_version() >= 6) {
658     fprintf(stderr, "The NPF driver isn't running.  You may have trouble "
659       "capturing or\nlisting interfaces.\n");
660   }
661 #endif
662
663   /* Get the compile-time version information string */
664   comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
665                                             epan_get_compiled_version_info);
666
667   /* Get the run-time version information string */
668   runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
669
670   /* Add it to the information to be reported on a crash. */
671   ws_add_crash_info("TShark (Wireshark) %s\n"
672          "\n"
673          "%s"
674          "\n"
675          "%s",
676       get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
677   g_string_free(comp_info_str, TRUE);
678   g_string_free(runtime_info_str, TRUE);
679
680   /* Fail sometimes. Useful for testing fuzz scripts. */
681   /* if (g_random_int_range(0, 100) < 5) abort(); */
682
683   /*
684    * In order to have the -X opts assigned before the wslua machine starts
685    * we need to call getopt_long before epan_init() gets called.
686    *
687    * In order to handle, for example, -o options, we also need to call it
688    * *after* epan_init() gets called, so that the dissectors have had a
689    * chance to register their preferences.
690    *
691    * XXX - can we do this all with one getopt_long() call, saving the
692    * arguments we can't handle until after initializing libwireshark,
693    * and then process them after initializing libwireshark?
694    */
695   opterr = 0;
696
697   while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
698     switch (opt) {
699     case 'C':        /* Configuration Profile */
700       if (profile_exists (optarg, FALSE)) {
701         set_profile_name (optarg);
702       } else {
703         cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
704         return 1;
705       }
706       break;
707     case 'P':        /* Print packet summary info even when writing to a file */
708       print_packet_info = TRUE;
709       print_summary = TRUE;
710       break;
711     case 'O':        /* Only output these protocols */
712       output_only = g_strdup(optarg);
713       /* FALLTHROUGH */
714     case 'V':        /* Verbose */
715       print_details = TRUE;
716       print_packet_info = TRUE;
717       break;
718     case 'x':        /* Print packet data in hex (and ASCII) */
719       print_hex = TRUE;
720       /*  The user asked for hex output, so let's ensure they get it,
721        *  even if they're writing to a file.
722        */
723       print_packet_info = TRUE;
724       break;
725     case 'X':
726       ex_opt_add(optarg);
727       break;
728     default:
729       break;
730     }
731   }
732
733   /*
734    * Print packet summary information is the default, unless either -V or -x
735    * were specified and -P was not.  Note that this is new behavior, which
736    * allows for the possibility of printing only hex/ascii output without
737    * necessarily requiring that either the summary or details be printed too.
738    */
739   if (print_summary == -1)
740     print_summary = (print_details || print_hex) ? FALSE : TRUE;
741
742 /** Send All g_log messages to our own handler **/
743
744   log_flags =
745                     G_LOG_LEVEL_ERROR|
746                     G_LOG_LEVEL_CRITICAL|
747                     G_LOG_LEVEL_WARNING|
748                     G_LOG_LEVEL_MESSAGE|
749                     G_LOG_LEVEL_INFO|
750                     G_LOG_LEVEL_DEBUG|
751                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
752
753   g_log_set_handler(NULL,
754                     (GLogLevelFlags)log_flags,
755                     tshark_log_handler, NULL /* user_data */);
756   g_log_set_handler(LOG_DOMAIN_MAIN,
757                     (GLogLevelFlags)log_flags,
758                     tshark_log_handler, NULL /* user_data */);
759
760 #ifdef HAVE_LIBPCAP
761   g_log_set_handler(LOG_DOMAIN_CAPTURE,
762                     (GLogLevelFlags)log_flags,
763                     tshark_log_handler, NULL /* user_data */);
764   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
765                     (GLogLevelFlags)log_flags,
766                     tshark_log_handler, NULL /* user_data */);
767 #endif
768
769   init_report_err(failure_message, open_failure_message, read_failure_message,
770                   write_failure_message);
771
772 #ifdef HAVE_LIBPCAP
773   capture_opts_init(&global_capture_opts);
774   capture_session_init(&global_capture_session, &cfile);
775 #endif
776
777   timestamp_set_type(TS_RELATIVE);
778   timestamp_set_precision(TS_PREC_AUTO);
779   timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
780
781   init_open_routines();
782
783 #ifdef HAVE_PLUGINS
784   /* Register all the plugin types we have. */
785   epan_register_plugin_types(); /* Types known to libwireshark */
786   wtap_register_plugin_types(); /* Types known to libwiretap */
787
788   /* Scan for plugins.  This does *not* call their registration routines;
789      that's done later. */
790   scan_plugins();
791
792   /* Register all libwiretap plugin modules. */
793   register_all_wiretap_modules();
794 #endif
795
796   /* Register all dissectors; we must do this before checking for the
797      "-G" flag, as the "-G" flag dumps information registered by the
798      dissectors, and we must do it before we read the preferences, in
799      case any dissectors register preferences. */
800   if (!epan_init(register_all_protocols, register_all_protocol_handoffs, NULL,
801                  NULL))
802     return 2;
803
804   /* Register all tap listeners; we do this before we parse the arguments,
805      as the "-z" argument can specify a registered tap. */
806
807   /* we register the plugin taps before the other taps because
808      stats_tree taps plugins will be registered as tap listeners
809      by stats_tree_stat.c and need to registered before that */
810 #ifdef HAVE_PLUGINS
811   register_all_plugin_tap_listeners();
812 #endif
813   register_all_tap_listeners();
814   conversation_table_set_gui_info(init_iousers);
815   hostlist_table_set_gui_info(init_hostlists);
816   srt_table_iterate_tables(register_srt_tables, NULL);
817   rtd_table_iterate_tables(register_rtd_tables, NULL);
818   new_stat_tap_iterate_tables(register_simple_stat_tables, NULL);
819
820   /* If invoked with the "-G" flag, we dump out information based on
821      the argument to the "-G" flag; if no argument is specified,
822      for backwards compatibility we dump out a glossary of display
823      filter symbols.
824
825      XXX - we do this here, for now, to support "-G" with no arguments.
826      If none of our build or other processes uses "-G" with no arguments,
827      we can just process it with the other arguments. */
828   if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
829     proto_initialize_all_prefixes();
830
831     if (argc == 2)
832       proto_registrar_dump_fields();
833     else {
834       if (strcmp(argv[2], "column-formats") == 0)
835         column_dump_column_formats();
836       else if (strcmp(argv[2], "currentprefs") == 0) {
837         read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
838             &pf_open_errno, &pf_read_errno, &pf_path);
839         write_prefs(NULL);
840       }
841       else if (strcmp(argv[2], "decodes") == 0)
842         dissector_dump_decodes();
843       else if (strcmp(argv[2], "defaultprefs") == 0)
844         write_prefs(NULL);
845       else if (strcmp(argv[2], "dissector-tables") == 0)
846         dissector_dump_dissector_tables();
847       else if (strcmp(argv[2], "fieldcount") == 0) {
848         /* return value for the test suite */
849         return proto_registrar_dump_fieldcount();
850       } else if (strcmp(argv[2], "fields") == 0)
851         proto_registrar_dump_fields();
852       else if (strcmp(argv[2], "ftypes") == 0)
853         proto_registrar_dump_ftypes();
854       else if (strcmp(argv[2], "heuristic-decodes") == 0)
855         dissector_dump_heur_decodes();
856       else if (strcmp(argv[2], "plugins") == 0) {
857 #ifdef HAVE_PLUGINS
858         plugins_dump_all();
859 #endif
860 #ifdef HAVE_LUA
861         wslua_plugins_dump_all();
862 #endif
863       }
864       else if (strcmp(argv[2], "protocols") == 0)
865         proto_registrar_dump_protocols();
866       else if (strcmp(argv[2], "values") == 0)
867         proto_registrar_dump_values();
868       else if (strcmp(argv[2], "?") == 0)
869         glossary_option_help();
870       else if (strcmp(argv[2], "-?") == 0)
871         glossary_option_help();
872       else {
873         cmdarg_err("Invalid \"%s\" option for -G flag, enter -G ? for more help.", argv[2]);
874         return 1;
875       }
876     }
877     return 0;
878   }
879
880   /* load the decode as entries of this profile */
881   load_decode_as_entries();
882
883   tshark_debug("tshark reading preferences");
884
885   prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
886                      &pf_open_errno, &pf_read_errno, &pf_path);
887   if (gpf_path != NULL) {
888     if (gpf_open_errno != 0) {
889       cmdarg_err("Can't open global preferences file \"%s\": %s.",
890               pf_path, g_strerror(gpf_open_errno));
891     }
892     if (gpf_read_errno != 0) {
893       cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
894               pf_path, g_strerror(gpf_read_errno));
895     }
896   }
897   if (pf_path != NULL) {
898     if (pf_open_errno != 0) {
899       cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
900               g_strerror(pf_open_errno));
901     }
902     if (pf_read_errno != 0) {
903       cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
904               pf_path, g_strerror(pf_read_errno));
905     }
906     g_free(pf_path);
907     pf_path = NULL;
908   }
909
910   read_filter_list(CFILTER_LIST, &cf_path, &cf_open_errno);
911   if (cf_path != NULL) {
912       cmdarg_err("Could not open your capture filter file\n\"%s\": %s.",
913           cf_path, g_strerror(cf_open_errno));
914       g_free(cf_path);
915   }
916
917   /* Read the disabled protocols file. */
918   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
919                             &dp_path, &dp_open_errno, &dp_read_errno);
920   read_disabled_heur_dissector_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
921                             &dp_path, &dp_open_errno, &dp_read_errno);
922   if (gdp_path != NULL) {
923     if (gdp_open_errno != 0) {
924       cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
925                  gdp_path, g_strerror(gdp_open_errno));
926     }
927     if (gdp_read_errno != 0) {
928       cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
929                  gdp_path, g_strerror(gdp_read_errno));
930     }
931     g_free(gdp_path);
932   }
933   if (dp_path != NULL) {
934     if (dp_open_errno != 0) {
935       cmdarg_err(
936         "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
937         g_strerror(dp_open_errno));
938     }
939     if (dp_read_errno != 0) {
940       cmdarg_err(
941         "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
942         g_strerror(dp_read_errno));
943     }
944     g_free(dp_path);
945   }
946
947   cap_file_init(&cfile);
948
949   /* Print format defaults to this. */
950   print_format = PR_FMT_TEXT;
951
952   output_fields = output_fields_new();
953
954   /*
955    * To reset the options parser, set optreset to 1 on platforms that
956    * have optreset (documented in *BSD and OS X, apparently present but
957    * not documented in Solaris - the Illumos repository seems to
958    * suggest that the first Solaris getopt_long(), at least as of 2004,
959    * was based on the NetBSD one, it had optreset) and set optind to 1,
960    * and set optind to 0 otherwise (documented as working in the GNU
961    * getopt_long().  Setting optind to 0 didn't originally work in the
962    * NetBSD one, but that was added later - we don't want to depend on
963    * it if we have optreset).
964    *
965    * Also reset opterr to 1, so that error messages are printed by
966    * getopt_long().
967    */
968 #ifdef HAVE_OPTRESET
969   optreset = 1;
970   optind = 1;
971 #else
972   optind = 0;
973 #endif
974   opterr = 1;
975
976   /* Now get our args */
977   while ((opt = getopt_long(argc, argv, optstring, long_options, NULL)) != -1) {
978     switch (opt) {
979     case '2':        /* Perform two pass analysis */
980       perform_two_pass_analysis = TRUE;
981       break;
982     case 'a':        /* autostop criteria */
983     case 'b':        /* Ringbuffer option */
984     case 'c':        /* Capture x packets */
985     case 'f':        /* capture filter */
986     case 'g':        /* enable group read access on file(s) */
987     case 'i':        /* Use interface x */
988     case 'p':        /* Don't capture in promiscuous mode */
989 #ifdef HAVE_PCAP_REMOTE
990     case 'A':        /* Authentication */
991 #endif
992 #ifdef HAVE_PCAP_CREATE
993     case 'I':        /* Capture in monitor mode, if available */
994 #endif
995     case 's':        /* Set the snapshot (capture) length */
996     case 'w':        /* Write to capture file x */
997     case 'y':        /* Set the pcap data link type */
998     case  LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
999 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
1000     case 'B':        /* Buffer size */
1001 #endif
1002 #ifdef HAVE_LIBPCAP
1003       status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1004       if (status != 0) {
1005         return status;
1006       }
1007 #else
1008       if (opt == 'w') {
1009         /*
1010          * Output file name, if we're reading a file and writing to another
1011          * file.
1012          */
1013         output_file_name = optarg;
1014       } else {
1015         capture_option_specified = TRUE;
1016         arg_error = TRUE;
1017       }
1018 #endif
1019       break;
1020     case 'C':
1021       /* already processed; just ignore it now */
1022       break;
1023     case 'd':        /* Decode as rule */
1024       if (!decode_as_command_option(optarg))
1025         return 1;
1026       break;
1027 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1028     case 'K':        /* Kerberos keytab file */
1029       read_keytab_file(optarg);
1030       break;
1031 #endif
1032     case 'D':        /* Print a list of capture devices and exit */
1033 #ifdef HAVE_LIBPCAP
1034       if_list = capture_interface_list(&err, &err_str,NULL);
1035       if (if_list == NULL) {
1036         if (err == 0)
1037           cmdarg_err("There are no interfaces on which a capture can be done");
1038         else {
1039           cmdarg_err("%s", err_str);
1040           g_free(err_str);
1041         }
1042         return 2;
1043       }
1044       capture_opts_print_interfaces(if_list);
1045       free_interface_list(if_list);
1046       return 0;
1047 #else
1048       capture_option_specified = TRUE;
1049       arg_error = TRUE;
1050 #endif
1051       break;
1052     case 'e':
1053       /* Field entry */
1054       output_fields_add(output_fields, optarg);
1055       break;
1056     case 'E':
1057       /* Field option */
1058       if (!output_fields_set_option(output_fields, optarg)) {
1059         cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1060         output_fields_list_options(stderr);
1061         return 1;
1062       }
1063       break;
1064     case 'F':
1065       out_file_type = wtap_short_string_to_file_type_subtype(optarg);
1066       if (out_file_type < 0) {
1067         cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1068         list_capture_types();
1069         return 1;
1070       }
1071       break;
1072     case 'j':
1073       protocolfilter = wmem_strsplit(wmem_epan_scope(), optarg, " ", -1);
1074       break;
1075     case 'W':        /* Select extra information to save in our capture file */
1076       /* This is patterned after the -N flag which may not be the best idea. */
1077       if (strchr(optarg, 'n')) {
1078         out_file_name_res = TRUE;
1079       } else {
1080         cmdarg_err("Invalid -W argument \"%s\"; it must be one of:", optarg);
1081         cmdarg_err_cont("\t'n' write network address resolution information (pcapng only)");
1082         return 1;
1083       }
1084       break;
1085     case 'H':        /* Read address to name mappings from a hosts file */
1086       if (! add_hosts_file(optarg))
1087       {
1088         cmdarg_err("Can't read host entries from \"%s\"", optarg);
1089         return 1;
1090       }
1091       out_file_name_res = TRUE;
1092       break;
1093
1094     case 'h':        /* Print help and exit */
1095       printf("TShark (Wireshark) %s\n"
1096              "Dump and analyze network traffic.\n"
1097              "See https://www.wireshark.org for more information.\n",
1098              get_ws_vcs_version_info());
1099       print_usage(stdout);
1100       return 0;
1101       break;
1102     case 'l':        /* "Line-buffer" standard output */
1103       /* This isn't line-buffering, strictly speaking, it's just
1104          flushing the standard output after the information for
1105          each packet is printed; however, that should be good
1106          enough for all the purposes to which "-l" is put (and
1107          is probably actually better for "-V", as it does fewer
1108          writes).
1109
1110          See the comment in "process_packet()" for an explanation of
1111          why we do that, and why we don't just use "setvbuf()" to
1112          make the standard output line-buffered (short version: in
1113          Windows, "line-buffered" is the same as "fully-buffered",
1114          and the output buffer is only flushed when it fills up). */
1115       line_buffered = TRUE;
1116       break;
1117     case 'L':        /* Print list of link-layer types and exit */
1118 #ifdef HAVE_LIBPCAP
1119       list_link_layer_types = TRUE;
1120 #else
1121       capture_option_specified = TRUE;
1122       arg_error = TRUE;
1123 #endif
1124       break;
1125     case 'n':        /* No name resolution */
1126       disable_name_resolution();
1127       break;
1128     case 'N':        /* Select what types of addresses/port #s to resolve */
1129       badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
1130       if (badopt != '\0') {
1131         cmdarg_err("-N specifies unknown resolving option '%c'; valid options are:",
1132                    badopt);
1133         cmdarg_err_cont("\t'd' to enable address resolution from captured DNS packets\n"
1134                         "\t'm' to enable MAC address resolution\n"
1135                         "\t'n' to enable network address resolution\n"
1136                         "\t'N' to enable using external resolvers (e.g., DNS)\n"
1137                         "\t    for network address resolution\n"
1138                         "\t't' to enable transport-layer port number resolution");
1139         return 1;
1140       }
1141       break;
1142     case 'o':        /* Override preference from command line */
1143       switch (prefs_set_pref(optarg)) {
1144
1145       case PREFS_SET_OK:
1146         break;
1147
1148       case PREFS_SET_SYNTAX_ERR:
1149         cmdarg_err("Invalid -o flag \"%s\"", optarg);
1150         return 1;
1151         break;
1152
1153       case PREFS_SET_NO_SUCH_PREF:
1154       case PREFS_SET_OBSOLETE:
1155         cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1156         return 1;
1157         break;
1158       }
1159       break;
1160     case 'q':        /* Quiet */
1161       quiet = TRUE;
1162       break;
1163     case 'Q':        /* Really quiet */
1164       quiet = TRUE;
1165       really_quiet = TRUE;
1166       break;
1167     case 'r':        /* Read capture file x */
1168       cf_name = g_strdup(optarg);
1169       break;
1170     case 'R':        /* Read file filter */
1171       rfilter = optarg;
1172       break;
1173     case 'P':
1174         /* already processed; just ignore it now */
1175         break;
1176     case 'S':        /* Set the line Separator to be printed between packets */
1177       separator = optarg;
1178       break;
1179     case 't':        /* Time stamp type */
1180       if (strcmp(optarg, "r") == 0)
1181         timestamp_set_type(TS_RELATIVE);
1182       else if (strcmp(optarg, "a") == 0)
1183         timestamp_set_type(TS_ABSOLUTE);
1184       else if (strcmp(optarg, "ad") == 0)
1185         timestamp_set_type(TS_ABSOLUTE_WITH_YMD);
1186       else if (strcmp(optarg, "adoy") == 0)
1187         timestamp_set_type(TS_ABSOLUTE_WITH_YDOY);
1188       else if (strcmp(optarg, "d") == 0)
1189         timestamp_set_type(TS_DELTA);
1190       else if (strcmp(optarg, "dd") == 0)
1191         timestamp_set_type(TS_DELTA_DIS);
1192       else if (strcmp(optarg, "e") == 0)
1193         timestamp_set_type(TS_EPOCH);
1194       else if (strcmp(optarg, "u") == 0)
1195         timestamp_set_type(TS_UTC);
1196       else if (strcmp(optarg, "ud") == 0)
1197         timestamp_set_type(TS_UTC_WITH_YMD);
1198       else if (strcmp(optarg, "udoy") == 0)
1199         timestamp_set_type(TS_UTC_WITH_YDOY);
1200       else {
1201         cmdarg_err("Invalid time stamp type \"%s\"; it must be one of:", optarg);
1202         cmdarg_err_cont("\t\"a\"    for absolute\n"
1203                         "\t\"ad\"   for absolute with YYYY-MM-DD date\n"
1204                         "\t\"adoy\" for absolute with YYYY/DOY date\n"
1205                         "\t\"d\"    for delta\n"
1206                         "\t\"dd\"   for delta displayed\n"
1207                         "\t\"e\"    for epoch\n"
1208                         "\t\"r\"    for relative\n"
1209                         "\t\"u\"    for absolute UTC\n"
1210                         "\t\"ud\"   for absolute UTC with YYYY-MM-DD date\n"
1211                         "\t\"udoy\" for absolute UTC with YYYY/DOY date");
1212         return 1;
1213       }
1214       break;
1215     case 'T':        /* printing Type */
1216       print_packet_info = TRUE;
1217       if (strcmp(optarg, "text") == 0) {
1218         output_action = WRITE_TEXT;
1219         print_format = PR_FMT_TEXT;
1220       } else if (strcmp(optarg, "ps") == 0) {
1221         output_action = WRITE_TEXT;
1222         print_format = PR_FMT_PS;
1223       } else if (strcmp(optarg, "pdml") == 0) {
1224         output_action = WRITE_XML;
1225         print_details = TRUE;   /* Need details */
1226         print_summary = FALSE;  /* Don't allow summary */
1227       } else if (strcmp(optarg, "psml") == 0) {
1228         output_action = WRITE_XML;
1229         print_details = FALSE;  /* Don't allow details */
1230         print_summary = TRUE;   /* Need summary */
1231       } else if (strcmp(optarg, "fields") == 0) {
1232         output_action = WRITE_FIELDS;
1233         print_details = TRUE;   /* Need full tree info */
1234         print_summary = FALSE;  /* Don't allow summary */
1235       } else if (strcmp(optarg, "json") == 0) {
1236         output_action = WRITE_JSON;
1237         print_details = TRUE;   /* Need details */
1238         print_summary = FALSE;  /* Don't allow summary */
1239       } else if (strcmp(optarg, "ek") == 0) {
1240         output_action = WRITE_EK;
1241         print_details = TRUE;   /* Need details */
1242         print_summary = FALSE;  /* Don't allow summary */
1243       }
1244       else {
1245         cmdarg_err("Invalid -T parameter \"%s\"; it must be one of:", optarg);                   /* x */
1246         cmdarg_err_cont("\t\"fields\" The values of fields specified with the -e option, in a form\n"
1247                         "\t         specified by the -E option.\n"
1248                         "\t\"pdml\"   Packet Details Markup Language, an XML-based format for the\n"
1249                         "\t         details of a decoded packet. This information is equivalent to\n"
1250                         "\t         the packet details printed with the -V flag.\n"
1251                         "\t\"ps\"     PostScript for a human-readable one-line summary of each of\n"
1252                         "\t         the packets, or a multi-line view of the details of each of\n"
1253                         "\t         the packets, depending on whether the -V flag was specified.\n"
1254                         "\t\"psml\"   Packet Summary Markup Language, an XML-based format for the\n"
1255                         "\t         summary information of a decoded packet. This information is\n"
1256                         "\t         equivalent to the information shown in the one-line summary\n"
1257                         "\t         printed by default.\n"
1258                         "\t\"json\"   Packet Summary, an JSON-based format for the details\n"
1259                         "\t         summary information of a decoded packet. This information is \n"
1260                         "\t         equivalent to the packet details printed with the -V flag.\n"
1261                         "\t\"ek\"   Packet Summary, an EK JSON-based format for the bulk insert \n"
1262                         "\t         into elastic search cluster. This information is \n"
1263                         "\t         equivalent to the packet details printed with the -V flag.\n"
1264                         "\t\"text\"   Text of a human-readable one-line summary of each of the\n"
1265                         "\t         packets, or a multi-line view of the details of each of the\n"
1266                         "\t         packets, depending on whether the -V flag was specified.\n"
1267                         "\t         This is the default.");
1268         return 1;
1269       }
1270       break;
1271     case 'u':        /* Seconds type */
1272       if (strcmp(optarg, "s") == 0)
1273         timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
1274       else if (strcmp(optarg, "hms") == 0)
1275         timestamp_set_seconds_type(TS_SECONDS_HOUR_MIN_SEC);
1276       else {
1277         cmdarg_err("Invalid seconds type \"%s\"; it must be one of:", optarg);
1278         cmdarg_err_cont("\t\"s\"   for seconds\n"
1279                         "\t\"hms\" for hours, minutes and seconds");
1280         return 1;
1281       }
1282       break;
1283     case 'U':        /* Export PDUs to file */
1284     {
1285         GSList *export_pdu_tap_name_list = NULL;
1286
1287         if (!*optarg) {
1288             cmdarg_err("Tap name is required! Valid names are:");
1289             for (export_pdu_tap_name_list = get_export_pdu_tap_list(); export_pdu_tap_name_list; export_pdu_tap_name_list = g_slist_next(export_pdu_tap_name_list)) {
1290                 cmdarg_err("%s\n", (const char*)(export_pdu_tap_name_list->data));
1291             }
1292             return 1;
1293         }
1294         pdu_export_arg = g_strdup(optarg);
1295         break;
1296     }
1297     case 'v':         /* Show version and exit */
1298       comp_info_str = get_compiled_version_info(get_tshark_compiled_version_info,
1299                                                 epan_get_compiled_version_info);
1300       runtime_info_str = get_runtime_version_info(get_tshark_runtime_version_info);
1301       show_version("TShark (Wireshark)", comp_info_str, runtime_info_str);
1302       g_string_free(comp_info_str, TRUE);
1303       g_string_free(runtime_info_str, TRUE);
1304       /* We don't really have to cleanup here, but it's a convenient way to test
1305        * start-up and shut-down of the epan library without any UI-specific
1306        * cruft getting in the way. Makes the results of running
1307        * $ ./tools/valgrind-wireshark -n
1308        * much more useful. */
1309       epan_cleanup();
1310       return 0;
1311     case 'O':        /* Only output these protocols */
1312       /* already processed; just ignore it now */
1313       break;
1314     case 'V':        /* Verbose */
1315       /* already processed; just ignore it now */
1316       break;
1317     case 'x':        /* Print packet data in hex (and ASCII) */
1318       /* already processed; just ignore it now */
1319       break;
1320     case 'X':
1321       /* already processed; just ignore it now */
1322       break;
1323     case 'Y':
1324       dfilter = optarg;
1325       break;
1326     case 'z':
1327       /* We won't call the init function for the stat this soon
1328          as it would disallow MATE's fields (which are registered
1329          by the preferences set callback) from being used as
1330          part of a tap filter.  Instead, we just add the argument
1331          to a list of stat arguments. */
1332       if (strcmp("help", optarg) == 0) {
1333         fprintf(stderr, "tshark: The available statistics for the \"-z\" option are:\n");
1334         list_stat_cmd_args();
1335         return 0;
1336       }
1337       if (!process_stat_cmd_arg(optarg)) {
1338         cmdarg_err("Invalid -z argument \"%s\"; it must be one of:", optarg);
1339         list_stat_cmd_args();
1340         return 1;
1341       }
1342       break;
1343     case LONGOPT_DISABLE_PROTOCOL: /* disable dissection of protocol */
1344       disable_protocol_slist = g_slist_append(disable_protocol_slist, optarg);
1345       break;
1346     case LONGOPT_ENABLE_HEURISTIC: /* enable heuristic dissection of protocol */
1347       enable_heur_slist = g_slist_append(enable_heur_slist, optarg);
1348       break;
1349     case LONGOPT_DISABLE_HEURISTIC: /* disable heuristic dissection of protocol */
1350       disable_heur_slist = g_slist_append(disable_heur_slist, optarg);
1351       break;
1352
1353     default:
1354     case '?':        /* Bad flag - print usage message */
1355       switch(optopt) {
1356       case 'F':
1357         list_capture_types();
1358         break;
1359       default:
1360         print_usage(stderr);
1361       }
1362       return 1;
1363       break;
1364     }
1365   }
1366
1367   /* If we specified output fields, but not the output field type... */
1368   if (WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1369         cmdarg_err("Output fields were specified with \"-e\", "
1370             "but \"-Tfields\" was not specified.");
1371         return 1;
1372   } else if (WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1373         cmdarg_err("\"-Tfields\" was specified, but no fields were "
1374                     "specified with \"-e\".");
1375
1376         return 1;
1377   }
1378
1379   /* If no capture filter or display filter has been specified, and there are
1380      still command-line arguments, treat them as the tokens of a capture
1381      filter (if no "-r" flag was specified) or a display filter (if a "-r"
1382      flag was specified. */
1383   if (optind < argc) {
1384     if (cf_name != NULL) {
1385       if (dfilter != NULL) {
1386         cmdarg_err("Display filters were specified both with \"-d\" "
1387             "and with additional command-line arguments.");
1388         return 1;
1389       }
1390       dfilter = get_args_as_string(argc, argv, optind);
1391     } else {
1392 #ifdef HAVE_LIBPCAP
1393       guint i;
1394
1395       if (global_capture_opts.default_options.cfilter) {
1396         cmdarg_err("A default capture filter was specified both with \"-f\""
1397             " and with additional command-line arguments.");
1398         return 1;
1399       }
1400       for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1401         interface_options interface_opts;
1402         interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1403         if (interface_opts.cfilter == NULL) {
1404           interface_opts.cfilter = get_args_as_string(argc, argv, optind);
1405           global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
1406           g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
1407         } else {
1408           cmdarg_err("A capture filter was specified both with \"-f\""
1409               " and with additional command-line arguments.");
1410           return 1;
1411         }
1412       }
1413       global_capture_opts.default_options.cfilter = get_args_as_string(argc, argv, optind);
1414 #else
1415       capture_option_specified = TRUE;
1416 #endif
1417     }
1418   }
1419
1420 #ifdef HAVE_LIBPCAP
1421   if (!global_capture_opts.saving_to_file) {
1422     /* We're not saving the capture to a file; if "-q" wasn't specified,
1423        we should print packet information */
1424     if (!quiet)
1425       print_packet_info = TRUE;
1426   } else {
1427     /* We're saving to a file; if we're writing to the standard output.
1428        and we'll also be writing dissected packets to the standard
1429        output, reject the request.  At best, we could redirect that
1430        to the standard error; we *can't* write both to the standard
1431        output and have either of them be useful. */
1432     if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1433       cmdarg_err("You can't write both raw packet data and dissected packets"
1434           " to the standard output.");
1435       return 1;
1436     }
1437   }
1438 #else
1439   /* We're not saving the capture to a file; if "-q" wasn't specified,
1440      we should print packet information */
1441   if (!quiet)
1442     print_packet_info = TRUE;
1443 #endif
1444
1445 #ifndef HAVE_LIBPCAP
1446   if (capture_option_specified)
1447     cmdarg_err("This version of TShark was not built with support for capturing packets.");
1448 #endif
1449   if (arg_error) {
1450     print_usage(stderr);
1451     return 1;
1452   }
1453
1454   if (print_hex) {
1455     if (output_action != WRITE_TEXT && output_action != WRITE_JSON && output_action != WRITE_EK) {
1456       cmdarg_err("Raw packet hex data can only be printed as text, PostScript, JSON or EK JSON");
1457       return 1;
1458     }
1459   }
1460
1461   if (output_only != NULL) {
1462     char *ps;
1463
1464     if (!print_details) {
1465       cmdarg_err("-O requires -V");
1466       return 1;
1467     }
1468
1469     output_only_tables = g_hash_table_new (g_str_hash, g_str_equal);
1470     for (ps = strtok (output_only, ","); ps; ps = strtok (NULL, ",")) {
1471       g_hash_table_insert(output_only_tables, (gpointer)ps, (gpointer)ps);
1472     }
1473   }
1474
1475   if (rfilter != NULL && !perform_two_pass_analysis) {
1476     cmdarg_err("-R without -2 is deprecated. For single-pass filtering use -Y.");
1477     return 1;
1478   }
1479
1480 #ifdef HAVE_LIBPCAP
1481   if (list_link_layer_types) {
1482     /* We're supposed to list the link-layer types for an interface;
1483        did the user also specify a capture file to be read? */
1484     if (cf_name) {
1485       /* Yes - that's bogus. */
1486       cmdarg_err("You can't specify -L and a capture file to be read.");
1487       return 1;
1488     }
1489     /* No - did they specify a ring buffer option? */
1490     if (global_capture_opts.multi_files_on) {
1491       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1492       return 1;
1493     }
1494   } else {
1495     if (cf_name) {
1496       /*
1497        * "-r" was specified, so we're reading a capture file.
1498        * Capture options don't apply here.
1499        */
1500
1501       /* We don't support capture filters when reading from a capture file
1502          (the BPF compiler doesn't support all link-layer types that we
1503          support in capture files we read). */
1504       if (global_capture_opts.default_options.cfilter) {
1505         cmdarg_err("Only read filters, not capture filters, "
1506           "can be specified when reading a capture file.");
1507         return 1;
1508       }
1509       if (global_capture_opts.multi_files_on) {
1510         cmdarg_err("Multiple capture files requested, but "
1511                    "a capture isn't being done.");
1512         return 1;
1513       }
1514       if (global_capture_opts.has_file_duration) {
1515         cmdarg_err("Switching capture files after a time interval was specified, but "
1516                    "a capture isn't being done.");
1517         return 1;
1518       }
1519       if (global_capture_opts.has_ring_num_files) {
1520         cmdarg_err("A ring buffer of capture files was specified, but "
1521           "a capture isn't being done.");
1522         return 1;
1523       }
1524       if (global_capture_opts.has_autostop_files) {
1525         cmdarg_err("A maximum number of capture files was specified, but "
1526           "a capture isn't being done.");
1527         return 1;
1528       }
1529       if (global_capture_opts.capture_comment) {
1530         cmdarg_err("A capture comment was specified, but "
1531           "a capture isn't being done.\nThere's no support for adding "
1532           "a capture comment to an existing capture file.");
1533         return 1;
1534       }
1535
1536       /* Note: TShark now allows the restriction of a _read_ file by packet count
1537        * and byte count as well as a write file. Other autostop options remain valid
1538        * only for a write file.
1539        */
1540       if (global_capture_opts.has_autostop_duration) {
1541         cmdarg_err("A maximum capture time was specified, but "
1542           "a capture isn't being done.");
1543         return 1;
1544       }
1545     } else {
1546       /*
1547        * "-r" wasn't specified, so we're doing a live capture.
1548        */
1549       if (perform_two_pass_analysis) {
1550         /* Two-pass analysis doesn't work with live capture since it requires us
1551          * to buffer packets until we've read all of them, but a live capture
1552          * has no useful/meaningful definition of "all" */
1553         cmdarg_err("Live captures do not support two-pass analysis.");
1554         return 1;
1555       }
1556
1557       if (global_capture_opts.saving_to_file) {
1558         /* They specified a "-w" flag, so we'll be saving to a capture file. */
1559
1560         /* When capturing, we only support writing pcap or pcap-ng format. */
1561         if (out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAP &&
1562             out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1563           cmdarg_err("Live captures can only be saved in pcap or pcapng format.");
1564           return 1;
1565         }
1566         if (global_capture_opts.capture_comment &&
1567             out_file_type != WTAP_FILE_TYPE_SUBTYPE_PCAPNG) {
1568           cmdarg_err("A capture comment can only be written to a pcapng file.");
1569           return 1;
1570         }
1571         if (global_capture_opts.multi_files_on) {
1572           /* Multiple-file mode doesn't work under certain conditions:
1573              a) it doesn't work if you're writing to the standard output;
1574              b) it doesn't work if you're writing to a pipe;
1575           */
1576           if (strcmp(global_capture_opts.save_file, "-") == 0) {
1577             cmdarg_err("Multiple capture files requested, but "
1578               "the capture is being written to the standard output.");
1579             return 1;
1580           }
1581           if (global_capture_opts.output_to_pipe) {
1582             cmdarg_err("Multiple capture files requested, but "
1583               "the capture file is a pipe.");
1584             return 1;
1585           }
1586           if (!global_capture_opts.has_autostop_filesize &&
1587               !global_capture_opts.has_file_duration) {
1588             cmdarg_err("Multiple capture files requested, but "
1589               "no maximum capture file size or duration was specified.");
1590             return 1;
1591           }
1592         }
1593         /* Currently, we don't support read or display filters when capturing
1594            and saving the packets. */
1595         if (rfilter != NULL) {
1596           cmdarg_err("Read filters aren't supported when capturing and saving the captured packets.");
1597           return 1;
1598         }
1599         if (dfilter != NULL) {
1600           cmdarg_err("Display filters aren't supported when capturing and saving the captured packets.");
1601           return 1;
1602         }
1603         global_capture_opts.use_pcapng = (out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAPNG) ? TRUE : FALSE;
1604       } else {
1605         /* They didn't specify a "-w" flag, so we won't be saving to a
1606            capture file.  Check for options that only make sense if
1607            we're saving to a file. */
1608         if (global_capture_opts.has_autostop_filesize) {
1609           cmdarg_err("Maximum capture file size specified, but "
1610            "capture isn't being saved to a file.");
1611           return 1;
1612         }
1613         if (global_capture_opts.multi_files_on) {
1614           cmdarg_err("Multiple capture files requested, but "
1615             "the capture isn't being saved to a file.");
1616           return 1;
1617         }
1618         if (global_capture_opts.capture_comment) {
1619           cmdarg_err("A capture comment was specified, but "
1620             "the capture isn't being saved to a file.");
1621           return 1;
1622         }
1623       }
1624     }
1625   }
1626 #endif
1627
1628 #ifdef _WIN32
1629   /* Start windows sockets */
1630   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1631 #endif /* _WIN32 */
1632
1633   /* Notify all registered modules that have had any of their preferences
1634      changed either from one of the preferences file or from the command
1635      line that their preferences have changed. */
1636   prefs_apply_all();
1637
1638   /* At this point MATE will have registered its field array so we can
1639      have a tap filter with one of MATE's late-registered fields as part
1640      of the filter.  We can now process all the "-z" arguments. */
1641   start_requested_stats();
1642
1643   /* At this point MATE will have registered its field array so we can
1644      check if the fields specified by the user are all good.
1645    */
1646   {
1647     GSList* it = NULL;
1648     GSList *invalid_fields = output_fields_valid(output_fields);
1649     if (invalid_fields != NULL) {
1650
1651       cmdarg_err("Some fields aren't valid:");
1652       for (it=invalid_fields; it != NULL; it = g_slist_next(it)) {
1653         cmdarg_err_cont("\t%s", (gchar *)it->data);
1654       }
1655       g_slist_free(invalid_fields);
1656       return 1;
1657     }
1658   }
1659 #ifdef HAVE_LIBPCAP
1660   /* We currently don't support taps, or printing dissected packets,
1661      if we're writing to a pipe. */
1662   if (global_capture_opts.saving_to_file &&
1663       global_capture_opts.output_to_pipe) {
1664     if (tap_listeners_require_dissection()) {
1665       cmdarg_err("Taps aren't supported when saving to a pipe.");
1666       return 1;
1667     }
1668     if (print_packet_info) {
1669       cmdarg_err("Printing dissected packets isn't supported when saving to a pipe.");
1670       return 1;
1671     }
1672   }
1673 #endif
1674
1675   if (ex_opt_count("read_format") > 0) {
1676     const gchar* name = ex_opt_get_next("read_format");
1677     in_file_type = open_info_name_to_type(name);
1678     if (in_file_type == WTAP_TYPE_AUTO) {
1679       cmdarg_err("\"%s\" isn't a valid read file format type", name? name : "");
1680       list_read_capture_types();
1681       return 1;
1682     }
1683   }
1684
1685   /* disabled protocols as per configuration file */
1686   if (gdp_path == NULL && dp_path == NULL) {
1687     set_disabled_protos_list();
1688     set_disabled_heur_dissector_list();
1689   }
1690
1691   if(disable_protocol_slist) {
1692       GSList *proto_disable;
1693       for (proto_disable = disable_protocol_slist; proto_disable != NULL; proto_disable = g_slist_next(proto_disable))
1694       {
1695           proto_disable_proto_by_name((char*)proto_disable->data);
1696       }
1697   }
1698
1699   if(enable_heur_slist) {
1700       GSList *heur_enable;
1701       for (heur_enable = enable_heur_slist; heur_enable != NULL; heur_enable = g_slist_next(heur_enable))
1702       {
1703           proto_enable_heuristic_by_name((char*)heur_enable->data, TRUE);
1704       }
1705   }
1706
1707   if(disable_heur_slist) {
1708       GSList *heur_disable;
1709       for (heur_disable = disable_heur_slist; heur_disable != NULL; heur_disable = g_slist_next(heur_disable))
1710       {
1711           proto_enable_heuristic_by_name((char*)heur_disable->data, FALSE);
1712       }
1713   }
1714
1715   /* Build the column format array */
1716   build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
1717
1718 #ifdef HAVE_LIBPCAP
1719   capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1720   capture_opts_trim_ring_num_files(&global_capture_opts);
1721 #endif
1722
1723   if (rfilter != NULL) {
1724     tshark_debug("Compiling read filter: '%s'", rfilter);
1725     if (!dfilter_compile(rfilter, &rfcode, &err_msg)) {
1726       cmdarg_err("%s", err_msg);
1727       g_free(err_msg);
1728       epan_cleanup();
1729 #ifdef HAVE_PCAP_OPEN_DEAD
1730       {
1731         pcap_t *pc;
1732
1733         pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1734         if (pc != NULL) {
1735           if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1736             cmdarg_err_cont(
1737               "  Note: That read filter code looks like a valid capture filter;\n"
1738               "        maybe you mixed them up?");
1739           }
1740           pcap_close(pc);
1741         }
1742       }
1743 #endif
1744       return 2;
1745     }
1746   }
1747   cfile.rfcode = rfcode;
1748
1749   if (dfilter != NULL) {
1750     tshark_debug("Compiling display filter: '%s'", dfilter);
1751     if (!dfilter_compile(dfilter, &dfcode, &err_msg)) {
1752       cmdarg_err("%s", err_msg);
1753       g_free(err_msg);
1754       epan_cleanup();
1755 #ifdef HAVE_PCAP_OPEN_DEAD
1756       {
1757         pcap_t *pc;
1758
1759         pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1760         if (pc != NULL) {
1761           if (pcap_compile(pc, &fcode, dfilter, 0, 0) != -1) {
1762             cmdarg_err_cont(
1763               "  Note: That display filter code looks like a valid capture filter;\n"
1764               "        maybe you mixed them up?");
1765           }
1766           pcap_close(pc);
1767         }
1768       }
1769 #endif
1770       return 2;
1771     }
1772   }
1773   cfile.dfcode = dfcode;
1774
1775   if (print_packet_info) {
1776     /* If we're printing as text or PostScript, we have
1777        to create a print stream. */
1778     if (output_action == WRITE_TEXT) {
1779       switch (print_format) {
1780
1781       case PR_FMT_TEXT:
1782         print_stream = print_stream_text_stdio_new(stdout);
1783         break;
1784
1785       case PR_FMT_PS:
1786         print_stream = print_stream_ps_stdio_new(stdout);
1787         break;
1788
1789       default:
1790         g_assert_not_reached();
1791       }
1792     }
1793   }
1794
1795   /* PDU export requested. Take the ownership of the '-w' file, apply tap
1796   * filters and start tapping. */
1797   if (pdu_export_arg) {
1798       const char *exp_pdu_filename;
1799       const char *exp_pdu_tap_name = pdu_export_arg;
1800       const char *exp_pdu_filter = dfilter; /* may be NULL to disable filter */
1801       char       *exp_pdu_error;
1802       int         exp_fd;
1803
1804       if (!cf_name) {
1805           cmdarg_err("PDUs export requires a capture file (specify with -r).");
1806           return 1;
1807       }
1808       /* Take ownership of the '-w' output file. */
1809 #ifdef HAVE_LIBPCAP
1810       exp_pdu_filename = global_capture_opts.save_file;
1811       global_capture_opts.save_file = NULL;
1812 #else
1813       exp_pdu_filename = output_file_name;
1814       output_file_name = NULL;
1815 #endif
1816       if (exp_pdu_filename == NULL) {
1817           cmdarg_err("PDUs export requires an output file (-w).");
1818           return 1;
1819       }
1820
1821       exp_pdu_error = exp_pdu_pre_open(exp_pdu_tap_name, exp_pdu_filter,
1822           &exp_pdu_tap_data);
1823       if (exp_pdu_error) {
1824           cmdarg_err("Cannot register tap: %s", exp_pdu_error);
1825           g_free(exp_pdu_error);
1826           return 2;
1827       }
1828
1829       exp_fd = ws_open(exp_pdu_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
1830       if (exp_fd == -1) {
1831           cmdarg_err("%s: %s", exp_pdu_filename, file_open_error_message(errno, TRUE));
1832           return 2;
1833       }
1834
1835       /* Activate the export PDU tap */
1836       err = exp_pdu_open(&exp_pdu_tap_data, exp_fd,
1837           g_strdup_printf("Dump of PDUs from %s", cf_name));
1838       if (err != 0) {
1839           cmdarg_err("Failed to start the PDU export: %s", g_strerror(err));
1840           return 2;
1841       }
1842   }
1843
1844   /* We have to dissect each packet if:
1845
1846         we're printing information about each packet;
1847
1848         we're using a read filter on the packets;
1849
1850         we're using a display filter on the packets;
1851
1852         we're exporting PDUs;
1853
1854         we're using any taps that need dissection. */
1855   do_dissection = print_packet_info || rfcode || dfcode || pdu_export_arg ||
1856       tap_listeners_require_dissection();
1857   tshark_debug("tshark: do_dissection = %s", do_dissection ? "TRUE" : "FALSE");
1858
1859   if (cf_name) {
1860     tshark_debug("tshark: Opening capture file: %s", cf_name);
1861     /*
1862      * We're reading a capture file.
1863      */
1864     if (cf_open(&cfile, cf_name, in_file_type, FALSE, &err) != CF_OK) {
1865       epan_cleanup();
1866       return 2;
1867     }
1868
1869     /* Process the packets in the file */
1870     tshark_debug("tshark: invoking load_cap_file() to process the packets");
1871     TRY {
1872 #ifdef HAVE_LIBPCAP
1873       err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type, out_file_name_res,
1874           global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1875           global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1876 #else
1877       err = load_cap_file(&cfile, output_file_name, out_file_type, out_file_name_res, 0, 0);
1878 #endif
1879     }
1880     CATCH(OutOfMemoryError) {
1881       fprintf(stderr,
1882               "Out Of Memory.\n"
1883               "\n"
1884               "Sorry, but TShark has to terminate now.\n"
1885               "\n"
1886               "More information and workarounds can be found at\n"
1887               "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
1888       err = ENOMEM;
1889     }
1890     ENDTRY;
1891     if (err != 0) {
1892       /* We still dump out the results of taps, etc., as we might have
1893          read some packets; however, we exit with an error status. */
1894       exit_status = 2;
1895     }
1896
1897     if (pdu_export_arg) {
1898         err = exp_pdu_close(&exp_pdu_tap_data);
1899         if (err) {
1900             cmdarg_err("%s", wtap_strerror(err));
1901             exit_status = 2;
1902         }
1903         g_free(pdu_export_arg);
1904     }
1905   } else {
1906     tshark_debug("tshark: no capture file specified");
1907     /* No capture file specified, so we're supposed to do a live capture
1908        or get a list of link-layer types for a live capture device;
1909        do we have support for live captures? */
1910 #ifdef HAVE_LIBPCAP
1911     /* if no interface was specified, pick a default */
1912     exit_status = capture_opts_default_iface_if_necessary(&global_capture_opts,
1913         ((prefs_p->capture_device) && (*prefs_p->capture_device != '\0')) ? get_if_name(prefs_p->capture_device) : NULL);
1914     if (exit_status != 0)
1915         return exit_status;
1916
1917     /* if requested, list the link layer types and exit */
1918     if (list_link_layer_types) {
1919         guint i;
1920
1921         /* Get the list of link-layer types for the capture devices. */
1922         for (i = 0; i < global_capture_opts.ifaces->len; i++) {
1923           interface_options  interface_opts;
1924           if_capabilities_t *caps;
1925           char *auth_str = NULL;
1926
1927           interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
1928 #ifdef HAVE_PCAP_REMOTE
1929           if (interface_opts.auth_type == CAPTURE_AUTH_PWD) {
1930               auth_str = g_strdup_printf("%s:%s", interface_opts.auth_username, interface_opts.auth_password);
1931           }
1932 #endif
1933           caps = capture_get_if_capabilities(interface_opts.name, interface_opts.monitor_mode, auth_str, &err_str, NULL);
1934           g_free(auth_str);
1935           if (caps == NULL) {
1936             cmdarg_err("%s", err_str);
1937             g_free(err_str);
1938             return 2;
1939           }
1940           if (caps->data_link_types == NULL) {
1941             cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
1942             return 2;
1943           }
1944           capture_opts_print_if_capabilities(caps, interface_opts.name, interface_opts.monitor_mode);
1945           free_if_capabilities(caps);
1946         }
1947         return 0;
1948     }
1949
1950     /*
1951      * If the standard error isn't a terminal, don't print packet counts,
1952      * as they won't show up on the user's terminal and they'll get in
1953      * the way of error messages in the file (to which we assume the
1954      * standard error was redirected; if it's redirected to the null
1955      * device, there's no point in printing packet counts anyway).
1956      *
1957      * Otherwise, if we're printing packet information and the standard
1958      * output is a terminal (which we assume means the standard output and
1959      * error are going to the same terminal), don't print packet counts,
1960      * as they'll get in the way of the packet information.
1961      *
1962      * Otherwise, if the user specified -q, don't print packet counts.
1963      *
1964      * Otherwise, print packet counts.
1965      *
1966      * XXX - what if the user wants to do a live capture, doesn't want
1967      * to save it to a file, doesn't want information printed for each
1968      * packet, does want some "-z" statistic, and wants packet counts
1969      * so they know whether they're seeing any packets?  -q will
1970      * suppress the information printed for each packet, but it'll
1971      * also suppress the packet counts.
1972      */
1973     if (!ws_isatty(ws_fileno(stderr)))
1974       print_packet_counts = FALSE;
1975     else if (print_packet_info && ws_isatty(ws_fileno(stdout)))
1976       print_packet_counts = FALSE;
1977     else if (quiet)
1978       print_packet_counts = FALSE;
1979     else
1980       print_packet_counts = TRUE;
1981
1982     if (print_packet_info) {
1983       if (!write_preamble(&cfile)) {
1984         show_print_file_io_error(errno);
1985         return 2;
1986       }
1987     }
1988
1989     tshark_debug("tshark: performing live capture");
1990     /*
1991      * XXX - this returns FALSE if an error occurred, but it also
1992      * returns FALSE if the capture stops because a time limit
1993      * was reached (and possibly other limits), so we can't assume
1994      * it means an error.
1995      *
1996      * The capture code is a bit twisty, so it doesn't appear to
1997      * be an easy fix.  We just ignore the return value for now.
1998      * Instead, pass on the exit status from the capture child.
1999      */
2000     capture();
2001     exit_status = global_capture_session.fork_child_status;
2002
2003     if (print_packet_info) {
2004       if (!write_finale()) {
2005         err = errno;
2006         show_print_file_io_error(err);
2007       }
2008     }
2009 #else
2010     /* No - complain. */
2011     cmdarg_err("This version of TShark was not built with support for capturing packets.");
2012     return 2;
2013 #endif
2014   }
2015
2016   g_free(cf_name);
2017
2018   if (cfile.frames != NULL) {
2019     free_frame_data_sequence(cfile.frames);
2020     cfile.frames = NULL;
2021   }
2022
2023   draw_tap_listeners(TRUE);
2024   funnel_dump_all_text_windows();
2025   epan_free(cfile.epan);
2026   epan_cleanup();
2027
2028   output_fields_free(output_fields);
2029   output_fields = NULL;
2030
2031   return exit_status;
2032 }
2033
2034 /*#define USE_BROKEN_G_MAIN_LOOP*/
2035
2036 #ifdef USE_BROKEN_G_MAIN_LOOP
2037   GMainLoop *loop;
2038 #else
2039   gboolean loop_running = FALSE;
2040 #endif
2041   guint32 packet_count = 0;
2042
2043
2044 typedef struct pipe_input_tag {
2045   gint             source;
2046   gpointer         user_data;
2047   ws_process_id   *child_process;
2048   pipe_input_cb_t  input_cb;
2049   guint            pipe_input_id;
2050 #ifdef _WIN32
2051   GMutex          *callback_running;
2052 #endif
2053 } pipe_input_t;
2054
2055 static pipe_input_t pipe_input;
2056
2057 #ifdef _WIN32
2058 /* The timer has expired, see if there's stuff to read from the pipe,
2059    if so, do the callback */
2060 static gint
2061 pipe_timer_cb(gpointer data)
2062 {
2063   HANDLE        handle;
2064   DWORD         avail        = 0;
2065   gboolean      result;
2066   DWORD         childstatus;
2067   pipe_input_t *pipe_input_p = data;
2068   gint          iterations   = 0;
2069
2070   g_mutex_lock (pipe_input_p->callback_running);
2071
2072   /* try to read data from the pipe only 5 times, to avoid blocking */
2073   while(iterations < 5) {
2074     /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
2075
2076     /* Oddly enough although Named pipes don't work on win9x,
2077        PeekNamedPipe does !!! */
2078     handle = (HANDLE) _get_osfhandle (pipe_input_p->source);
2079     result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
2080
2081     /* Get the child process exit status */
2082     GetExitCodeProcess((HANDLE)*(pipe_input_p->child_process),
2083                        &childstatus);
2084
2085     /* If the Peek returned an error, or there are bytes to be read
2086        or the childwatcher thread has terminated then call the normal
2087        callback */
2088     if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
2089
2090       /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
2091
2092       /* And call the real handler */
2093       if (!pipe_input_p->input_cb(pipe_input_p->source, pipe_input_p->user_data)) {
2094         g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
2095         /* pipe closed, return false so that the timer is stopped */
2096         g_mutex_unlock (pipe_input_p->callback_running);
2097         return FALSE;
2098       }
2099     }
2100     else {
2101       /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
2102       /* No data, stop now */
2103       break;
2104     }
2105
2106     iterations++;
2107   }
2108
2109   /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
2110
2111   g_mutex_unlock (pipe_input_p->callback_running);
2112
2113   /* we didn't stopped the timer, so let it run */
2114   return TRUE;
2115 }
2116 #endif
2117
2118
2119 void
2120 pipe_input_set_handler(gint source, gpointer user_data, ws_process_id *child_process, pipe_input_cb_t input_cb)
2121 {
2122
2123   pipe_input.source         = source;
2124   pipe_input.child_process  = child_process;
2125   pipe_input.user_data      = user_data;
2126   pipe_input.input_cb       = input_cb;
2127
2128 #ifdef _WIN32
2129 #if GLIB_CHECK_VERSION(2,31,0)
2130   pipe_input.callback_running = g_malloc(sizeof(GMutex));
2131   g_mutex_init(pipe_input.callback_running);
2132 #else
2133   pipe_input.callback_running = g_mutex_new();
2134 #endif
2135   /* Tricky to use pipes in win9x, as no concept of wait.  NT can
2136      do this but that doesn't cover all win32 platforms.  GTK can do
2137      this but doesn't seem to work over processes.  Attempt to do
2138      something similar here, start a timer and check for data on every
2139      timeout. */
2140   /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
2141   pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
2142 #endif
2143 }
2144
2145 static const nstime_t *
2146 tshark_get_frame_ts(void *data, guint32 frame_num)
2147 {
2148   capture_file *cf = (capture_file *) data;
2149
2150   if (ref && ref->num == frame_num)
2151     return &ref->abs_ts;
2152
2153   if (prev_dis && prev_dis->num == frame_num)
2154     return &prev_dis->abs_ts;
2155
2156   if (prev_cap && prev_cap->num == frame_num)
2157     return &prev_cap->abs_ts;
2158
2159   if (cf->frames) {
2160      frame_data *fd = frame_data_sequence_find(cf->frames, frame_num);
2161
2162      return (fd) ? &fd->abs_ts : NULL;
2163   }
2164
2165   return NULL;
2166 }
2167
2168 static epan_t *
2169 tshark_epan_new(capture_file *cf)
2170 {
2171   epan_t *epan = epan_new();
2172
2173   epan->data = cf;
2174   epan->get_frame_ts = tshark_get_frame_ts;
2175   epan->get_interface_name = cap_file_get_interface_name;
2176   epan->get_user_comment = NULL;
2177
2178   return epan;
2179 }
2180
2181 #ifdef HAVE_LIBPCAP
2182 static gboolean
2183 capture(void)
2184 {
2185   gboolean          ret;
2186   guint             i;
2187   GString          *str;
2188 #ifdef USE_TSHARK_SELECT
2189   fd_set            readfds;
2190 #endif
2191 #ifndef _WIN32
2192   struct sigaction  action, oldaction;
2193 #endif
2194
2195   /* Create new dissection section. */
2196   epan_free(cfile.epan);
2197   cfile.epan = tshark_epan_new(&cfile);
2198
2199 #ifdef _WIN32
2200   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
2201   SetConsoleCtrlHandler(capture_cleanup, TRUE);
2202 #else /* _WIN32 */
2203   /* Catch SIGINT and SIGTERM and, if we get either of them,
2204      clean up and exit.  If SIGHUP isn't being ignored, catch
2205      it too and, if we get it, clean up and exit.
2206
2207      We restart any read that was in progress, so that it doesn't
2208      disrupt reading from the sync pipe.  The signal handler tells
2209      the capture child to finish; it will report that it finished,
2210      or will exit abnormally, so  we'll stop reading from the sync
2211      pipe, pick up the exit status, and quit. */
2212   memset(&action, 0, sizeof(action));
2213   action.sa_handler = capture_cleanup;
2214   action.sa_flags = SA_RESTART;
2215   sigemptyset(&action.sa_mask);
2216   sigaction(SIGTERM, &action, NULL);
2217   sigaction(SIGINT, &action, NULL);
2218   sigaction(SIGHUP, NULL, &oldaction);
2219   if (oldaction.sa_handler == SIG_DFL)
2220     sigaction(SIGHUP, &action, NULL);
2221
2222 #ifdef SIGINFO
2223   /* Catch SIGINFO and, if we get it and we're capturing to a file in
2224      quiet mode, report the number of packets we've captured.
2225
2226      Again, restart any read that was in progress, so that it doesn't
2227      disrupt reading from the sync pipe. */
2228   action.sa_handler = report_counts_siginfo;
2229   action.sa_flags = SA_RESTART;
2230   sigemptyset(&action.sa_mask);
2231   sigaction(SIGINFO, &action, NULL);
2232 #endif /* SIGINFO */
2233 #endif /* _WIN32 */
2234
2235   global_capture_session.state = CAPTURE_PREPARING;
2236
2237   /* Let the user know which interfaces were chosen. */
2238   for (i = 0; i < global_capture_opts.ifaces->len; i++) {
2239     interface_options interface_opts;
2240
2241     interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
2242     interface_opts.descr = get_interface_descriptive_name(interface_opts.name);
2243     global_capture_opts.ifaces = g_array_remove_index(global_capture_opts.ifaces, i);
2244     g_array_insert_val(global_capture_opts.ifaces, i, interface_opts);
2245   }
2246   str = get_iface_list_string(&global_capture_opts, IFLIST_QUOTE_IF_DESCRIPTION);
2247   if (really_quiet == FALSE)
2248     fprintf(stderr, "Capturing on %s\n", str->str);
2249   fflush(stderr);
2250   g_string_free(str, TRUE);
2251
2252   ret = sync_pipe_start(&global_capture_opts, &global_capture_session, &global_info_data, NULL);
2253
2254   if (!ret)
2255     return FALSE;
2256
2257   /* the actual capture loop
2258    *
2259    * XXX - glib doesn't seem to provide any event based loop handling.
2260    *
2261    * XXX - for whatever reason,
2262    * calling g_main_loop_new() ends up in 100% cpu load.
2263    *
2264    * But that doesn't matter: in UNIX we can use select() to find an input
2265    * source with something to do.
2266    *
2267    * But that doesn't matter because we're in a CLI (that doesn't need to
2268    * update a GUI or something at the same time) so it's OK if we block
2269    * trying to read from the pipe.
2270    *
2271    * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
2272    * wrong (but I leave it there in case I am...).
2273    */
2274
2275 #ifdef USE_TSHARK_SELECT
2276   FD_ZERO(&readfds);
2277   FD_SET(pipe_input.source, &readfds);
2278 #endif
2279
2280   loop_running = TRUE;
2281
2282   TRY
2283   {
2284     while (loop_running)
2285     {
2286 #ifdef USE_TSHARK_SELECT
2287       ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
2288
2289       if (ret == -1)
2290       {
2291         fprintf(stderr, "%s: %s\n", "select()", g_strerror(errno));
2292         return TRUE;
2293       } else if (ret == 1) {
2294 #endif
2295         /* Call the real handler */
2296         if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
2297           g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
2298           return FALSE;
2299         }
2300 #ifdef USE_TSHARK_SELECT
2301       }
2302 #endif
2303     }
2304   }
2305   CATCH(OutOfMemoryError) {
2306     fprintf(stderr,
2307             "Out Of Memory.\n"
2308             "\n"
2309             "Sorry, but TShark has to terminate now.\n"
2310             "\n"
2311             "More information and workarounds can be found at\n"
2312             "https://wiki.wireshark.org/KnownBugs/OutOfMemory\n");
2313     exit(1);
2314   }
2315   ENDTRY;
2316   return TRUE;
2317 }
2318
2319 /* capture child detected an error */
2320 void
2321 capture_input_error_message(capture_session *cap_session _U_, char *error_msg, char *secondary_error_msg)
2322 {
2323   cmdarg_err("%s", error_msg);
2324   cmdarg_err_cont("%s", secondary_error_msg);
2325 }
2326
2327
2328 /* capture child detected an capture filter related error */
2329 void
2330 capture_input_cfilter_error_message(capture_session *cap_session, guint i, char *error_message)
2331 {
2332   capture_options *capture_opts = cap_session->capture_opts;
2333   dfilter_t         *rfcode = NULL;
2334   interface_options  interface_opts;
2335
2336   g_assert(i < capture_opts->ifaces->len);
2337   interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2338
2339   if (dfilter_compile(interface_opts.cfilter, &rfcode, NULL) && rfcode != NULL) {
2340     cmdarg_err(
2341       "Invalid capture filter \"%s\" for interface '%s'.\n"
2342       "\n"
2343       "That string looks like a valid display filter; however, it isn't a valid\n"
2344       "capture filter (%s).\n"
2345       "\n"
2346       "Note that display filters and capture filters don't have the same syntax,\n"
2347       "so you can't use most display filter expressions as capture filters.\n"
2348       "\n"
2349       "See the User's Guide for a description of the capture filter syntax.",
2350       interface_opts.cfilter, interface_opts.descr, error_message);
2351     dfilter_free(rfcode);
2352   } else {
2353     cmdarg_err(
2354       "Invalid capture filter \"%s\" for interface '%s'.\n"
2355       "\n"
2356       "That string isn't a valid capture filter (%s).\n"
2357       "See the User's Guide for a description of the capture filter syntax.",
2358       interface_opts.cfilter, interface_opts.descr, error_message);
2359   }
2360 }
2361
2362
2363 /* capture child tells us we have a new (or the first) capture file */
2364 gboolean
2365 capture_input_new_file(capture_session *cap_session, gchar *new_file)
2366 {
2367   capture_options *capture_opts = cap_session->capture_opts;
2368   capture_file *cf = (capture_file *) cap_session->cf;
2369   gboolean is_tempfile;
2370   int      err;
2371
2372   if (cap_session->state == CAPTURE_PREPARING) {
2373     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started.");
2374   }
2375   g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
2376
2377   g_assert(cap_session->state == CAPTURE_PREPARING || cap_session->state == CAPTURE_RUNNING);
2378
2379   /* free the old filename */
2380   if (capture_opts->save_file != NULL) {
2381
2382     /* we start a new capture file, close the old one (if we had one before) */
2383     if (cf->state != FILE_CLOSED) {
2384       if (cf->wth != NULL) {
2385         wtap_close(cf->wth);
2386         cf->wth = NULL;
2387       }
2388       cf->state = FILE_CLOSED;
2389     }
2390
2391     g_free(capture_opts->save_file);
2392     is_tempfile = FALSE;
2393
2394     epan_free(cf->epan);
2395     cf->epan = tshark_epan_new(cf);
2396   } else {
2397     /* we didn't had a save_file before, must be a tempfile */
2398     is_tempfile = TRUE;
2399   }
2400
2401   /* save the new filename */
2402   capture_opts->save_file = g_strdup(new_file);
2403
2404   /* if we are in real-time mode, open the new file now */
2405   if (do_dissection) {
2406     /* this is probably unecessary, but better safe than sorry */
2407     ((capture_file *)cap_session->cf)->open_type = WTAP_TYPE_AUTO;
2408     /* Attempt to open the capture file and set up to read from it. */
2409     switch(cf_open((capture_file *)cap_session->cf, capture_opts->save_file, WTAP_TYPE_AUTO, is_tempfile, &err)) {
2410     case CF_OK:
2411       break;
2412     case CF_ERROR:
2413       /* Don't unlink (delete) the save file - leave it around,
2414          for debugging purposes. */
2415       g_free(capture_opts->save_file);
2416       capture_opts->save_file = NULL;
2417       return FALSE;
2418     }
2419   }
2420
2421   cap_session->state = CAPTURE_RUNNING;
2422
2423   return TRUE;
2424 }
2425
2426
2427 /* capture child tells us we have new packets to read */
2428 void
2429 capture_input_new_packets(capture_session *cap_session, int to_read)
2430 {
2431   gboolean      ret;
2432   int           err;
2433   gchar        *err_info;
2434   gint64        data_offset;
2435   capture_file *cf = (capture_file *)cap_session->cf;
2436   gboolean      filtering_tap_listeners;
2437   guint         tap_flags;
2438
2439 #ifdef SIGINFO
2440   /*
2441    * Prevent a SIGINFO handler from writing to the standard error while
2442    * we're doing so or writing to the standard output; instead, have it
2443    * just set a flag telling us to print that information when we're done.
2444    */
2445   infodelay = TRUE;
2446 #endif /* SIGINFO */
2447
2448   /* Do we have any tap listeners with filters? */
2449   filtering_tap_listeners = have_filtering_tap_listeners();
2450
2451   /* Get the union of the flags for all tap listeners. */
2452   tap_flags = union_of_tap_listener_flags();
2453
2454   if (do_dissection) {
2455     gboolean create_proto_tree;
2456     epan_dissect_t *edt;
2457
2458     if (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
2459         (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2460       create_proto_tree = TRUE;
2461     else
2462       create_proto_tree = FALSE;
2463
2464     /* The protocol tree will be "visible", i.e., printed, only if we're
2465        printing packet details, which is true if we're printing stuff
2466        ("print_packet_info" is true) and we're in verbose mode
2467        ("packet_details" is true). */
2468     edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
2469
2470     while (to_read-- && cf->wth) {
2471       wtap_cleareof(cf->wth);
2472       ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2473       if (ret == FALSE) {
2474         /* read from file failed, tell the capture child to stop */
2475         sync_pipe_stop(cap_session);
2476         wtap_close(cf->wth);
2477         cf->wth = NULL;
2478       } else {
2479         ret = process_packet(cf, edt, data_offset, wtap_phdr(cf->wth),
2480                              wtap_buf_ptr(cf->wth),
2481                              tap_flags);
2482       }
2483       if (ret != FALSE) {
2484         /* packet successfully read and gone through the "Read Filter" */
2485         packet_count++;
2486       }
2487     }
2488
2489     epan_dissect_free(edt);
2490
2491   } else {
2492     /*
2493      * Dumpcap's doing all the work; we're not doing any dissection.
2494      * Count all the packets it wrote.
2495      */
2496     packet_count += to_read;
2497   }
2498
2499   if (print_packet_counts) {
2500       /* We're printing packet counts. */
2501       if (packet_count != 0) {
2502         fprintf(stderr, "\r%u ", packet_count);
2503         /* stderr could be line buffered */
2504         fflush(stderr);
2505       }
2506   }
2507
2508 #ifdef SIGINFO
2509   /*
2510    * Allow SIGINFO handlers to write.
2511    */
2512   infodelay = FALSE;
2513
2514   /*
2515    * If a SIGINFO handler asked us to write out capture counts, do so.
2516    */
2517   if (infoprint)
2518     report_counts();
2519 #endif /* SIGINFO */
2520 }
2521
2522 static void
2523 report_counts(void)
2524 {
2525   if ((print_packet_counts == FALSE) && (really_quiet == FALSE)) {
2526     /* Report the count only if we aren't printing a packet count
2527        as packets arrive. */
2528       fprintf(stderr, "%u packet%s captured\n", packet_count,
2529             plurality(packet_count, "", "s"));
2530   }
2531 #ifdef SIGINFO
2532   infoprint = FALSE; /* we just reported it */
2533 #endif /* SIGINFO */
2534 }
2535
2536 #ifdef SIGINFO
2537 static void
2538 report_counts_siginfo(int signum _U_)
2539 {
2540   int sav_errno = errno;
2541   /* If we've been told to delay printing, just set a flag asking
2542      that we print counts (if we're supposed to), otherwise print
2543      the count of packets captured (if we're supposed to). */
2544   if (infodelay)
2545     infoprint = TRUE;
2546   else
2547     report_counts();
2548   errno = sav_errno;
2549 }
2550 #endif /* SIGINFO */
2551
2552
2553 /* capture child detected any packet drops? */
2554 void
2555 capture_input_drops(capture_session *cap_session _U_, guint32 dropped)
2556 {
2557   if (print_packet_counts) {
2558     /* We're printing packet counts to stderr.
2559        Send a newline so that we move to the line after the packet count. */
2560     fprintf(stderr, "\n");
2561   }
2562
2563   if (dropped != 0) {
2564     /* We're printing packet counts to stderr.
2565        Send a newline so that we move to the line after the packet count. */
2566     fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2567   }
2568 }
2569
2570
2571 /*
2572  * Capture child closed its side of the pipe, report any error and
2573  * do the required cleanup.
2574  */
2575 void
2576 capture_input_closed(capture_session *cap_session, gchar *msg)
2577 {
2578   capture_file *cf = (capture_file *) cap_session->cf;
2579
2580   if (msg != NULL)
2581     fprintf(stderr, "tshark: %s\n", msg);
2582
2583   report_counts();
2584
2585   if (cf != NULL && cf->wth != NULL) {
2586     wtap_close(cf->wth);
2587     if (cf->is_tempfile) {
2588       ws_unlink(cf->filename);
2589     }
2590   }
2591 #ifdef USE_BROKEN_G_MAIN_LOOP
2592   /*g_main_loop_quit(loop);*/
2593   g_main_loop_quit(loop);
2594 #else
2595   loop_running = FALSE;
2596 #endif
2597 }
2598
2599
2600
2601
2602 #ifdef _WIN32
2603 static BOOL WINAPI
2604 capture_cleanup(DWORD ctrltype _U_)
2605 {
2606   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2607      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2608      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2609      like SIGTERM at least when the machine's shutting down.
2610
2611      For now, we handle them all as indications that we should clean up
2612      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2613      way on UNIX.
2614
2615      We must return TRUE so that no other handler - such as one that would
2616      terminate the process - gets called.
2617
2618      XXX - for some reason, typing ^C to TShark, if you run this in
2619      a Cygwin console window in at least some versions of Cygwin,
2620      causes TShark to terminate immediately; this routine gets
2621      called, but the main loop doesn't get a chance to run and
2622      exit cleanly, at least if this is compiled with Microsoft Visual
2623      C++ (i.e., it's a property of the Cygwin console window or Bash;
2624      it happens if TShark is not built with Cygwin - for all I know,
2625      building it with Cygwin may make the problem go away). */
2626
2627   /* tell the capture child to stop */
2628   sync_pipe_stop(&global_capture_session);
2629
2630   /* don't stop our own loop already here, otherwise status messages and
2631    * cleanup wouldn't be done properly. The child will indicate the stop of
2632    * everything by calling capture_input_closed() later */
2633
2634   return TRUE;
2635 }
2636 #else
2637 static void
2638 capture_cleanup(int signum _U_)
2639 {
2640   /* tell the capture child to stop */
2641   sync_pipe_stop(&global_capture_session);
2642
2643   /* don't stop our own loop already here, otherwise status messages and
2644    * cleanup wouldn't be done properly. The child will indicate the stop of
2645    * everything by calling capture_input_closed() later */
2646 }
2647 #endif /* _WIN32 */
2648 #endif /* HAVE_LIBPCAP */
2649
2650 static gboolean
2651 process_packet_first_pass(capture_file *cf, epan_dissect_t *edt,
2652                gint64 offset, struct wtap_pkthdr *whdr,
2653                const guchar *pd)
2654 {
2655   frame_data     fdlocal;
2656   guint32        framenum;
2657   gboolean       passed;
2658
2659   /* The frame number of this packet is one more than the count of
2660      frames in this packet. */
2661   framenum = cf->count + 1;
2662
2663   /* If we're not running a display filter and we're not printing any
2664      packet information, we don't need to do a dissection. This means
2665      that all packets can be marked as 'passed'. */
2666   passed = TRUE;
2667
2668   frame_data_init(&fdlocal, framenum, whdr, offset, cum_bytes);
2669
2670   /* If we're going to print packet information, or we're going to
2671      run a read filter, or display filter, or we're going to process taps, set up to
2672      do a dissection and do so. */
2673   if (edt) {
2674     if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2675         gbl_resolv_flags.transport_name)
2676       /* Grab any resolved addresses */
2677       host_name_lookup_process();
2678
2679     /* If we're running a read filter, prime the epan_dissect_t with that
2680        filter. */
2681     if (cf->rfcode)
2682       epan_dissect_prime_dfilter(edt, cf->rfcode);
2683
2684     if (cf->dfcode)
2685       epan_dissect_prime_dfilter(edt, cf->dfcode);
2686
2687     frame_data_set_before_dissect(&fdlocal, &cf->elapsed_time,
2688                                   &ref, prev_dis);
2689     if (ref == &fdlocal) {
2690       ref_frame = fdlocal;
2691       ref = &ref_frame;
2692     }
2693
2694     epan_dissect_run(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdlocal, pd), &fdlocal, NULL);
2695
2696     /* Run the read filter if we have one. */
2697     if (cf->rfcode)
2698       passed = dfilter_apply_edt(cf->rfcode, edt);
2699   }
2700
2701   if (passed) {
2702     frame_data_set_after_dissect(&fdlocal, &cum_bytes);
2703     prev_cap = prev_dis = frame_data_sequence_add(cf->frames, &fdlocal);
2704
2705     /* If we're not doing dissection then there won't be any dependent frames.
2706      * More importantly, edt.pi.dependent_frames won't be initialized because
2707      * epan hasn't been initialized.
2708      * if we *are* doing dissection, then mark the dependent frames, but only
2709      * if a display filter was given and it matches this packet.
2710      */
2711     if (edt && cf->dfcode) {
2712       if (dfilter_apply_edt(cf->dfcode, edt)) {
2713         g_slist_foreach(edt->pi.dependent_frames, find_and_mark_frame_depended_upon, cf->frames);
2714       }
2715     }
2716
2717     cf->count++;
2718   } else {
2719     /* if we don't add it to the frame_data_sequence, clean it up right now
2720      * to avoid leaks */
2721     frame_data_destroy(&fdlocal);
2722   }
2723
2724   if (edt)
2725     epan_dissect_reset(edt);
2726
2727   return passed;
2728 }
2729
2730 static gboolean
2731 process_packet_second_pass(capture_file *cf, epan_dissect_t *edt, frame_data *fdata,
2732                struct wtap_pkthdr *phdr, Buffer *buf,
2733                guint tap_flags)
2734 {
2735   column_info    *cinfo;
2736   gboolean        passed;
2737
2738   /* If we're not running a display filter and we're not printing any
2739      packet information, we don't need to do a dissection. This means
2740      that all packets can be marked as 'passed'. */
2741   passed = TRUE;
2742
2743   /* If we're going to print packet information, or we're going to
2744      run a read filter, or we're going to process taps, set up to
2745      do a dissection and do so. */
2746   if (edt) {
2747     if (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
2748         gbl_resolv_flags.transport_name)
2749       /* Grab any resolved addresses */
2750       host_name_lookup_process();
2751
2752     /* If we're running a display filter, prime the epan_dissect_t with that
2753        filter. */
2754     if (cf->dfcode)
2755       epan_dissect_prime_dfilter(edt, cf->dfcode);
2756
2757     col_custom_prime_edt(edt, &cf->cinfo);
2758
2759     /* We only need the columns if either
2760          1) some tap needs the columns
2761        or
2762          2) we're printing packet info but we're *not* verbose; in verbose
2763             mode, we print the protocol tree, not the protocol summary.
2764      */
2765     if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
2766       cinfo = &cf->cinfo;
2767     else
2768       cinfo = NULL;
2769
2770     frame_data_set_before_dissect(fdata, &cf->elapsed_time,
2771                                   &ref, prev_dis);
2772     if (ref == fdata) {
2773       ref_frame = *fdata;
2774       ref = &ref_frame;
2775     }
2776
2777     epan_dissect_run_with_taps(edt, cf->cd_t, phdr, frame_tvbuff_new_buffer(fdata, buf), fdata, cinfo);
2778
2779     /* Run the read/display filter if we have one. */
2780     if (cf->dfcode)
2781       passed = dfilter_apply_edt(cf->dfcode, edt);
2782   }
2783
2784   if (passed) {
2785     frame_data_set_after_dissect(fdata, &cum_bytes);
2786     /* Process this packet. */
2787     if (print_packet_info) {
2788       /* We're printing packet information; print the information for
2789          this packet. */
2790       print_packet(cf, edt);
2791
2792       /* The ANSI C standard does not appear to *require* that a line-buffered
2793          stream be flushed to the host environment whenever a newline is
2794          written, it just says that, on such a stream, characters "are
2795          intended to be transmitted to or from the host environment as a
2796          block when a new-line character is encountered".
2797
2798          The Visual C++ 6.0 C implementation doesn't do what is intended;
2799          even if you set a stream to be line-buffered, it still doesn't
2800          flush the buffer at the end of every line.
2801
2802          So, if the "-l" flag was specified, we flush the standard output
2803          at the end of a packet.  This will do the right thing if we're
2804          printing packet summary lines, and, as we print the entire protocol
2805          tree for a single packet without waiting for anything to happen,
2806          it should be as good as line-buffered mode if we're printing
2807          protocol trees.  (The whole reason for the "-l" flag in either
2808          tcpdump or TShark is to allow the output of a live capture to
2809          be piped to a program or script and to have that script see the
2810          information for the packet as soon as it's printed, rather than
2811          having to wait until a standard I/O buffer fills up. */
2812       if (line_buffered)
2813         fflush(stdout);
2814
2815       if (ferror(stdout)) {
2816         show_print_file_io_error(errno);
2817         exit(2);
2818       }
2819     }
2820     prev_dis = fdata;
2821   }
2822   prev_cap = fdata;
2823
2824   if (edt) {
2825     epan_dissect_reset(edt);
2826   }
2827   return passed || fdata->flags.dependent_of_displayed;
2828 }
2829
2830 static int
2831 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2832     gboolean out_file_name_res, int max_packet_count, gint64 max_byte_count)
2833 {
2834   gint         linktype;
2835   int          snapshot_length;
2836   wtap_dumper *pdh;
2837   guint32      framenum;
2838   int          err;
2839   gchar       *err_info = NULL;
2840   gint64       data_offset;
2841   char        *save_file_string = NULL;
2842   gboolean     filtering_tap_listeners;
2843   guint        tap_flags;
2844   GArray                      *shb_hdrs = NULL;
2845   wtapng_iface_descriptions_t *idb_inf = NULL;
2846   GArray                      *nrb_hdrs = NULL;
2847   struct wtap_pkthdr phdr;
2848   Buffer       buf;
2849   epan_dissect_t *edt = NULL;
2850   char                        *shb_user_appl;
2851
2852   wtap_phdr_init(&phdr);
2853
2854   idb_inf = wtap_file_get_idb_info(cf->wth);
2855 #ifdef PCAP_NG_DEFAULT
2856   if (idb_inf->interface_data->len > 1) {
2857     linktype = WTAP_ENCAP_PER_PACKET;
2858   } else {
2859     linktype = wtap_file_encap(cf->wth);
2860   }
2861 #else
2862   linktype = wtap_file_encap(cf->wth);
2863 #endif
2864   if (save_file != NULL) {
2865     /* Get a string that describes what we're writing to */
2866     save_file_string = output_file_description(save_file);
2867
2868     /* Set up to write to the capture file. */
2869     snapshot_length = wtap_snapshot_length(cf->wth);
2870     if (snapshot_length == 0) {
2871       /* Snapshot length of input file not known. */
2872       snapshot_length = WTAP_MAX_PACKET_SIZE;
2873     }
2874     tshark_debug("tshark: snapshot_length = %d", snapshot_length);
2875
2876     shb_hdrs = wtap_file_get_shb_for_new_file(cf->wth);
2877     nrb_hdrs = wtap_file_get_nrb_for_new_file(cf->wth);
2878
2879     /* If we don't have an application name add Tshark */
2880     wtap_optionblock_get_option_string(g_array_index(shb_hdrs, wtap_optionblock_t, 0), OPT_SHB_USERAPPL, &shb_user_appl);
2881     if (shb_user_appl == NULL) {
2882         /* this is free'd by wtap_optionblock_free() later */
2883         wtap_optionblock_set_option_string_format(g_array_index(shb_hdrs, wtap_optionblock_t, 0), OPT_SHB_USERAPPL, "TShark (Wireshark) %s", get_ws_vcs_version_info());
2884     }
2885
2886     if (linktype != WTAP_ENCAP_PER_PACKET &&
2887         out_file_type == WTAP_FILE_TYPE_SUBTYPE_PCAP) {
2888         tshark_debug("tshark: writing PCAP format to %s", save_file);
2889         if (strcmp(save_file, "-") == 0) {
2890           /* Write to the standard output. */
2891           pdh = wtap_dump_open_stdout(out_file_type, linktype,
2892               snapshot_length, FALSE /* compressed */, &err);
2893         } else {
2894           pdh = wtap_dump_open(save_file, out_file_type, linktype,
2895               snapshot_length, FALSE /* compressed */, &err);
2896         }
2897     }
2898     else {
2899         tshark_debug("tshark: writing format type %d, to %s", out_file_type, save_file);
2900         if (strcmp(save_file, "-") == 0) {
2901           /* Write to the standard output. */
2902           pdh = wtap_dump_open_stdout_ng(out_file_type, linktype,
2903               snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
2904         } else {
2905           pdh = wtap_dump_open_ng(save_file, out_file_type, linktype,
2906               snapshot_length, FALSE /* compressed */, shb_hdrs, idb_inf, nrb_hdrs, &err);
2907         }
2908     }
2909
2910     g_free(idb_inf);
2911     idb_inf = NULL;
2912
2913     if (pdh == NULL) {
2914       /* We couldn't set up to write to the capture file. */
2915       switch (err) {
2916
2917       case WTAP_ERR_UNWRITABLE_FILE_TYPE:
2918         cmdarg_err("Capture files can't be written in that format.");
2919         break;
2920
2921       case WTAP_ERR_UNWRITABLE_ENCAP:
2922       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2923         cmdarg_err("The capture file being read can't be written as a "
2924           "\"%s\" file.", wtap_file_type_subtype_short_string(out_file_type));
2925         break;
2926
2927       case WTAP_ERR_CANT_OPEN:
2928         cmdarg_err("The %s couldn't be created for some "
2929           "unknown reason.", save_file_string);
2930         break;
2931
2932       case WTAP_ERR_SHORT_WRITE:
2933         cmdarg_err("A full header couldn't be written to the %s.",
2934                    save_file_string);
2935         break;
2936
2937       default:
2938         cmdarg_err("The %s could not be created: %s.", save_file_string,
2939                    wtap_strerror(err));
2940         break;
2941       }
2942       goto out;
2943     }
2944   } else {
2945     if (print_packet_info) {
2946       if (!write_preamble(cf)) {
2947         err = errno;
2948         show_print_file_io_error(err);
2949         goto out;
2950       }
2951     }
2952     g_free(idb_inf);
2953     idb_inf = NULL;
2954     pdh = NULL;
2955   }
2956
2957   /* Do we have any tap listeners with filters? */
2958   filtering_tap_listeners = have_filtering_tap_listeners();
2959
2960   /* Get the union of the flags for all tap listeners. */
2961   tap_flags = union_of_tap_listener_flags();
2962
2963   if (perform_two_pass_analysis) {
2964     frame_data *fdata;
2965
2966     tshark_debug("tshark: perform_two_pass_analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
2967
2968     /* Allocate a frame_data_sequence for all the frames. */
2969     cf->frames = new_frame_data_sequence();
2970
2971     if (do_dissection) {
2972        gboolean create_proto_tree = FALSE;
2973
2974       /* If we're going to be applying a filter, we'll need to
2975          create a protocol tree against which to apply the filter. */
2976       if (cf->rfcode || cf->dfcode)
2977         create_proto_tree = TRUE;
2978
2979       tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
2980
2981       /* We're not going to display the protocol tree on this pass,
2982          so it's not going to be "visible". */
2983       edt = epan_dissect_new(cf->epan, create_proto_tree, FALSE);
2984     }
2985
2986     tshark_debug("tshark: reading records for first pass");
2987     while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2988       if (process_packet_first_pass(cf, edt, data_offset, wtap_phdr(cf->wth),
2989                          wtap_buf_ptr(cf->wth))) {
2990         /* Stop reading if we have the maximum number of packets;
2991          * When the -c option has not been used, max_packet_count
2992          * starts at 0, which practically means, never stop reading.
2993          * (unless we roll over max_packet_count ?)
2994          */
2995         if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2996           tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
2997                         max_packet_count, data_offset, max_byte_count);
2998           err = 0; /* This is not an error */
2999           break;
3000         }
3001       }
3002     }
3003
3004     if (edt) {
3005       epan_dissect_free(edt);
3006       edt = NULL;
3007     }
3008
3009     /* Close the sequential I/O side, to free up memory it requires. */
3010     wtap_sequential_close(cf->wth);
3011
3012     /* Allow the protocol dissectors to free up memory that they
3013      * don't need after the sequential run-through of the packets. */
3014     postseq_cleanup_all_protocols();
3015
3016     prev_dis = NULL;
3017     prev_cap = NULL;
3018     ws_buffer_init(&buf, 1500);
3019
3020     tshark_debug("tshark: done with first pass");
3021
3022     if (do_dissection) {
3023       gboolean create_proto_tree;
3024
3025       if (cf->dfcode || print_details || filtering_tap_listeners ||
3026          (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
3027            create_proto_tree = TRUE;
3028       else
3029            create_proto_tree = FALSE;
3030
3031       tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3032
3033       /* The protocol tree will be "visible", i.e., printed, only if we're
3034          printing packet details, which is true if we're printing stuff
3035          ("print_packet_info" is true) and we're in verbose mode
3036          ("packet_details" is true). */
3037       edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3038     }
3039
3040     for (framenum = 1; err == 0 && framenum <= cf->count; framenum++) {
3041       fdata = frame_data_sequence_find(cf->frames, framenum);
3042       if (wtap_seek_read(cf->wth, fdata->file_off, &phdr, &buf, &err,
3043                          &err_info)) {
3044         tshark_debug("tshark: invoking process_packet_second_pass() for frame #%d", framenum);
3045         if (process_packet_second_pass(cf, edt, fdata, &phdr, &buf,
3046                                        tap_flags)) {
3047           /* Either there's no read filtering or this packet passed the
3048              filter, so, if we're writing to a capture file, write
3049              this packet out. */
3050           if (pdh != NULL) {
3051             tshark_debug("tshark: writing packet #%d to outfile", framenum);
3052             if (!wtap_dump(pdh, &phdr, ws_buffer_start_ptr(&buf), &err, &err_info)) {
3053               /* Error writing to a capture file */
3054               tshark_debug("tshark: error writing to a capture file (%d)", err);
3055               switch (err) {
3056
3057               case WTAP_ERR_UNWRITABLE_ENCAP:
3058                 /*
3059                  * This is a problem with the particular frame we're writing
3060                  * and the file type and subtype we're writing; note that,
3061                  * and report the frame number and file type/subtype.
3062                  *
3063                  * XXX - framenum is not necessarily the frame number in
3064                  * the input file if there was a read filter.
3065                  */
3066                 fprintf(stderr,
3067                         "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
3068                         framenum, cf->filename,
3069                         wtap_file_type_subtype_short_string(out_file_type));
3070                 break;
3071
3072               case WTAP_ERR_PACKET_TOO_LARGE:
3073                 /*
3074                  * This is a problem with the particular frame we're writing
3075                  * and the file type and subtype we're writing; note that,
3076                  * and report the frame number and file type/subtype.
3077                  *
3078                  * XXX - framenum is not necessarily the frame number in
3079                  * the input file if there was a read filter.
3080                  */
3081                 fprintf(stderr,
3082                         "Frame %u of \"%s\" is too large for a \"%s\" file.\n",
3083                         framenum, cf->filename,
3084                         wtap_file_type_subtype_short_string(out_file_type));
3085                 break;
3086
3087               case WTAP_ERR_UNWRITABLE_REC_TYPE:
3088                 /*
3089                  * This is a problem with the particular record we're writing
3090                  * and the file type and subtype we're writing; note that,
3091                  * and report the record number and file type/subtype.
3092                  *
3093                  * XXX - framenum is not necessarily the record number in
3094                  * the input file if there was a read filter.
3095                  */
3096                 fprintf(stderr,
3097                         "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
3098                         framenum, cf->filename,
3099                         wtap_file_type_subtype_short_string(out_file_type));
3100                 break;
3101
3102               case WTAP_ERR_UNWRITABLE_REC_DATA:
3103                 /*
3104                  * This is a problem with the particular record we're writing
3105                  * and the file type and subtype we're writing; note that,
3106                  * and report the record number and file type/subtype.
3107                  *
3108                  * XXX - framenum is not necessarily the record number in
3109                  * the input file if there was a read filter.
3110                  */
3111                 fprintf(stderr,
3112                         "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
3113                         framenum, cf->filename,
3114                         wtap_file_type_subtype_short_string(out_file_type),
3115                         err_info != NULL ? err_info : "no information supplied");
3116                 g_free(err_info);
3117                 break;
3118
3119               default:
3120                 show_capture_file_io_error(save_file, err, FALSE);
3121                 break;
3122               }
3123               wtap_dump_close(pdh, &err);
3124               wtap_optionblock_array_free(shb_hdrs);
3125               wtap_optionblock_array_free(nrb_hdrs);
3126               exit(2);
3127             }
3128           }
3129         }
3130       }
3131     }
3132
3133     if (edt) {
3134       epan_dissect_free(edt);
3135       edt = NULL;
3136     }
3137
3138     ws_buffer_free(&buf);
3139
3140     tshark_debug("tshark: done with second pass");
3141   }
3142   else {
3143     /* !perform_two_pass_analysis */
3144     framenum = 0;
3145
3146     tshark_debug("tshark: perform one pass analysis, do_dissection=%s", do_dissection ? "TRUE" : "FALSE");
3147
3148     if (do_dissection) {
3149       gboolean create_proto_tree;
3150
3151       if (cf->rfcode || cf->dfcode || print_details || filtering_tap_listeners ||
3152           (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
3153         create_proto_tree = TRUE;
3154       else
3155         create_proto_tree = FALSE;
3156
3157       tshark_debug("tshark: create_proto_tree = %s", create_proto_tree ? "TRUE" : "FALSE");
3158
3159       /* The protocol tree will be "visible", i.e., printed, only if we're
3160          printing packet details, which is true if we're printing stuff
3161          ("print_packet_info" is true) and we're in verbose mode
3162          ("packet_details" is true). */
3163       edt = epan_dissect_new(cf->epan, create_proto_tree, print_packet_info && print_details);
3164     }
3165
3166     while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
3167       framenum++;
3168
3169       tshark_debug("tshark: processing packet #%d", framenum);
3170
3171       if (process_packet(cf, edt, data_offset, wtap_phdr(cf->wth),
3172                          wtap_buf_ptr(cf->wth),
3173                          tap_flags)) {
3174         /* Either there's no read filtering or this packet passed the
3175            filter, so, if we're writing to a capture file, write
3176            this packet out. */
3177         if (pdh != NULL) {
3178           tshark_debug("tshark: writing packet #%d to outfile", framenum);
3179           if (!wtap_dump(pdh, wtap_phdr(cf->wth), wtap_buf_ptr(cf->wth), &err, &err_info)) {
3180             /* Error writing to a capture file */
3181             tshark_debug("tshark: error writing to a capture file (%d)", err);
3182             switch (err) {
3183
3184             case WTAP_ERR_UNWRITABLE_ENCAP:
3185               /*
3186                * This is a problem with the particular frame we're writing
3187                * and the file type and subtype we're writing; note that,
3188                * and report the frame number and file type/subtype.
3189                */
3190               fprintf(stderr,
3191                       "Frame %u of \"%s\" has a network type that can't be saved in a \"%s\" file.\n",
3192                       framenum, cf->filename,
3193                       wtap_file_type_subtype_short_string(out_file_type));
3194               break;
3195
3196             case WTAP_ERR_PACKET_TOO_LARGE:
3197               /*
3198                * This is a problem with the particular frame we're writing
3199                * and the file type and subtype we're writing; note that,
3200                * and report the frame number and file type/subtype.
3201                */
3202               fprintf(stderr,
3203                       "Frame %u of \"%s\" is too large for a \"%s\" file.\n",
3204                       framenum, cf->filename,
3205                       wtap_file_type_subtype_short_string(out_file_type));
3206               break;
3207
3208             case WTAP_ERR_UNWRITABLE_REC_TYPE:
3209               /*
3210                * This is a problem with the particular record we're writing
3211                * and the file type and subtype we're writing; note that,
3212                * and report the record number and file type/subtype.
3213                */
3214               fprintf(stderr,
3215                       "Record %u of \"%s\" has a record type that can't be saved in a \"%s\" file.\n",
3216                       framenum, cf->filename,
3217                       wtap_file_type_subtype_short_string(out_file_type));
3218               break;
3219
3220             case WTAP_ERR_UNWRITABLE_REC_DATA:
3221               /*
3222                * This is a problem with the particular record we're writing
3223                * and the file type and subtype we're writing; note that,
3224                * and report the record number and file type/subtype.
3225                */
3226               fprintf(stderr,
3227                       "Record %u of \"%s\" has data that can't be saved in a \"%s\" file.\n(%s)\n",
3228                       framenum, cf->filename,
3229                       wtap_file_type_subtype_short_string(out_file_type),
3230                       err_info != NULL ? err_info : "no information supplied");
3231               g_free(err_info);
3232               break;
3233
3234             default:
3235               show_capture_file_io_error(save_file, err, FALSE);
3236               break;
3237             }
3238             wtap_dump_close(pdh, &err);
3239             wtap_optionblock_array_free(shb_hdrs);
3240             wtap_optionblock_array_free(nrb_hdrs);
3241             exit(2);
3242           }
3243         }
3244       }
3245       /* Stop reading if we have the maximum number of packets;
3246        * When the -c option has not been used, max_packet_count
3247        * starts at 0, which practically means, never stop reading.
3248        * (unless we roll over max_packet_count ?)
3249        */
3250       if ( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
3251         tshark_debug("tshark: max_packet_count (%d) or max_byte_count (%" G_GINT64_MODIFIER "d/%" G_GINT64_MODIFIER "d) reached",
3252                       max_packet_count, data_offset, max_byte_count);
3253         err = 0; /* This is not an error */
3254         break;
3255       }
3256     }
3257
3258     if (edt) {
3259       epan_dissect_free(edt);
3260       edt = NULL;
3261     }
3262   }
3263
3264   wtap_phdr_cleanup(&phdr);
3265
3266   if (err != 0) {
3267     tshark_debug("tshark: something failed along the line (%d)", err);
3268     /*
3269      * Print a message noting that the read failed somewhere along the line.
3270      *
3271      * If we're printing packet data, and the standard output and error are
3272      * going to the same place, flush the standard output, so everything
3273      * buffered up is written, and then print a newline to the standard error
3274      * before printing the error message, to separate it from the packet
3275      * data.  (Alas, that only works on UN*X; st_dev is meaningless, and
3276      * the _fstat() documentation at Microsoft doesn't indicate whether
3277      * st_ino is even supported.)
3278      */
3279 #ifndef _WIN32
3280     if (print_packet_info) {
3281       ws_statb64 stat_stdout, stat_stderr;
3282
3283       if (ws_fstat64(1, &stat_stdout) == 0 && ws_fstat64(2, &stat_stderr) == 0) {
3284         if (stat_stdout.st_dev == stat_stderr.st_dev &&
3285             stat_stdout.st_ino == stat_stderr.st_ino) {
3286           fflush(stdout);
3287           fprintf(stderr, "\n");
3288         }
3289       }
3290     }
3291 #endif
3292     switch (err) {
3293
3294     case WTAP_ERR_UNSUPPORTED:
3295       cmdarg_err("The file \"%s\" contains record data that TShark doesn't support.\n(%s)",
3296                  cf->filename,
3297                  err_info != NULL ? err_info : "no information supplied");
3298       g_free(err_info);
3299       break;
3300
3301     case WTAP_ERR_SHORT_READ:
3302       cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
3303                  cf->filename);
3304       break;
3305
3306     case WTAP_ERR_BAD_FILE:
3307       cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
3308                  cf->filename,
3309                  err_info != NULL ? err_info : "no information supplied");
3310       g_free(err_info);
3311       break;
3312
3313     case WTAP_ERR_DECOMPRESS:
3314       cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n"
3315                  "(%s)", cf->filename,
3316                  err_info != NULL ? err_info : "no information supplied");
3317       g_free(err_info);
3318       break;
3319
3320     default:
3321       cmdarg_err("An error occurred while reading the file \"%s\": %s.",
3322                  cf->filename, wtap_strerror(err));
3323       break;
3324     }
3325     if (save_file != NULL) {
3326       /* Now close the capture file. */
3327       if (!wtap_dump_close(pdh, &err))
3328         show_capture_file_io_error(save_file, err, TRUE);
3329     }
3330   } else {
3331     if (save_file != NULL) {
3332       if (pdh && out_file_name_res) {
3333         if (!wtap_dump_set_addrinfo_list(pdh, get_addrinfo_list())) {
3334           cmdarg_err("The file format \"%s\" doesn't support name resolution information.",
3335                      wtap_file_type_subtype_short_string(out_file_type));
3336         }
3337       }
3338       /* Now close the capture file. */
3339       if (!wtap_dump_close(pdh, &err))
3340         show_capture_file_io_error(save_file, err, TRUE);
3341     } else {
3342       if (print_packet_info) {
3343         if (!write_finale()) {
3344           err = errno;
3345           show_print_file_io_error(err);
3346         }
3347       }
3348     }
3349   }
3350
3351 out:
3352   wtap_close(cf->wth);
3353   cf->wth = NULL;
3354
3355   g_free(save_file_string);
3356   wtap_optionblock_array_free(shb_hdrs);
3357   wtap_optionblock_array_free(nrb_hdrs);
3358
3359   return err;
3360 }
3361
3362 static gboolean
3363 process_packet(capture_file *cf, epan_dissect_t *edt, gint64 offset, struct wtap_pkthdr *whdr,
3364                const guchar *pd, guint tap_flags)
3365 {
3366   frame_data      fdata;
3367   column_info    *cinfo;
3368   gboolean        passed;
3369
3370   /* Count this packet. */
3371   cf->count++;
3372
3373   /* If we're not running a display filter and we're not printing any
3374      packet information, we don't need to do a dissection. This means
3375      that all packets can be marked as 'passed'. */
3376   passed = TRUE;
3377
3378   frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
3379
3380   /* If we're going to print packet information, or we're going to
3381      run a read filter, or we're going to process taps, set up to
3382      do a dissection and do so. */
3383   if (edt) {
3384     if (print_packet_info && (gbl_resolv_flags.mac_name || gbl_resolv_flags.network_name ||
3385         gbl_resolv_flags.transport_name))
3386       /* Grab any resolved addresses */
3387       host_name_lookup_process();
3388
3389     /* If we're running a filter, prime the epan_dissect_t with that
3390        filter. */
3391     if (cf->dfcode)
3392       epan_dissect_prime_dfilter(edt, cf->dfcode);
3393
3394     col_custom_prime_edt(edt, &cf->cinfo);
3395
3396     /* We only need the columns if either
3397          1) some tap needs the columns
3398        or
3399          2) we're printing packet info but we're *not* verbose; in verbose
3400             mode, we print the protocol tree, not the protocol summary.
3401        or
3402          3) there is a column mapped as an individual field */
3403     if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && print_summary) || output_fields_has_cols(output_fields))
3404       cinfo = &cf->cinfo;
3405     else
3406       cinfo = NULL;
3407
3408     frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
3409                                   &ref, prev_dis);
3410     if (ref == &fdata) {
3411       ref_frame = fdata;
3412       ref = &ref_frame;
3413     }
3414
3415     epan_dissect_run_with_taps(edt, cf->cd_t, whdr, frame_tvbuff_new(&fdata, pd), &fdata, cinfo);
3416
3417     /* Run the filter if we have it. */
3418     if (cf->dfcode)
3419       passed = dfilter_apply_edt(cf->dfcode, edt);
3420   }
3421
3422   if (passed) {
3423     frame_data_set_after_dissect(&fdata, &cum_bytes);
3424
3425     /* Process this packet. */
3426     if (print_packet_info) {
3427       /* We're printing packet information; print the information for
3428          this packet. */
3429       print_packet(cf, edt);
3430
3431       /* The ANSI C standard does not appear to *require* that a line-buffered
3432          stream be flushed to the host environment whenever a newline is
3433          written, it just says that, on such a stream, characters "are
3434          intended to be transmitted to or from the host environment as a
3435          block when a new-line character is encountered".
3436
3437          The Visual C++ 6.0 C implementation doesn't do what is intended;
3438          even if you set a stream to be line-buffered, it still doesn't
3439          flush the buffer at the end of every line.
3440
3441          So, if the "-l" flag was specified, we flush the standard output
3442          at the end of a packet.  This will do the right thing if we're
3443          printing packet summary lines, and, as we print the entire protocol
3444          tree for a single packet without waiting for anything to happen,
3445          it should be as good as line-buffered mode if we're printing
3446          protocol trees.  (The whole reason for the "-l" flag in either
3447          tcpdump or TShark is to allow the output of a live capture to
3448          be piped to a program or script and to have that script see the
3449          information for the packet as soon as it's printed, rather than
3450          having to wait until a standard I/O buffer fills up. */
3451       if (line_buffered)
3452         fflush(stdout);
3453
3454       if (ferror(stdout)) {
3455         show_print_file_io_error(errno);
3456         exit(2);
3457       }
3458     }
3459
3460     /* this must be set after print_packet() [bug #8160] */
3461     prev_dis_frame = fdata;
3462     prev_dis = &prev_dis_frame;
3463   }
3464
3465   prev_cap_frame = fdata;
3466   prev_cap = &prev_cap_frame;
3467
3468   if (edt) {
3469     epan_dissect_reset(edt);
3470     frame_data_destroy(&fdata);
3471   }
3472   return passed;
3473 }
3474
3475 static gboolean
3476 write_preamble(capture_file *cf)
3477 {
3478   switch (output_action) {
3479
3480   case WRITE_TEXT:
3481     return print_preamble(print_stream, cf->filename, get_ws_vcs_version_info());
3482
3483   case WRITE_XML:
3484     if (print_details)
3485       write_pdml_preamble(stdout, cf->filename);
3486     else
3487       write_psml_preamble(&cf->cinfo, stdout);
3488     return !ferror(stdout);
3489
3490   case WRITE_FIELDS:
3491     write_fields_preamble(output_fields, stdout);
3492     return !ferror(stdout);
3493
3494   case WRITE_JSON:
3495     write_json_preamble(stdout);
3496     return !ferror(stdout);
3497
3498   case WRITE_EK:
3499     return !ferror(stdout);
3500
3501   default:
3502     g_assert_not_reached();
3503     return FALSE;
3504   }
3505 }
3506
3507 static char *
3508 get_line_buf(size_t len)
3509 {
3510   static char   *line_bufp    = NULL;
3511   static size_t  line_buf_len = 256;
3512   size_t         new_line_buf_len;
3513
3514   for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
3515        new_line_buf_len *= 2)
3516     ;
3517   if (line_bufp == NULL) {
3518     line_buf_len = new_line_buf_len;
3519     line_bufp = (char *)g_malloc(line_buf_len + 1);
3520   } else {
3521     if (new_line_buf_len > line_buf_len) {
3522       line_buf_len = new_line_buf_len;
3523       line_bufp = (char *)g_realloc(line_bufp, line_buf_len + 1);
3524     }
3525   }
3526   return line_bufp;
3527 }
3528
3529 static inline void
3530 put_string(char *dest, const char *str, size_t str_len)
3531 {
3532   memcpy(dest, str, str_len);
3533   dest[str_len] = '\0';
3534 }
3535
3536 static inline void
3537 put_spaces_string(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3538 {
3539   size_t i;
3540
3541   for (i = str_len; i < str_with_spaces; i++)
3542     *dest++ = ' ';
3543
3544   put_string(dest, str, str_len);
3545 }
3546
3547 static inline void
3548 put_string_spaces(char *dest, const char *str, size_t str_len, size_t str_with_spaces)
3549 {
3550   size_t i;
3551
3552   memcpy(dest, str, str_len);
3553   for (i = str_len; i < str_with_spaces; i++)
3554     dest[i] = ' ';
3555
3556   dest[str_with_spaces] = '\0';
3557 }
3558
3559 static gboolean
3560 print_columns(capture_file *cf)
3561 {
3562   char   *line_bufp;
3563   int     i;
3564   size_t  buf_offset;
3565   size_t  column_len;
3566   size_t  col_len;
3567   col_item_t* col_item;
3568
3569   line_bufp = get_line_buf(256);
3570   buf_offset = 0;
3571   *line_bufp = '\0';
3572   for (i = 0; i < cf->cinfo.num_cols; i++) {
3573     col_item = &cf->cinfo.columns[i];
3574     /* Skip columns not marked as visible. */
3575     if (!get_column_visible(i))
3576       continue;
3577     switch (col_item->col_fmt) {
3578     case COL_NUMBER:
3579       column_len = col_len = strlen(col_item->col_data);
3580       if (column_len < 3)
3581         column_len = 3;
3582       line_bufp = get_line_buf(buf_offset + column_len);
3583       put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3584       break;
3585
3586     case COL_CLS_TIME:
3587     case COL_REL_TIME:
3588     case COL_ABS_TIME:
3589     case COL_ABS_YMD_TIME:  /* XXX - wider */
3590     case COL_ABS_YDOY_TIME: /* XXX - wider */
3591     case COL_UTC_TIME:
3592     case COL_UTC_YMD_TIME:  /* XXX - wider */
3593     case COL_UTC_YDOY_TIME: /* XXX - wider */
3594       column_len = col_len = strlen(col_item->col_data);
3595       if (column_len < 10)
3596         column_len = 10;
3597       line_bufp = get_line_buf(buf_offset + column_len);
3598       put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3599       break;
3600
3601     case COL_DEF_SRC:
3602     case COL_RES_SRC:
3603     case COL_UNRES_SRC:
3604     case COL_DEF_DL_SRC:
3605     case COL_RES_DL_SRC:
3606     case COL_UNRES_DL_SRC:
3607     case COL_DEF_NET_SRC:
3608     case COL_RES_NET_SRC:
3609     case COL_UNRES_NET_SRC:
3610       column_len = col_len = strlen(col_item->col_data);
3611       if (column_len < 12)
3612         column_len = 12;
3613       line_bufp = get_line_buf(buf_offset + column_len);
3614       put_spaces_string(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3615       break;
3616
3617     case COL_DEF_DST:
3618     case COL_RES_DST:
3619     case COL_UNRES_DST:
3620     case COL_DEF_DL_DST:
3621     case COL_RES_DL_DST:
3622     case COL_UNRES_DL_DST:
3623     case COL_DEF_NET_DST:
3624     case COL_RES_NET_DST:
3625     case COL_UNRES_NET_DST:
3626       column_len = col_len = strlen(col_item->col_data);
3627       if (column_len < 12)
3628         column_len = 12;
3629       line_bufp = get_line_buf(buf_offset + column_len);
3630       put_string_spaces(line_bufp + buf_offset, col_item->col_data, col_len, column_len);
3631       break;
3632
3633     default:
3634       column_len = strlen(col_item->col_data);
3635       line_bufp = get_line_buf(buf_offset + column_len);
3636       put_string(line_bufp + buf_offset, col_item->col_data, column_len);
3637       break;
3638     }
3639     buf_offset += column_len;
3640     if (i != cf->cinfo.num_cols - 1) {
3641       /*
3642        * This isn't the last column, so we need to print a
3643        * separator between this column and the next.
3644        *
3645        * If we printed a network source and are printing a
3646        * network destination of the same type next, separate
3647        * them with a UTF-8 right arrow; if we printed a network
3648        * destination and are printing a network source of the same
3649        * type next, separate them with a UTF-8 left arrow;
3650        * otherwise separate them with a space.
3651        *
3652        * We add enough space to the buffer for " \xe2\x86\x90 "
3653        * or " \xe2\x86\x92 ", even if we're only adding " ".
3654        */
3655       line_bufp = get_line_buf(buf_offset + 5);
3656       switch (col_item->col_fmt) {
3657
3658       case COL_DEF_SRC:
3659       case COL_RES_SRC:
3660       case COL_UNRES_SRC:
3661         switch (cf->cinfo.columns[i+1].col_fmt) {
3662
3663         case COL_DEF_DST:
3664         case COL_RES_DST:
3665         case COL_UNRES_DST:
3666           put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3667           buf_offset += 5;
3668           break;
3669
3670         default:
3671           put_string(line_bufp + buf_offset, " ", 1);
3672           buf_offset += 1;
3673           break;
3674         }
3675         break;
3676
3677       case COL_DEF_DL_SRC:
3678       case COL_RES_DL_SRC:
3679       case COL_UNRES_DL_SRC:
3680         switch (cf->cinfo.columns[i+1].col_fmt) {
3681
3682         case COL_DEF_DL_DST:
3683         case COL_RES_DL_DST:
3684         case COL_UNRES_DL_DST:
3685           put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3686           buf_offset += 5;
3687           break;
3688
3689         default:
3690           put_string(line_bufp + buf_offset, " ", 1);
3691           buf_offset += 1;
3692           break;
3693         }
3694         break;
3695
3696       case COL_DEF_NET_SRC:
3697       case COL_RES_NET_SRC:
3698       case COL_UNRES_NET_SRC:
3699         switch (cf->cinfo.columns[i+1].col_fmt) {
3700
3701         case COL_DEF_NET_DST:
3702         case COL_RES_NET_DST:
3703         case COL_UNRES_NET_DST:
3704           put_string(line_bufp + buf_offset, " " UTF8_RIGHTWARDS_ARROW " ", 5);
3705           buf_offset += 5;
3706           break;
3707
3708         default:
3709           put_string(line_bufp + buf_offset, " ", 1);
3710           buf_offset += 1;
3711           break;
3712         }
3713         break;
3714
3715       case COL_DEF_DST:
3716       case COL_RES_DST:
3717       case COL_UNRES_DST:
3718         switch (cf->cinfo.columns[i+1].col_fmt) {
3719
3720         case COL_DEF_SRC:
3721         case COL_RES_SRC:
3722         case COL_UNRES_SRC:
3723           put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3724           buf_offset += 5;
3725           break;
3726
3727         default:
3728           put_string(line_bufp + buf_offset, " ", 1);
3729           buf_offset += 1;
3730           break;
3731         }
3732         break;
3733
3734       case COL_DEF_DL_DST:
3735       case COL_RES_DL_DST:
3736       case COL_UNRES_DL_DST:
3737         switch (cf->cinfo.columns[i+1].col_fmt) {
3738
3739         case COL_DEF_DL_SRC:
3740         case COL_RES_DL_SRC:
3741         case COL_UNRES_DL_SRC:
3742           put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3743           buf_offset += 5;
3744           break;
3745
3746         default:
3747           put_string(line_bufp + buf_offset, " ", 1);
3748           buf_offset += 1;
3749           break;
3750         }
3751         break;
3752
3753       case COL_DEF_NET_DST:
3754       case COL_RES_NET_DST:
3755       case COL_UNRES_NET_DST:
3756         switch (cf->cinfo.columns[i+1].col_fmt) {
3757
3758         case COL_DEF_NET_SRC:
3759         case COL_RES_NET_SRC:
3760         case COL_UNRES_NET_SRC:
3761           put_string(line_bufp + buf_offset, " " UTF8_LEFTWARDS_ARROW " ", 5);
3762           buf_offset += 5;
3763           break;
3764
3765         default:
3766           put_string(line_bufp + buf_offset, " ", 1);
3767           buf_offset += 1;
3768           break;
3769         }
3770         break;
3771
3772       default:
3773         put_string(line_bufp + buf_offset, " ", 1);
3774         buf_offset += 1;
3775         break;
3776       }
3777     }
3778   }
3779   return print_line(print_stream, 0, line_bufp);
3780 }
3781
3782 static gboolean
3783 print_packet(capture_file *cf, epan_dissect_t *edt)
3784 {
3785   print_args_t print_args;
3786
3787   if (print_summary || output_fields_has_cols(output_fields)) {
3788     /* Just fill in the columns. */
3789     epan_dissect_fill_in_columns(edt, FALSE, TRUE);
3790
3791     if (print_summary) {
3792       /* Now print them. */
3793       switch (output_action) {
3794
3795       case WRITE_TEXT:
3796         if (!print_columns(cf))
3797           return FALSE;
3798         break;
3799
3800       case WRITE_XML:
3801         write_psml_columns(edt, stdout);
3802         return !ferror(stdout);
3803       case WRITE_FIELDS: /*No non-verbose "fields" format */
3804       case WRITE_JSON:
3805       case WRITE_EK:
3806         g_assert_not_reached();
3807         break;
3808       }
3809     }
3810   }
3811   if (print_details) {
3812     /* Print the information in the protocol tree. */
3813     switch (output_action) {
3814
3815     case WRITE_TEXT:
3816       /* Only initialize the fields that are actually used in proto_tree_print.
3817        * This is particularly important for .range, as that's heap memory which
3818        * we would otherwise have to g_free().
3819       print_args.to_file = TRUE;
3820       print_args.format = print_format;
3821       print_args.print_summary = print_summary;
3822       print_args.print_formfeed = FALSE;
3823       packet_range_init(&print_args.range, &cfile);
3824       */
3825       print_args.print_hex = print_hex;
3826       print_args.print_dissections = print_details ? print_dissections_expanded : print_dissections_none;
3827
3828       if (!proto_tree_print(&print_args, edt, output_only_tables, print_stream))
3829         return FALSE;
3830       if (!print_hex) {
3831         if (!print_line(print_stream, 0, separator))
3832           return FALSE;
3833       }
3834       break;
3835
3836     case WRITE_XML:
3837       write_pdml_proto_tree(protocolfilter, edt, stdout);
3838       printf("\n");
3839       return !ferror(stdout);
3840     case WRITE_FIELDS:
3841       write_fields_proto_tree(output_fields, edt, &cf->cinfo, stdout);
3842       printf("\n");
3843       return !ferror(stdout);
3844     case WRITE_JSON:
3845       print_args.print_hex = print_hex;
3846       write_json_proto_tree(&print_args, protocolfilter, edt, stdout);
3847       printf("\n");
3848       return !ferror(stdout);
3849     case WRITE_EK:
3850       print_args.print_hex = print_hex;
3851       write_ek_proto_tree(&print_args, protocolfilter, edt, stdout);
3852       printf("\n");
3853       return !ferror(stdout);
3854     }
3855   }
3856   if (print_hex) {
3857     if (print_summary || print_details) {
3858       if (!print_line(print_stream, 0, ""))
3859         return FALSE;
3860     }
3861     if (!print_hex_data(print_stream, edt))
3862       return FALSE;
3863     if (!print_line(print_stream, 0, separator))
3864       return FALSE;
3865   }
3866   return TRUE;
3867 }
3868
3869 static gboolean
3870 write_finale(void)
3871 {
3872   switch (output_action) {
3873
3874   case WRITE_TEXT:
3875     return print_finale(print_stream);
3876
3877   case WRITE_XML:
3878     if (print_details)
3879       write_pdml_finale(stdout);
3880     else
3881       write_psml_finale(stdout);
3882     return !ferror(stdout);
3883
3884   case WRITE_FIELDS:
3885     write_fields_finale(output_fields, stdout);
3886     return !ferror(stdout);
3887
3888   case WRITE_JSON:
3889     write_json_finale(stdout);
3890     return !ferror(stdout);
3891
3892   case WRITE_EK:
3893     return !ferror(stdout);
3894
3895   default:
3896     g_assert_not_reached();
3897     return FALSE;
3898   }
3899 }
3900
3901 cf_status_t
3902 cf_open(capture_file *cf, const char *fname, unsigned int type, gboolean is_tempfile, int *err)
3903 {
3904   wtap  *wth;
3905   gchar *err_info;
3906   char   err_msg[2048+1];
3907
3908   wth = wtap_open_offline(fname, type, err, &err_info, perform_two_pass_analysis);
3909   if (wth == NULL)
3910     goto fail;
3911
3912   /* The open succeeded.  Fill in the information for this file. */
3913
3914   /* Create new epan session for dissection. */
3915   epan_free(cf->epan);
3916   cf->epan = tshark_epan_new(cf);
3917
3918   cf->wth = wth;
3919   cf->f_datalen = 0; /* not used, but set it anyway */
3920
3921   /* Set the file name because we need it to set the follow stream filter.
3922      XXX - is that still true?  We need it for other reasons, though,
3923      in any case. */
3924   cf->filename = g_strdup(fname);
3925
3926   /* Indicate whether it's a permanent or temporary file. */
3927   cf->is_tempfile = is_tempfile;
3928
3929   /* No user changes yet. */
3930   cf->unsaved_changes = FALSE;
3931
3932   cf->cd_t      = wtap_file_type_subtype(cf->wth);
3933   cf->open_type = type;
3934   cf->count     = 0;
3935   cf->drops_known = FALSE;
3936   cf->drops     = 0;
3937   cf->snap      = wtap_snapshot_length(cf->wth);
3938   if (cf->snap == 0) {
3939     /* Snapshot length not known. */
3940     cf->has_snap = FALSE;
3941     cf->snap = WTAP_MAX_PACKET_SIZE;
3942   } else
3943     cf->has_snap = TRUE;
3944   nstime_set_zero(&cf->elapsed_time);
3945   ref = NULL;
3946   prev_dis = NULL;
3947   prev_cap = NULL;
3948
3949   cf->state = FILE_READ_IN_PROGRESS;
3950
3951   wtap_set_cb_new_ipv4(cf->wth, add_ipv4_name);
3952   wtap_set_cb_new_ipv6(cf->wth, (wtap_new_ipv6_callback_t) add_ipv6_name);
3953
3954   return CF_OK;
3955
3956 fail:
3957   g_snprintf(err_msg, sizeof err_msg,
3958              cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3959   cmdarg_err("%s", err_msg);
3960   return CF_ERROR;
3961 }
3962
3963 static void
3964 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
3965 {
3966   char *save_file_string;
3967
3968   save_file_string = output_file_description(fname);
3969
3970   switch (err) {
3971
3972   case ENOSPC:
3973     cmdarg_err("Not all the packets could be written to the %s because there is "
3974                "no space left on the file system.",
3975                save_file_string);
3976     break;
3977
3978 #ifdef EDQUOT
3979   case EDQUOT:
3980     cmdarg_err("Not all the packets could be written to the %s because you are "
3981                "too close to, or over your disk quota.",
3982                save_file_string);
3983   break;
3984 #endif
3985
3986   case WTAP_ERR_CANT_CLOSE:
3987     cmdarg_err("The %s couldn't be closed for some unknown reason.",
3988                save_file_string);
3989     break;
3990
3991   case WTAP_ERR_SHORT_WRITE:
3992     cmdarg_err("Not all the packets could be written to the %s.",
3993                save_file_string);
3994     break;
3995
3996   default:
3997     if (is_close) {
3998       cmdarg_err("The %s could not be closed: %s.", save_file_string,
3999                  wtap_strerror(err));
4000     } else {
4001       cmdarg_err("An error occurred while writing to the %s: %s.",
4002                  save_file_string, wtap_strerror(err));
4003     }
4004     break;
4005   }
4006   g_free(save_file_string);
4007 }
4008
4009 static void
4010 show_print_file_io_error(int err)
4011 {
4012   switch (err) {
4013
4014   case ENOSPC:
4015     cmdarg_err("Not all the packets could be printed because there is "
4016 "no space left on the file system.");
4017     break;
4018
4019 #ifdef EDQUOT
4020   case EDQUOT:
4021     cmdarg_err("Not all the packets could be printed because you are "
4022 "too close to, or over your disk quota.");
4023   break;
4024 #endif
4025
4026   default:
4027     cmdarg_err("An error occurred while printing packets: %s.",
4028       g_strerror(err));
4029     break;
4030   }
4031 }
4032
4033 static const char *
4034 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
4035                       int file_type)
4036 {
4037   const char *errmsg;
4038   static char errmsg_errno[1024+1];
4039
4040   if (err < 0) {
4041     /* Wiretap error. */
4042     switch (err) {
4043
4044     case WTAP_ERR_NOT_REGULAR_FILE:
4045       errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
4046       break;
4047
4048     case WTAP_ERR_RANDOM_OPEN_PIPE:
4049       /* Seen only when opening a capture file for reading. */
4050       errmsg = "The file \"%s\" is a pipe or FIFO; TShark can't read pipe or FIFO files in two-pass mode.";
4051       break;
4052
4053     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
4054       /* Seen only when opening a capture file for reading. */
4055       errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
4056       break;
4057
4058     case WTAP_ERR_UNSUPPORTED:
4059       /* Seen only when opening a capture file for reading. */
4060       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4061                  "The file \"%%s\" contains record data that TShark doesn't support.\n"
4062                  "(%s)",
4063                  err_info != NULL ? err_info : "no information supplied");
4064       g_free(err_info);
4065       errmsg = errmsg_errno;
4066       break;
4067
4068     case WTAP_ERR_CANT_WRITE_TO_PIPE:
4069       /* Seen only when opening a capture file for writing. */
4070       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4071                  "The file \"%%s\" is a pipe, and \"%s\" capture files can't be "
4072                  "written to a pipe.", wtap_file_type_subtype_short_string(file_type));
4073       errmsg = errmsg_errno;
4074       break;
4075
4076     case WTAP_ERR_UNWRITABLE_FILE_TYPE:
4077       /* Seen only when opening a capture file for writing. */
4078       errmsg = "TShark doesn't support writing capture files in that format.";
4079       break;
4080
4081     case WTAP_ERR_UNWRITABLE_ENCAP:
4082       /* Seen only when opening a capture file for writing. */
4083       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4084                  "TShark can't save this capture as a \"%s\" file.",
4085                  wtap_file_type_subtype_short_string(file_type));
4086       errmsg = errmsg_errno;
4087       break;
4088
4089     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
4090       if (for_writing) {
4091         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4092                    "TShark can't save this capture as a \"%s\" file.",
4093                    wtap_file_type_subtype_short_string(file_type));
4094         errmsg = errmsg_errno;
4095       } else
4096         errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
4097       break;
4098
4099     case WTAP_ERR_BAD_FILE:
4100       /* Seen only when opening a capture file for reading. */
4101       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4102                  "The file \"%%s\" appears to be damaged or corrupt.\n"
4103                  "(%s)",
4104                  err_info != NULL ? err_info : "no information supplied");
4105       g_free(err_info);
4106       errmsg = errmsg_errno;
4107       break;
4108
4109     case WTAP_ERR_CANT_OPEN:
4110       if (for_writing)
4111         errmsg = "The file \"%s\" could not be created for some unknown reason.";
4112       else
4113         errmsg = "The file \"%s\" could not be opened for some unknown reason.";
4114       break;
4115
4116     case WTAP_ERR_SHORT_READ:
4117       errmsg = "The file \"%s\" appears to have been cut short"
4118                " in the middle of a packet or other data.";
4119       break;
4120
4121     case WTAP_ERR_SHORT_WRITE:
4122       errmsg = "A full header couldn't be written to the file \"%s\".";
4123       break;
4124
4125     case WTAP_ERR_COMPRESSION_NOT_SUPPORTED:
4126       errmsg = "This file type cannot be written as a compressed file.";
4127       break;
4128
4129     case WTAP_ERR_DECOMPRESS:
4130       /* Seen only when opening a capture file for reading. */
4131       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4132                  "The compressed file \"%%s\" appears to be damaged or corrupt.\n"
4133                  "(%s)",
4134                  err_info != NULL ? err_info : "no information supplied");
4135       g_free(err_info);
4136       errmsg = errmsg_errno;
4137       break;
4138
4139     default:
4140       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
4141                  "The file \"%%s\" could not be %s: %s.",
4142                  for_writing ? "created" : "opened",
4143                  wtap_strerror(err));
4144       errmsg = errmsg_errno;
4145       break;
4146     }
4147   } else
4148     errmsg = file_open_error_message(err, for_writing);
4149   return errmsg;
4150 }
4151
4152 /*
4153  * Open/create errors are reported with an console message in TShark.
4154  */
4155 static void
4156 open_failure_message(const char *filename, int err, gboolean for_writing)
4157 {
4158   fprintf(stderr, "tshark: ");
4159   fprintf(stderr, file_open_error_message(err, for_writing), filename);
4160   fprintf(stderr, "\n");
4161 }
4162
4163 /*
4164  * General errors are reported with an console message in TShark.
4165  */
4166 static void
4167 failure_message(const char *msg_format, va_list ap)
4168 {
4169   fprintf(stderr, "tshark: ");
4170   vfprintf(stderr, msg_format, ap);
4171   fprintf(stderr, "\n");
4172 }
4173
4174 /*
4175  * Read errors are reported with an console message in TShark.
4176  */
4177 static void
4178 read_failure_message(const char *filename, int err)
4179 {
4180   cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
4181           filename, g_strerror(err));
4182 }
4183
4184 /*
4185  * Write errors are reported with an console message in TShark.
4186  */
4187 static void
4188 write_failure_message(const char *filename, int err)
4189 {
4190   cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
4191           filename, g_strerror(err));
4192 }
4193
4194 /*
4195  * Report additional information for an error in command-line arguments.
4196  */
4197 static void
4198 failure_message_cont(const char *msg_format, va_list ap)
4199 {
4200   vfprintf(stderr, msg_format, ap);
4201   fprintf(stderr, "\n");
4202 }
4203
4204 /*
4205  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
4206  *
4207  * Local variables:
4208  * c-basic-offset: 2
4209  * tab-width: 8
4210  * indent-tabs-mode: nil
4211  * End:
4212  *
4213  * vi: set shiftwidth=2 tabstop=8 expandtab:
4214  * :indentSize=2:tabSize=8:noTabs=true:
4215  */