nexmon – Blame information for rev 1

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