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