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