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