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