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