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