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