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