Add an option to col_fill_in() to allow us to disable column expression processing...
[obnox/wireshark/wip.git] / tshark.c
1 /* tshark.c
2  *
3  * Text-mode variant of Wireshark, along the lines of tcpdump and snoop,
4  * by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris <guy@alum.mit.edu>.
5  *
6  * $Id$
7  *
8  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <locale.h>
36 #include <limits.h>
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #include <errno.h>
43
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47
48 #include <signal.h>
49
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h>
52 #endif
53
54 #ifdef NEED_STRERROR_H
55 #include "strerror.h"
56 #endif
57
58 #ifdef NEED_GETOPT_H
59 #include "getopt.h"
60 #endif
61
62 #include <glib.h>
63 #include <epan/epan.h>
64 #include <epan/filesystem.h>
65 #include <wsutil/privileges.h>
66
67 #include "globals.h"
68 #include <epan/timestamp.h>
69 #include <epan/packet.h>
70 #include "file.h"
71 #include "disabled_protos.h"
72 #include <epan/prefs.h>
73 #include <epan/column.h>
74 #include "print.h"
75 #include <epan/addr_resolv.h>
76 #include "util.h"
77 #include "clopts_common.h"
78 #include "cmdarg_err.h"
79 #include "version_info.h"
80 #include <epan/plugins.h>
81 #include "register.h"
82 #include <epan/epan_dissect.h>
83 #include <epan/tap.h>
84 #include <epan/stat_cmd_args.h>
85 #include <epan/timestamp.h>
86 #include <epan/ex-opt.h>
87
88 #ifdef HAVE_LIBPCAP
89 #include "capture_ui_utils.h"
90 #include <pcap.h>
91 #include "capture-pcap-util.h"
92 #ifdef _WIN32
93 #include "capture-wpcap.h"
94 #include "capture_errs.h"
95 #endif /* _WIN32 */
96 #include "capture_sync.h"
97 #endif /* HAVE_LIBPCAP */
98 #include "log.h"
99 #include <epan/funnel.h>
100
101
102 /*
103  * This is the template for the decode as option; it is shared between the
104  * various functions that output the usage for this parameter.
105  */
106 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
107
108 static nstime_t first_ts;
109 static nstime_t prev_dis_ts;
110 static nstime_t prev_cap_ts;
111 static GString *comp_info_str, *runtime_info_str;
112
113 static gboolean print_packet_info;      /* TRUE if we're to print packet information */
114 /*
115  * The way the packet decode is to be written.
116  */
117 typedef enum {
118         WRITE_TEXT,     /* summary or detail text */
119         WRITE_XML,      /* PDML or PSML */
120         WRITE_FIELDS    /* User defined list of fields */
121         /* Add CSV and the like here */
122 } output_action_e;
123 static output_action_e output_action;
124 static gboolean do_dissection;  /* TRUE if we have to dissect each packet */
125 static gboolean verbose;
126 static gboolean print_hex;
127 static gboolean line_buffered;
128 static guint32 cum_bytes = 0;
129 static print_format_e print_format = PR_FMT_TEXT;
130 static print_stream_t *print_stream;
131
132 static output_fields_t* output_fields  = NULL;
133
134 /*
135  * Standard secondary message for unexpected errors.
136  */
137 static const char please_report[] =
138     "Please report this to the Wireshark developers";
139
140 #ifdef HAVE_LIBPCAP
141 /*
142  * TRUE if we're to print packet counts to keep track of captured packets.
143  */
144 static gboolean print_packet_counts;
145
146
147 static capture_options global_capture_opts;
148
149 #ifdef SIGINFO
150 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
151 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
152 #endif /* SIGINFO */
153
154 static int capture(void);
155 static void report_counts(void);
156 #ifdef _WIN32
157 static BOOL WINAPI capture_cleanup(DWORD);
158 #else /* _WIN32 */
159 static void capture_cleanup(int);
160 #ifdef SIGINFO
161 static void report_counts_siginfo(int);
162 #endif /* SIGINFO */
163 #endif /* _WIN32 */
164 #endif /* HAVE_LIBPCAP */
165
166 static int load_cap_file(capture_file *, char *, int, int, gint64);
167 static gboolean process_packet(capture_file *cf, gint64 offset,
168     const struct wtap_pkthdr *whdr, union wtap_pseudo_header *pseudo_header,
169     const guchar *pd, gboolean filtering_tap_listeners, guint tap_flags);
170 static void show_capture_file_io_error(const char *, int, gboolean);
171 static void show_print_file_io_error(int err);
172 static gboolean write_preamble(capture_file *cf);
173 static gboolean print_packet(capture_file *cf, epan_dissect_t *edt);
174 static gboolean write_finale(void);
175 static const char *cf_open_error_message(int err, gchar *err_info,
176     gboolean for_writing, int file_type);
177
178 static void open_failure_message(const char *filename, int err,
179     gboolean for_writing);
180 static void failure_message(const char *msg_format, va_list ap);
181 static void read_failure_message(const char *filename, int err);
182 static void write_failure_message(const char *filename, int err);
183
184 capture_file cfile;
185
186 /*
187  * Mark a particular frame.
188  * Copied from file.c
189  */
190 void
191 cf_mark_frame(capture_file *cf, frame_data *frame)
192 {
193   if (! frame->flags.marked) {
194     frame->flags.marked = TRUE;
195     if (cf->count > cf->marked_count)
196       cf->marked_count++;
197   }
198 }
199
200 /*
201  * Unmark a particular frame.
202  * Copied from file.c
203  */
204 void
205 cf_unmark_frame(capture_file *cf, frame_data *frame)
206 {
207   if (frame->flags.marked) {
208     frame->flags.marked = FALSE;
209     if (cf->marked_count > 0)
210       cf->marked_count--;
211   }
212 }
213
214
215 static void list_capture_types(void) {
216     int i;
217
218     fprintf(stderr, "editcap: The available capture file types for \"F\":\n");
219     for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
220       if (wtap_dump_can_open(i))
221         fprintf(stderr, "    %s - %s\n",
222           wtap_file_type_short_string(i), wtap_file_type_string(i));
223     }
224 }
225
226 static void
227 print_usage(gboolean print_ver)
228 {
229   FILE *output;
230
231   if (print_ver) {
232     output = stdout;
233     fprintf(output,
234         "TShark " VERSION "%s\n"
235         "Dump and analyze network traffic.\n"
236         "See http://www.wireshark.org for more information.\n"
237         "\n"
238         "%s",
239         wireshark_svnversion, get_copyright_info());
240   } else {
241     output = stderr;
242   }
243   fprintf(output, "\n");
244   fprintf(output, "Usage: tshark [options] ...\n");
245   fprintf(output, "\n");
246
247 #ifdef HAVE_LIBPCAP
248   fprintf(output, "Capture interface:\n");
249   fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback)\n");
250   fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
251   fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
252   fprintf(output, "  -p                       don't capture in promiscuous mode\n");
253 #ifdef _WIN32
254   fprintf(output, "  -B <buffer size>         size of kernel buffer (def: 1MB)\n");
255 #endif
256   fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
257   fprintf(output, "  -D                       print list of interfaces and exit\n");
258   fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
259   fprintf(output, "\n");
260   fprintf(output, "Capture stop conditions:\n");
261   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
262   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
263   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
264   fprintf(output, "                              files:NUM - stop after NUM files\n");
265   /*fprintf(output, "\n");*/
266   fprintf(output, "Capture output:\n");
267   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
268   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
269   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
270 #endif  /* HAVE_LIBPCAP */
271
272   /*fprintf(output, "\n");*/
273   fprintf(output, "Input file:\n");
274   fprintf(output, "  -r <infile>              set the filename to read from (no pipes or stdin!)\n");
275
276   fprintf(output, "\n");
277   fprintf(output, "Processing:\n");
278   fprintf(output, "  -R <read filter>         packet filter in Wireshark display filter syntax\n");
279   fprintf(output, "  -n                       disable all name resolutions (def: all enabled)\n");
280   fprintf(output, "  -N <name resolve flags>  enable specific name resolution(s): \"mntC\"\n");
281   fprintf(output, "  -d %s ...\n", decode_as_arg_template);
282   fprintf(output, "                           \"Decode As\", see the man page for details\n");
283   fprintf(output, "                           Example: tcp.port==8888,http\n");
284
285   /*fprintf(output, "\n");*/
286   fprintf(output, "Output:\n");
287   fprintf(output, "  -w <outfile|->           write packets to a pcap-format file named \"outfile\"\n");
288   fprintf(output, "                           (or to the standard output for \"-\")\n");
289   fprintf(output, "  -C <config profile>      start with specified configuration profile\n");
290   fprintf(output, "  -F <output file type>    set the output file type, default is libpcap\n");
291   fprintf(output, "                           an empty \"-F\" option will list the file types\n");
292   fprintf(output, "  -V                       add output of packet tree        (Packet Details)\n");
293   fprintf(output, "  -S                       display packets even when writing to a file\n");
294   fprintf(output, "  -x                       add output of hex and ASCII dump (Packet Bytes)\n");
295   fprintf(output, "  -T pdml|ps|psml|text|fields\n");
296   fprintf(output, "                           format of text output (def: text)\n");
297   fprintf(output, "  -e <field>               field to print if -Tfields selected (e.g. tcp.port);\n");
298   fprintf(output, "                           this option can be repeated to print multiple fields\n");
299   fprintf(output, "  -E<fieldsoption>=<value> set options for output when -Tfields selected:\n");
300   fprintf(output, "     header=y|n            switch headers on and off\n");
301   fprintf(output, "     separator=/t|/s|<char> select tab, space, printable character as separator\n");
302   fprintf(output, "     quote=d|s|n           select double, single, no quotes for values\n");
303   fprintf(output, "  -t ad|a|r|d|dd|e         output format of time stamps (def: r: rel. to first)\n");
304   fprintf(output, "  -l                       flush standard output after each packet\n");
305   fprintf(output, "  -q                       be more quiet on stdout (e.g. when using statistics)\n");
306   fprintf(output, "  -X <key>:<value>         eXtension options, see the man page for details\n");
307   fprintf(output, "  -z <statistics>          various statistics, see the man page for details\n");
308
309   fprintf(output, "\n");
310   fprintf(output, "Miscellaneous:\n");
311   fprintf(output, "  -h                       display this help and exit\n");
312   fprintf(output, "  -v                       display version info and exit\n");
313   fprintf(output, "  -o <name>:<value> ...    override preference setting\n");
314   fprintf(output, "  -K <keytab>              keytab file to use for kerberos decryption\n");
315 }
316
317 /*
318  * For a dissector table, print on the stream described by output,
319  * its short name (which is what's used in the "-d" option) and its
320  * descriptive name.
321  */
322 static void
323 display_dissector_table_names(const char *table_name, const char *ui_name,
324                               gpointer output)
325 {
326   fprintf((FILE *)output, "\t%s (%s)\n", table_name, ui_name);
327 }
328
329 /*
330  * For a dissector handle, print on the stream described by output,
331  * the filter name (which is what's used in the "-d" option) and the full
332  * name for the protocol that corresponds to this handle.
333  */
334 static void
335 display_dissector_names(const gchar *table _U_, gpointer handle, gpointer output)
336 {
337   int                proto_id;
338   const gchar*       proto_filter_name;
339   const gchar*       proto_ui_name;
340
341   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
342
343   if (proto_id != -1) {
344     proto_filter_name = proto_get_protocol_filter_name(proto_id);
345     proto_ui_name =  proto_get_protocol_name(proto_id);
346     g_assert(proto_filter_name != NULL);
347     g_assert(proto_ui_name != NULL);
348
349     fprintf((FILE *)output, "\t%s (%s)\n",
350             proto_filter_name,
351             proto_ui_name);
352   }
353 }
354
355 /*
356  * The protocol_name_search structure is used by find_protocol_name_func()
357  * to pass parameters and store results
358  */
359 struct protocol_name_search{
360   gchar              *searched_name;  /* Protocol filter name we are looking for */
361   dissector_handle_t  matched_handle; /* Handle for a dissector whose protocol has the specified filter name */
362   guint               nb_match;       /* How many dissectors matched searched_name */
363 };
364 typedef struct protocol_name_search *protocol_name_search_t;
365
366 /*
367  * This function parses all dissectors associated with a table to find the
368  * one whose protocol has the specified filter name.  It is called
369  * as a reference function in a call to dissector_table_foreach_handle.
370  * The name we are looking for, as well as the results, are stored in the
371  * protocol_name_search struct pointed to by user_data.
372  * If called using dissector_table_foreach_handle, we actually parse the
373  * whole list of dissectors.
374  */
375 static void
376 find_protocol_name_func(const gchar *table _U_, gpointer handle, gpointer user_data)
377
378 {
379   int                         proto_id;
380   const gchar                *protocol_filter_name;
381   protocol_name_search_t      search_info;
382
383   g_assert(handle);
384
385   search_info = (protocol_name_search_t)user_data;
386
387   proto_id = dissector_handle_get_protocol_index((dissector_handle_t)handle);
388   if (proto_id != -1) {
389     protocol_filter_name = proto_get_protocol_filter_name(proto_id);
390     g_assert(protocol_filter_name != NULL);
391     if (strcmp(protocol_filter_name, search_info->searched_name) == 0) {
392       /* Found a match */
393       if (search_info->nb_match == 0) {
394         /* Record this handle only if this is the first match */
395         search_info->matched_handle = (dissector_handle_t)handle; /* Record the handle for this matching dissector */
396       }
397       search_info->nb_match++;
398     }
399   }
400 }
401
402 /*
403  * Print all layer type names supported.
404  * We send the output to the stream described by the handle output.
405  */
406
407 static void
408 fprint_all_layer_types(FILE *output)
409
410 {
411   dissector_all_tables_foreach_table(display_dissector_table_names, (gpointer)output);
412 }
413
414 /*
415  * Print all protocol names supported for a specific layer type.
416  * table_name contains the layer type name in which the search is performed.
417  * We send the output to the stream described by the handle output.
418  */
419
420 static void
421 fprint_all_protocols_for_layer_types(FILE *output, gchar *table_name)
422
423 {
424   dissector_table_foreach_handle(table_name,
425                                  display_dissector_names,
426                                  (gpointer)output);
427 }
428
429 /*
430  * The function below parses the command-line parameters for the decode as
431  * feature (a string pointer by cl_param).
432  * It checks the format of the command-line, searches for a matching table
433  * and dissector.  If a table/dissector match is not found, we display a
434  * summary of the available tables/dissectors (on stderr) and return FALSE.
435  * If everything is fine, we get the "Decode as" preference activated,
436  * then we return TRUE.
437  */
438 static gboolean
439 add_decode_as(const gchar *cl_param)
440 {
441   gchar                        *table_name;
442   guint32                       selector;
443   gchar                        *decoded_param;
444   gchar                        *remaining_param;
445   gchar                        *selector_str;
446   gchar                        *dissector_str;
447   dissector_handle_t            dissector_matching;
448   dissector_table_t             table_matching;
449   ftenum_t                      dissector_table_selector_type;
450   struct protocol_name_search   user_protocol_name;
451
452   /* The following code will allocate and copy the command-line options in a string pointed by decoded_param */
453
454   g_assert(cl_param);
455   decoded_param = g_strdup(cl_param);
456   g_assert(decoded_param);
457
458
459   /* The lines below will parse this string (modifying it) to extract all
460     necessary information.  Note that decoded_param is still needed since
461     strings are not copied - we just save pointers. */
462
463   /* This section extracts a layer type (table_name) from decoded_param */
464   table_name = decoded_param; /* Layer type string starts from beginning */
465
466   remaining_param = strchr(table_name, '=');
467   if (remaining_param == NULL) {
468     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
469     /* If the argument does not follow the template, carry on anyway to check
470        if the table name is at least correct.  If remaining_param is NULL,
471        we'll exit anyway further down */
472   }
473   else {
474     *remaining_param = '\0'; /* Terminate the layer type string (table_name) where '=' was detected */
475   }
476
477   /* Remove leading and trailing spaces from the table name */
478   while ( table_name[0] == ' ' )
479     table_name++;
480   while ( table_name[strlen(table_name) - 1] == ' ' )
481     table_name[strlen(table_name) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
482
483 /* The following part searches a table matching with the layer type specified */
484   table_matching = NULL;
485
486 /* Look for the requested table */
487   if ( !(*(table_name)) ) { /* Is the table name empty, if so, don't even search for anything, display a message */
488     cmdarg_err("No layer type specified"); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
489   }
490   else {
491     table_matching = find_dissector_table(table_name);
492     if (!table_matching) {
493       cmdarg_err("Unknown layer type -- %s", table_name); /* Note, we don't exit here, but table_matching will remain NULL, so we exit below */
494     }
495   }
496
497   if (!table_matching) {
498     /* Display a list of supported layer types to help the user, if the
499        specified layer type was not found */
500     cmdarg_err("Valid layer types are:");
501     fprint_all_layer_types(stderr);
502   }
503   if (remaining_param == NULL || !table_matching) {
504     /* Exit if the layer type was not found, or if no '=' separator was found
505        (see above) */
506     g_free(decoded_param);
507     return FALSE;
508   }
509
510   if (*(remaining_param + 1) != '=') { /* Check for "==" and not only '=' */
511     cmdarg_err("WARNING: -d requires \"==\" instead of \"=\". Option will be treated as \"%s==%s\"", table_name, remaining_param + 1);
512   }
513   else {
514     remaining_param++; /* Move to the second '=' */
515     *remaining_param = '\0'; /* Remove the second '=' */
516   }
517   remaining_param++; /* Position after the layer type string */
518
519   /* This section extracts a selector value (selector_str) from decoded_param */
520
521   selector_str = remaining_param; /* Next part starts with the selector number */
522
523   remaining_param = strchr(selector_str, ',');
524   if (remaining_param == NULL) {
525     cmdarg_err("Parameter \"%s\" doesn't follow the template \"%s\"", cl_param, decode_as_arg_template);
526     /* If the argument does not follow the template, carry on anyway to check
527        if the selector value is at least correct.  If remaining_param is NULL,
528        we'll exit anyway further down */
529   }
530   else {
531     *remaining_param = '\0'; /* Terminate the selector number string (selector_str) where ',' was detected */
532   }
533
534   dissector_table_selector_type = get_dissector_table_selector_type(table_name);
535
536   switch (dissector_table_selector_type) {
537
538   case FT_UINT8:
539   case FT_UINT16:
540   case FT_UINT24:
541   case FT_UINT32:
542     /* The selector for this table is an unsigned number.  Parse it as such.
543        There's no need to remove leading and trailing spaces from the
544        selector number string, because sscanf will do that for us. */
545     if ( sscanf(selector_str, "%u", &selector) != 1 ) {
546       cmdarg_err("Invalid selector number \"%s\"", selector_str);
547       g_free(decoded_param);
548       return FALSE;
549     }
550     break;
551
552   case FT_STRING:
553   case FT_STRINGZ:
554   case FT_EBCDIC:
555     /* The selector for this table is a string. */
556     break;
557
558   default:
559     /* There are currently no dissector tables with any types other
560        than the ones listed above. */
561     g_assert_not_reached();
562   }
563
564   if (remaining_param == NULL) {
565     /* Exit if no ',' separator was found (see above) */
566     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
567     fprint_all_protocols_for_layer_types(stderr, table_name);
568     g_free(decoded_param);
569     return FALSE;
570   }
571
572   remaining_param++; /* Position after the selector number string */
573
574   /* This section extracts a protocol filter name (dissector_str) from decoded_param */
575
576   dissector_str = remaining_param; /* All the rest of the string is the dissector (decode as protocol) name */
577
578   /* Remove leading and trailing spaces from the dissector name */
579   while ( dissector_str[0] == ' ' )
580     dissector_str++;
581   while ( dissector_str[strlen(dissector_str) - 1] == ' ' )
582     dissector_str[strlen(dissector_str) - 1] = '\0'; /* Note: if empty string, while loop will eventually exit */
583
584   dissector_matching = NULL;
585
586   /* We now have a pointer to the handle for the requested table inside the variable table_matching */
587   if ( ! (*dissector_str) ) { /* Is the dissector name empty, if so, don't even search for a matching dissector and display all dissectors found for the selected table */
588     cmdarg_err("No protocol name specified"); /* Note, we don't exit here, but dissector_matching will remain NULL, so we exit below */
589   }
590   else {
591     user_protocol_name.nb_match = 0;
592     user_protocol_name.searched_name = dissector_str;
593     user_protocol_name.matched_handle = NULL;
594
595     dissector_table_foreach_handle(table_name, find_protocol_name_func, &user_protocol_name); /* Go and perform the search for this dissector in the this table's dissectors' names and shortnames */
596
597     if (user_protocol_name.nb_match != 0) {
598       dissector_matching = user_protocol_name.matched_handle;
599       if (user_protocol_name.nb_match > 1) {
600         cmdarg_err("WARNING: Protocol \"%s\" matched %u dissectors, first one will be used", dissector_str, user_protocol_name.nb_match);
601       }
602     }
603     else {
604       /* OK, check whether the problem is that there isn't any such
605          protocol, or that there is but it's not specified as a protocol
606          that's valid for that dissector table.
607          Note, we don't exit here, but dissector_matching will remain NULL,
608          so we exit below */
609       if (proto_get_id_by_filter_name(dissector_str) == -1) {
610         /* No such protocol */
611         cmdarg_err("Unknown protocol -- \"%s\"", dissector_str);
612       } else {
613         cmdarg_err("Protocol \"%s\" isn't valid for layer type \"%s\"",
614                 dissector_str, table_name);
615       }
616     }
617   }
618
619   if (!dissector_matching) {
620     cmdarg_err("Valid protocols for layer type \"%s\" are:", table_name);
621     fprint_all_protocols_for_layer_types(stderr, table_name);
622     g_free(decoded_param);
623     return FALSE;
624   }
625
626 /* This is the end of the code that parses the command-line options.
627    All information is now stored in the variables:
628    table_name
629    selector
630    dissector_matching
631    The above variables that are strings are still pointing to areas within
632    decoded_parm.  decoded_parm thus still needs to be kept allocated in
633    until we stop needing these variables
634    decoded_param will be deallocated at each exit point of this function */
635
636
637   /* We now have a pointer to the handle for the requested dissector
638      (requested protocol) inside the variable dissector_matching */
639   switch (dissector_table_selector_type) {
640
641   case FT_UINT8:
642   case FT_UINT16:
643   case FT_UINT24:
644   case FT_UINT32:
645     /* The selector for this table is an unsigned number. */
646     dissector_change(table_name, selector, dissector_matching);
647     break;
648
649   case FT_STRING:
650   case FT_STRINGZ:
651   case FT_EBCDIC:
652     /* The selector for this table is a string. */
653     dissector_change_string(table_name, selector_str, dissector_matching);
654     break;
655
656   default:
657     /* There are currently no dissector tables with any types other
658        than the ones listed above. */
659     g_assert_not_reached();
660   }
661   g_free(decoded_param); /* "Decode As" rule has been succesfully added */
662   return TRUE;
663 }
664
665 static void
666 tshark_log_handler (const gchar *log_domain, GLogLevelFlags log_level,
667     const gchar *message, gpointer user_data)
668 {
669   /* ignore log message, if log_level isn't interesting based
670      upon the console log preferences.
671      If the preferences haven't been loaded loaded yet, display the
672      message anyway.
673
674      The default console_log_level preference value is such that only
675        ERROR, CRITICAL and WARNING level messages are processed;
676        MESSAGE, INFO and DEBUG level messages are ignored.
677
678      XXX: Aug 07, 2009: Prior tshark g_log code was hardwired to process only
679            ERROR and CRITICAL level messages so the current code is a behavioral
680            change.  The current behavior is the same as in Wireshark.
681   */
682   if((log_level & G_LOG_LEVEL_MASK & prefs.console_log_level) == 0 &&
683      prefs.console_log_level != 0) {
684     return;
685   }
686
687   g_log_default_handler(log_domain, log_level, message, user_data);
688
689 }
690
691 static char *
692 output_file_description(const char *fname)
693 {
694   char *save_file_string;
695
696   /* Get a string that describes what we're writing to */
697   if (strcmp(fname, "-") == 0) {
698     /* We're writing to the standard output */
699     save_file_string = g_strdup("standard output");
700   } else {
701     /* We're writing to a file with the name in save_file */
702     save_file_string = g_strdup_printf("file \"%s\"", fname);
703   }
704   return save_file_string;
705 }
706
707 static void
708 print_current_user(void) {
709   gchar *cur_user, *cur_group;
710   if (started_with_special_privs()) {
711     cur_user = get_cur_username();
712     cur_group = get_cur_groupname();
713     fprintf(stderr, "Running as user \"%s\" and group \"%s\".",
714       cur_user, cur_group);
715     g_free(cur_user);
716     g_free(cur_group);
717     if (running_with_special_privs()) {
718       fprintf(stderr, " This could be dangerous.");
719     }
720     fprintf(stderr, "\n");
721   }
722 }
723
724 static void
725 check_capture_privs(void) {
726 #ifdef _WIN32
727   load_wpcap();
728   /* Warn the user if npf.sys isn't loaded. */
729   if (!npf_sys_is_running() && get_os_major_version() >= 6) {
730     fprintf(stderr, "The NPF driver isn't running.  You may have trouble "
731       "capturing or\nlisting interfaces.\n");
732   }
733 #endif
734 }
735
736
737
738 int
739 main(int argc, char *argv[])
740 {
741   char                *init_progfile_dir_error;
742   int                  opt;
743   extern char         *optarg;
744   gboolean             arg_error = FALSE;
745
746 #ifdef _WIN32
747   WSADATA               wsaData;
748 #endif  /* _WIN32 */
749
750   char                *gpf_path, *pf_path;
751   char                *gdp_path, *dp_path;
752   int                  gpf_open_errno, gpf_read_errno;
753   int                  pf_open_errno, pf_read_errno;
754   int                  gdp_open_errno, gdp_read_errno;
755   int                  dp_open_errno, dp_read_errno;
756   int                  err;
757 #ifdef HAVE_LIBPCAP
758   gboolean             list_link_layer_types = FALSE;
759   gboolean             start_capture = FALSE;
760   int                  status;
761 #else
762   gboolean             capture_option_specified = FALSE;
763 #endif
764   gboolean             quiet = FALSE;
765   int                  out_file_type = WTAP_FILE_PCAP;
766   gchar               *cf_name = NULL, *rfilter = NULL;
767 #ifdef HAVE_PCAP_OPEN_DEAD
768   struct bpf_program   fcode;
769 #endif
770   dfilter_t           *rfcode = NULL;
771   e_prefs             *prefs;
772   char                 badopt;
773   GLogLevelFlags       log_flags;
774   int                  optind_initial;
775
776 #define OPTSTRING_INIT "a:b:c:C:d:De:E:f:F:G:hi:K:lLnN:o:pqr:R:s:St:T:vVw:xX:y:z:"
777 #ifdef HAVE_LIBPCAP
778 #ifdef _WIN32
779 #define OPTSTRING_WIN32 "B:"
780 #else
781 #define OPTSTRING_WIN32 ""
782 #endif  /* _WIN32 */
783 #else
784 #define OPTSTRING_WIN32 ""
785 #endif  /* HAVE_LIBPCAP */
786
787   static const char    optstring[] = OPTSTRING_INIT OPTSTRING_WIN32;
788
789   /*
790    * Get credential information for later use.
791    */
792   get_credential_info();
793
794   /*
795    * Attempt to get the pathname of the executable file.
796    */
797   init_progfile_dir_error = init_progfile_dir(argv[0], main);
798   if (init_progfile_dir_error != NULL) {
799     fprintf(stderr, "tshark: Can't get pathname of tshark program: %s.\n",
800             init_progfile_dir_error);
801   }
802
803   /*
804    * In order to have the -X opts assigned before the wslua machine starts
805    * we need to call getopts before epan_init() gets called.
806    */
807   opterr = 0;
808   optind_initial = optind;
809
810   while ((opt = getopt(argc, argv, optstring)) != -1) {
811           switch (opt) {
812                   case 'C':        /* Configuration Profile */
813                           if (profile_exists (optarg)) {
814                                   set_profile_name (optarg);
815                           } else {
816                                   cmdarg_err("Configuration Profile \"%s\" does not exist", optarg);
817                                   exit(1);
818                           }
819                           break;
820                   case 'X':
821                           ex_opt_add(optarg);
822                           break;
823                   default:
824                           break;
825           }
826   }
827
828   optind = optind_initial;
829   opterr = 1;
830
831
832
833 /** Send All g_log messages to our own handler **/
834
835   log_flags =
836                     G_LOG_LEVEL_ERROR|
837                     G_LOG_LEVEL_CRITICAL|
838                     G_LOG_LEVEL_WARNING|
839                     G_LOG_LEVEL_MESSAGE|
840                     G_LOG_LEVEL_INFO|
841                     G_LOG_LEVEL_DEBUG|
842                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
843
844   g_log_set_handler(NULL,
845                     log_flags,
846                     tshark_log_handler, NULL /* user_data */);
847   g_log_set_handler(LOG_DOMAIN_MAIN,
848                     log_flags,
849                     tshark_log_handler, NULL /* user_data */);
850
851 #ifdef HAVE_LIBPCAP
852   g_log_set_handler(LOG_DOMAIN_CAPTURE,
853                     log_flags,
854                     tshark_log_handler, NULL /* user_data */);
855   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
856                     log_flags,
857                     tshark_log_handler, NULL /* user_data */);
858 #endif
859
860   initialize_funnel_ops();
861
862 #ifdef HAVE_LIBPCAP
863   capture_opts_init(&global_capture_opts, &cfile);
864 #endif
865
866   timestamp_set_type(TS_RELATIVE);
867   timestamp_set_precision(TS_PREC_AUTO);
868
869   /* Register all dissectors; we must do this before checking for the
870      "-G" flag, as the "-G" flag dumps information registered by the
871      dissectors, and we must do it before we read the preferences, in
872      case any dissectors register preferences. */
873   epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
874             failure_message, open_failure_message, read_failure_message,
875             write_failure_message);
876
877   /* Register all tap listeners; we do this before we parse the arguments,
878      as the "-z" argument can specify a registered tap. */
879
880   /* we register the plugin taps before the other taps because
881      stats_tree taps plugins will be registered as tap listeners
882      by stats_tree_stat.c and need to registered before that */
883 #ifdef HAVE_PLUGINS
884   register_all_plugin_tap_listeners();
885 #endif
886   register_all_tap_listeners();
887
888   /* Now register the preferences for any non-dissector modules.
889      We must do that before we read the preferences as well. */
890   prefs_register_modules();
891
892   /* If invoked with the "-G" flag, we dump out information based on
893      the argument to the "-G" flag; if no argument is specified,
894      for backwards compatibility we dump out a glossary of display
895      filter symbols.
896
897      XXX - we do this here, for now, to support "-G" with no arguments.
898      If none of our build or other processes uses "-G" with no arguments,
899      we can just process it with the other arguments. */
900   if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
901           proto_initialize_all_prefixes();
902
903     if (argc == 2)
904       proto_registrar_dump_fields(1);
905     else {
906       if (strcmp(argv[2], "fields") == 0)
907         proto_registrar_dump_fields(1);
908       else if (strcmp(argv[2], "fields2") == 0)
909         proto_registrar_dump_fields(2);
910       else if (strcmp(argv[2], "fields3") == 0)
911         proto_registrar_dump_fields(3);
912       else if (strcmp(argv[2], "protocols") == 0)
913         proto_registrar_dump_protocols();
914       else if (strcmp(argv[2], "values") == 0)
915         proto_registrar_dump_values();
916       else if (strcmp(argv[2], "decodes") == 0)
917         dissector_dump_decodes();
918       else if (strcmp(argv[2], "defaultprefs") == 0)
919         write_prefs(NULL);
920       else if (strcmp(argv[2], "currentprefs") == 0) {
921         read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
922             &pf_open_errno, &pf_read_errno, &pf_path);
923         write_prefs(NULL);
924       } else {
925         cmdarg_err("Invalid \"%s\" option for -G flag", argv[2]);
926         exit(1);
927       }
928     }
929     exit(0);
930   }
931
932   /* Set the C-language locale to the native environment. */
933   setlocale(LC_ALL, "");
934
935   prefs = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
936                      &pf_open_errno, &pf_read_errno, &pf_path);
937   if (gpf_path != NULL) {
938     if (gpf_open_errno != 0) {
939       cmdarg_err("Can't open global preferences file \"%s\": %s.",
940               pf_path, strerror(gpf_open_errno));
941     }
942     if (gpf_read_errno != 0) {
943       cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
944               pf_path, strerror(gpf_read_errno));
945     }
946   }
947   if (pf_path != NULL) {
948     if (pf_open_errno != 0) {
949       cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
950               strerror(pf_open_errno));
951     }
952     if (pf_read_errno != 0) {
953       cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
954               pf_path, strerror(pf_read_errno));
955     }
956     g_free(pf_path);
957     pf_path = NULL;
958   }
959
960   /* Set the name resolution code's flags from the preferences. */
961   g_resolv_flags = prefs->name_resolve;
962
963   /* Read the disabled protocols file. */
964   read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
965                             &dp_path, &dp_open_errno, &dp_read_errno);
966   if (gdp_path != NULL) {
967     if (gdp_open_errno != 0) {
968       cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
969                  gdp_path, strerror(gdp_open_errno));
970     }
971     if (gdp_read_errno != 0) {
972       cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
973                  gdp_path, strerror(gdp_read_errno));
974     }
975     g_free(gdp_path);
976   }
977   if (dp_path != NULL) {
978     if (dp_open_errno != 0) {
979       cmdarg_err(
980         "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
981         strerror(dp_open_errno));
982     }
983     if (dp_read_errno != 0) {
984       cmdarg_err(
985         "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
986         strerror(dp_read_errno));
987     }
988     g_free(dp_path);
989   }
990
991   check_capture_privs();
992
993   init_cap_file(&cfile);
994
995   /* Assemble the compile-time version information string */
996   comp_info_str = g_string_new("Compiled ");
997   get_compiled_version_info(comp_info_str, get_epan_compiled_version_info);
998
999   /* Assemble the run-time version information string */
1000   runtime_info_str = g_string_new("Running ");
1001   get_runtime_version_info(runtime_info_str, NULL);
1002
1003   /* Print format defaults to this. */
1004   print_format = PR_FMT_TEXT;
1005
1006   output_fields = output_fields_new();
1007
1008   /* Now get our args */
1009   while ((opt = getopt(argc, argv, optstring)) != -1) {
1010     switch (opt) {
1011       case 'a':        /* autostop criteria */
1012       case 'b':        /* Ringbuffer option */
1013       case 'c':        /* Capture x packets */
1014       case 'f':        /* capture filter */
1015       case 'i':        /* Use interface x */
1016       case 'p':        /* Don't capture in promiscuous mode */
1017       case 's':        /* Set the snapshot (capture) length */
1018       case 'w':        /* Write to capture file x */
1019       case 'y':        /* Set the pcap data link type */
1020 #ifdef _WIN32
1021       case 'B':        /* Buffer size */
1022 #endif /* _WIN32 */
1023 #ifdef HAVE_LIBPCAP
1024         status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
1025         if(status != 0) {
1026             exit(status);
1027         }
1028 #else
1029         capture_option_specified = TRUE;
1030         arg_error = TRUE;
1031 #endif
1032         break;
1033       case 'C':
1034         /* Configuration profile settings were already processed just ignore them this time*/
1035         break;
1036       case 'd':        /* Decode as rule */
1037         if (!add_decode_as(optarg))
1038           exit(1);
1039         break;
1040 #if defined(HAVE_HEIMDAL_KERBEROS) || defined(HAVE_MIT_KERBEROS)
1041       case 'K':        /* Kerberos keytab file */
1042         read_keytab_file(optarg);
1043         break;
1044 #endif
1045       case 'D':        /* Print a list of capture devices and exit */
1046 #ifdef HAVE_LIBPCAP
1047         status = capture_opts_list_interfaces(FALSE);
1048         exit(status);
1049 #else
1050         capture_option_specified = TRUE;
1051         arg_error = TRUE;
1052 #endif
1053         break;
1054       case 'e':
1055         /* Field entry */
1056         output_fields_add(output_fields, optarg);
1057         break;
1058       case 'E':
1059         /* Field option */
1060         if(!output_fields_set_option(output_fields, optarg)) {
1061           cmdarg_err("\"%s\" is not a valid field output option=value pair.", optarg);
1062           output_fields_list_options(stderr);
1063           exit(1);
1064         }
1065         break;
1066       case 'F':
1067         out_file_type = wtap_short_string_to_file_type(optarg);
1068         if (out_file_type < 0) {
1069           cmdarg_err("\"%s\" isn't a valid capture file type", optarg);
1070           list_capture_types();
1071           exit(1);
1072         }
1073         break;
1074       case 'h':        /* Print help and exit */
1075         print_usage(TRUE);
1076         exit(0);
1077         break;
1078       case 'l':        /* "Line-buffer" standard output */
1079         /* This isn't line-buffering, strictly speaking, it's just
1080            flushing the standard output after the information for
1081            each packet is printed; however, that should be good
1082            enough for all the purposes to which "-l" is put (and
1083            is probably actually better for "-V", as it does fewer
1084            writes).
1085
1086            See the comment in "process_packet()" for an explanation of
1087            why we do that, and why we don't just use "setvbuf()" to
1088            make the standard output line-buffered (short version: in
1089            Windows, "line-buffered" is the same as "fully-buffered",
1090            and the output buffer is only flushed when it fills up). */
1091         line_buffered = TRUE;
1092         break;
1093       case 'L':        /* Print list of link-layer types and exit */
1094 #ifdef HAVE_LIBPCAP
1095         list_link_layer_types = TRUE;
1096 #else
1097         capture_option_specified = TRUE;
1098         arg_error = TRUE;
1099 #endif
1100         break;
1101       case 'n':        /* No name resolution */
1102         g_resolv_flags = RESOLV_NONE;
1103         break;
1104       case 'N':        /* Select what types of addresses/port #s to resolve */
1105         if (g_resolv_flags == RESOLV_ALL)
1106           g_resolv_flags = RESOLV_NONE;
1107         badopt = string_to_name_resolve(optarg, &g_resolv_flags);
1108         if (badopt != '\0') {
1109           cmdarg_err("-N specifies unknown resolving option '%c';",
1110                      badopt);
1111           cmdarg_err_cont( "           Valid options are 'm', 'n', 't', and 'C'");
1112           exit(1);
1113         }
1114         break;
1115       case 'o':        /* Override preference from command line */
1116         switch (prefs_set_pref(optarg)) {
1117
1118         case PREFS_SET_OK:
1119           break;
1120
1121         case PREFS_SET_SYNTAX_ERR:
1122           cmdarg_err("Invalid -o flag \"%s\"", optarg);
1123           exit(1);
1124           break;
1125
1126         case PREFS_SET_NO_SUCH_PREF:
1127         case PREFS_SET_OBSOLETE:
1128           cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
1129           exit(1);
1130           break;
1131         }
1132         break;
1133       case 'q':        /* Quiet */
1134         quiet = TRUE;
1135         break;
1136       case 'r':        /* Read capture file x */
1137         cf_name = g_strdup(optarg);
1138         break;
1139       case 'R':        /* Read file filter */
1140         rfilter = optarg;
1141         break;
1142       case 'S':        /* show packets in real time */
1143         print_packet_info = TRUE;
1144         break;
1145       case 't':        /* Time stamp type */
1146         if (strcmp(optarg, "r") == 0)
1147           timestamp_set_type(TS_RELATIVE);
1148         else if (strcmp(optarg, "a") == 0)
1149           timestamp_set_type(TS_ABSOLUTE);
1150         else if (strcmp(optarg, "ad") == 0)
1151           timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
1152         else if (strcmp(optarg, "d") == 0)
1153           timestamp_set_type(TS_DELTA);
1154         else if (strcmp(optarg, "dd") == 0)
1155           timestamp_set_type(TS_DELTA_DIS);
1156         else if (strcmp(optarg, "e") == 0)
1157           timestamp_set_type(TS_EPOCH);
1158         else {
1159           cmdarg_err("Invalid time stamp type \"%s\"",
1160             optarg);
1161           cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
1162           cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
1163           exit(1);
1164         }
1165         break;
1166       case 'T':        /* printing Type */
1167         if (strcmp(optarg, "text") == 0) {
1168           output_action = WRITE_TEXT;
1169           print_format = PR_FMT_TEXT;
1170         } else if (strcmp(optarg, "ps") == 0) {
1171           output_action = WRITE_TEXT;
1172           print_format = PR_FMT_PS;
1173         } else if (strcmp(optarg, "pdml") == 0) {
1174           output_action = WRITE_XML;
1175           verbose = TRUE;
1176         } else if (strcmp(optarg, "psml") == 0) {
1177           output_action = WRITE_XML;
1178           verbose = FALSE;
1179         } else if(strcmp(optarg, "fields") == 0) {
1180           output_action = WRITE_FIELDS;
1181           verbose = TRUE; /* Need full tree info */
1182         } else {
1183           cmdarg_err("Invalid -T parameter.");
1184           cmdarg_err_cont("It must be \"ps\", \"text\", \"pdml\", \"psml\" or \"fields\".");
1185           exit(1);
1186         }
1187         break;
1188       case 'v':        /* Show version and exit */
1189         printf("TShark " VERSION "%s\n"
1190                "\n"
1191                "%s"
1192                "\n"
1193                "%s"
1194                "\n"
1195                "%s",
1196                wireshark_svnversion, get_copyright_info(), comp_info_str->str,
1197                runtime_info_str->str);
1198         exit(0);
1199         break;
1200       case 'V':        /* Verbose */
1201         verbose = TRUE;
1202         break;
1203       case 'x':        /* Print packet data in hex (and ASCII) */
1204           print_hex = TRUE;
1205           break;
1206       case 'X':
1207           break;
1208       case 'z':
1209         /* We won't call the init function for the stat this soon
1210            as it would disallow MATE's fields (which are registered
1211            by the preferences set callback) from being used as
1212            part of a tap filter.  Instead, we just add the argument
1213            to a list of stat arguments. */
1214         if (!process_stat_cmd_arg(optarg)) {
1215           cmdarg_err("invalid -z argument.");
1216           cmdarg_err_cont("  -z argument must be one of :");
1217           list_stat_cmd_args();
1218           exit(1);
1219         }
1220         break;
1221       default:
1222       case '?':        /* Bad flag - print usage message */
1223         switch(optopt) {
1224         case 'F':
1225           list_capture_types();
1226           break;
1227         default:
1228           print_usage(TRUE);
1229         }
1230         exit(1);
1231         break;
1232     }
1233   }
1234
1235   /* If we specified output fields, but not the output field type... */
1236   if(WRITE_FIELDS != output_action && 0 != output_fields_num_fields(output_fields)) {
1237         cmdarg_err("Output fields were specified with \"-e\", "
1238             "but \"-Tfields\" was not specified.");
1239         exit(1);
1240   } else if(WRITE_FIELDS == output_action && 0 == output_fields_num_fields(output_fields)) {
1241         cmdarg_err("\"-Tfields\" was specified, but no fields were "
1242                     "specified with \"-e\".");
1243
1244         exit(1);
1245   }
1246
1247   /* If no capture filter or read filter has been specified, and there are
1248      still command-line arguments, treat them as the tokens of a capture
1249      filter (if no "-r" flag was specified) or a read filter (if a "-r"
1250      flag was specified. */
1251   if (optind < argc) {
1252     if (cf_name != NULL) {
1253       if (rfilter != NULL) {
1254         cmdarg_err("Read filters were specified both with \"-R\" "
1255             "and with additional command-line arguments");
1256         exit(1);
1257       }
1258       rfilter = get_args_as_string(argc, argv, optind);
1259     } else {
1260 #ifdef HAVE_LIBPCAP
1261       if (global_capture_opts.has_cfilter) {
1262         cmdarg_err("Capture filters were specified both with \"-f\""
1263             " and with additional command-line arguments");
1264         exit(1);
1265       }
1266       global_capture_opts.has_cfilter = TRUE;
1267       global_capture_opts.cfilter = get_args_as_string(argc, argv, optind);
1268 #else
1269       capture_option_specified = TRUE;
1270 #endif
1271     }
1272   }
1273
1274 #ifdef HAVE_LIBPCAP
1275   if (!global_capture_opts.saving_to_file) {
1276     /* We're not saving the capture to a file; if "-q" wasn't specified,
1277        we should print packet information */
1278     if (!quiet)
1279       print_packet_info = TRUE;
1280   } else {
1281     /* We're saving to a file; if we're writing to the standard output.
1282        and we'll also be writing dissected packets to the standard
1283        output, reject the request.  At best, we could redirect that
1284        to the standard error; we *can't* write both to the standard
1285        output and have either of them be useful. */
1286     if (strcmp(global_capture_opts.save_file, "-") == 0 && print_packet_info) {
1287       cmdarg_err("You can't write both raw packet data and dissected packets"
1288           " to the standard output.");
1289       exit(1);
1290     }
1291   }
1292 #else
1293   /* We're not saving the capture to a file; if "-q" wasn't specified,
1294      we should print packet information */
1295   if (!quiet)
1296     print_packet_info = TRUE;
1297 #endif
1298
1299 #ifndef HAVE_LIBPCAP
1300   if (capture_option_specified)
1301     cmdarg_err("This version of TShark was not built with support for capturing packets.");
1302 #endif
1303   if (arg_error) {
1304     print_usage(FALSE);
1305     exit(1);
1306   }
1307
1308   /* We don't support capture filters when reading from a capture file
1309      (the BPF compiler doesn't support all link-layer types that we
1310      support in capture files we read). */
1311 #ifdef HAVE_LIBPCAP
1312   if (cf_name != NULL) {
1313     if (global_capture_opts.has_cfilter) {
1314       cmdarg_err("Only read filters, not capture filters, "
1315           "can be specified when reading a capture file.");
1316       exit(1);
1317     }
1318   }
1319 #endif
1320
1321   if (print_hex) {
1322     if (output_action != WRITE_TEXT) {
1323       cmdarg_err("Raw packet hex data can only be printed as text or PostScript");
1324       exit(1);
1325     }
1326   }
1327
1328 #ifdef HAVE_LIBPCAP
1329   if (list_link_layer_types) {
1330     /* We're supposed to list the link-layer types for an interface;
1331        did the user also specify a capture file to be read? */
1332     if (cf_name) {
1333       /* Yes - that's bogus. */
1334       cmdarg_err("You can't specify -L and a capture file to be read.");
1335       exit(1);
1336     }
1337     /* No - did they specify a ring buffer option? */
1338     if (global_capture_opts.multi_files_on) {
1339       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
1340       exit(1);
1341     }
1342   } else {
1343     if (cf_name) {
1344       /*
1345        * "-r" was specified, so we're reading a capture file.
1346        * Capture options don't apply here.
1347        */
1348       if (global_capture_opts.multi_files_on) {
1349         cmdarg_err("Multiple capture files requested, but "
1350                    "a capture isn't being done.");
1351         exit(1);
1352       }
1353       if (global_capture_opts.has_file_duration) {
1354         cmdarg_err("Switching capture files after a time interval was specified, but "
1355                    "a capture isn't being done.");
1356         exit(1);
1357       }
1358       if (global_capture_opts.has_ring_num_files) {
1359         cmdarg_err("A ring buffer of capture files was specified, but "
1360           "a capture isn't being done.");
1361         exit(1);
1362       }
1363       if (global_capture_opts.has_autostop_files) {
1364         cmdarg_err("A maximum number of capture files was specified, but "
1365           "a capture isn't being done.");
1366         exit(1);
1367       }
1368
1369       /* Note: TShark now allows the restriction of a _read_ file by packet count
1370        * and byte count as well as a write file. Other autostop options remain valid
1371        * only for a write file.
1372        */
1373       if (global_capture_opts.has_autostop_duration) {
1374         cmdarg_err("A maximum capture time was specified, but "
1375           "a capture isn't being done.");
1376         exit(1);
1377       }
1378     } else {
1379       /*
1380        * "-r" wasn't specified, so we're doing a live capture.
1381        */
1382       if (global_capture_opts.saving_to_file) {
1383         /* They specified a "-w" flag, so we'll be saving to a capture file. */
1384
1385         /* When capturing, we only support writing libpcap format. */
1386         if (out_file_type != WTAP_FILE_PCAP) {
1387           cmdarg_err("Live captures can only be saved in libpcap format.");
1388           exit(1);
1389         }
1390         if (global_capture_opts.multi_files_on) {
1391           /* Multiple-file mode doesn't work under certain conditions:
1392              a) it doesn't work if you're writing to the standard output;
1393              b) it doesn't work if you're writing to a pipe;
1394           */
1395           if (strcmp(global_capture_opts.save_file, "-") == 0) {
1396             cmdarg_err("Multiple capture files requested, but "
1397               "the capture is being written to the standard output.");
1398             exit(1);
1399           }
1400           if (global_capture_opts.output_to_pipe) {
1401             cmdarg_err("Multiple capture files requested, but "
1402               "the capture file is a pipe.");
1403             exit(1);
1404           }
1405           if (!global_capture_opts.has_autostop_filesize &&
1406               !global_capture_opts.has_file_duration) {
1407             cmdarg_err("Multiple capture files requested, but "
1408               "no maximum capture file size or duration was specified.");
1409             exit(1);
1410           }
1411         }
1412       } else {
1413         /* They didn't specify a "-w" flag, so we won't be saving to a
1414            capture file.  Check for options that only make sense if
1415            we're saving to a file. */
1416         if (global_capture_opts.has_autostop_filesize) {
1417           cmdarg_err("Maximum capture file size specified, but "
1418            "capture isn't being saved to a file.");
1419           exit(1);
1420         }
1421         if (global_capture_opts.multi_files_on) {
1422           cmdarg_err("Multiple capture files requested, but "
1423             "the capture isn't being saved to a file.");
1424           exit(1);
1425         }
1426       }
1427     }
1428   }
1429 #endif
1430
1431 #ifdef _WIN32
1432   /* Start windows sockets */
1433   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
1434 #endif /* _WIN32 */
1435
1436   /* Notify all registered modules that have had any of their preferences
1437      changed either from one of the preferences file or from the command
1438      line that their preferences have changed. */
1439   prefs_apply_all();
1440
1441   /* At this point MATE will have registered its field array so we can
1442      have a tap filter with one of MATE's late-registered fields as part
1443      of the filter.  We can now process all the "-z" arguments. */
1444   start_requested_stats();
1445
1446   /* disabled protocols as per configuration file */
1447   if (gdp_path == NULL && dp_path == NULL) {
1448     set_disabled_protos_list();
1449   }
1450
1451   /* Build the column format array */
1452   build_column_format_array(&cfile.cinfo, prefs->num_cols, TRUE);
1453
1454 #ifdef HAVE_LIBPCAP
1455   capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
1456   capture_opts_trim_ring_num_files(&global_capture_opts);
1457 #endif
1458
1459   if (rfilter != NULL) {
1460     if (!dfilter_compile(rfilter, &rfcode)) {
1461       cmdarg_err("%s", dfilter_error_msg);
1462       epan_cleanup();
1463 #ifdef HAVE_PCAP_OPEN_DEAD
1464       {
1465         pcap_t *pc;
1466
1467         pc = pcap_open_dead(DLT_EN10MB, MIN_PACKET_SIZE);
1468         if (pc != NULL) {
1469           if (pcap_compile(pc, &fcode, rfilter, 0, 0) != -1) {
1470             cmdarg_err_cont(
1471               "  Note: That display filter code looks like a valid capture filter;");
1472             cmdarg_err_cont(
1473               "        maybe you mixed them up?");
1474           }
1475           pcap_close(pc);
1476         }
1477       }
1478 #endif
1479       exit(2);
1480     }
1481   }
1482   cfile.rfcode = rfcode;
1483
1484   if (print_packet_info) {
1485     /* If we're printing as text or PostScript, we have
1486        to create a print stream. */
1487     if (output_action == WRITE_TEXT) {
1488       switch (print_format) {
1489
1490       case PR_FMT_TEXT:
1491         print_stream = print_stream_text_stdio_new(stdout);
1492         break;
1493
1494       case PR_FMT_PS:
1495         print_stream = print_stream_ps_stdio_new(stdout);
1496         break;
1497
1498       default:
1499         g_assert_not_reached();
1500       }
1501     }
1502   }
1503
1504   /* We have to dissect each packet if:
1505
1506         we're printing information about each packet;
1507
1508         we're using a read filter on the packets;
1509
1510         we're using any taps. */
1511   do_dissection = print_packet_info || rfcode || have_tap_listeners();
1512
1513   if (cf_name) {
1514     /*
1515      * We're reading a capture file.
1516      */
1517
1518     /*
1519      * Immediately relinquish any special privileges we have; we must not
1520      * be allowed to read any capture files the user running TShark
1521      * can't open.
1522      */
1523     relinquish_special_privs_perm();
1524     print_current_user();
1525
1526     if (cf_open(&cfile, cf_name, FALSE, &err) != CF_OK) {
1527       epan_cleanup();
1528       exit(2);
1529     }
1530
1531     /* Set timestamp precision; there should arguably be a command-line
1532        option to let the user set this. */
1533     switch(wtap_file_tsprecision(cfile.wth)) {
1534     case(WTAP_FILE_TSPREC_SEC):
1535       timestamp_set_precision(TS_PREC_AUTO_SEC);
1536       break;
1537     case(WTAP_FILE_TSPREC_DSEC):
1538       timestamp_set_precision(TS_PREC_AUTO_DSEC);
1539       break;
1540     case(WTAP_FILE_TSPREC_CSEC):
1541       timestamp_set_precision(TS_PREC_AUTO_CSEC);
1542       break;
1543     case(WTAP_FILE_TSPREC_MSEC):
1544       timestamp_set_precision(TS_PREC_AUTO_MSEC);
1545       break;
1546     case(WTAP_FILE_TSPREC_USEC):
1547       timestamp_set_precision(TS_PREC_AUTO_USEC);
1548       break;
1549     case(WTAP_FILE_TSPREC_NSEC):
1550       timestamp_set_precision(TS_PREC_AUTO_NSEC);
1551       break;
1552     default:
1553       g_assert_not_reached();
1554     }
1555
1556     /* Process the packets in the file */
1557 #ifdef HAVE_LIBPCAP
1558     err = load_cap_file(&cfile, global_capture_opts.save_file, out_file_type,
1559         global_capture_opts.has_autostop_packets ? global_capture_opts.autostop_packets : 0,
1560         global_capture_opts.has_autostop_filesize ? global_capture_opts.autostop_filesize : 0);
1561 #else
1562     err = load_cap_file(&cfile, NULL, out_file_type, 0, 0);
1563 #endif
1564     if (err != 0) {
1565       epan_cleanup();
1566       exit(2);
1567     }
1568     cf_name[0] = '\0';
1569   } else {
1570     /* No capture file specified, so we're supposed to do a live capture
1571        (or get a list of link-layer types for a live capture device);
1572        do we have support for live captures? */
1573 #ifdef HAVE_LIBPCAP
1574
1575 #ifdef _WIN32
1576     if (!has_wpcap) {
1577       char *detailed_err;
1578
1579       cmdarg_err("WinPcap couldn't be found.");
1580       detailed_err = cant_load_winpcap_err("TShark");
1581       cmdarg_err_cont("%s", detailed_err);
1582       g_free(detailed_err);
1583       exit(2);
1584     }
1585 #endif
1586
1587     /* trim the interface name and exit if that failed */
1588     if (!capture_opts_trim_iface(&global_capture_opts,
1589         (prefs->capture_device) ? get_if_name(prefs->capture_device) : NULL)) {
1590         exit(2);
1591     }
1592
1593     /* if requested, list the link layer types and exit */
1594     if (list_link_layer_types) {
1595         status = capture_opts_list_link_layer_types(&global_capture_opts, FALSE);
1596         exit(status);
1597     }
1598
1599     if (print_packet_info) {
1600       if (!write_preamble(NULL)) {
1601         err = errno;
1602         show_print_file_io_error(err);
1603         return err;
1604       }
1605     } else if (!quiet) {
1606       /*
1607        * We're not printing information for each packet, and the user
1608        * didn't ask us not to print a count of packets as they arrive,
1609        * so print that count so the user knows that packets are arriving.
1610        *
1611        * XXX - what if the user wants to do a live capture, doesn't want
1612        * to save it to a file, doesn't want information printed for each
1613        * packet, does want some "-z" statistic, and wants packet counts
1614        * so they know whether they're seeing any packets?
1615        */
1616       print_packet_counts = TRUE;
1617     }
1618
1619     /* For now, assume libpcap gives microsecond precision. */
1620     timestamp_set_precision(TS_PREC_AUTO_USEC);
1621
1622     capture();
1623
1624     if (print_packet_info) {
1625       if (!write_finale()) {
1626         err = errno;
1627         show_print_file_io_error(err);
1628       }
1629     }
1630 #else
1631     /* No - complain. */
1632     cmdarg_err("This version of TShark was not built with support for capturing packets.");
1633     exit(2);
1634 #endif
1635   }
1636
1637   draw_tap_listeners(TRUE);
1638   funnel_dump_all_text_windows();
1639   epan_cleanup();
1640
1641   output_fields_free(output_fields);
1642   output_fields = NULL;
1643
1644   return 0;
1645 }
1646
1647 /*#define USE_BROKEN_G_MAIN_LOOP*/
1648
1649 #ifdef USE_BROKEN_G_MAIN_LOOP
1650   GMainLoop *loop;
1651 #else
1652   gboolean loop_running = FALSE;
1653 #endif
1654   guint32 packet_count = 0;
1655
1656
1657 /* XXX - move to the right position / file */
1658 /* read from a pipe (callback) */
1659 typedef gboolean (*pipe_input_cb_t) (gint source, gpointer user_data);
1660
1661 typedef struct pipe_input_tag {
1662     gint                source;
1663     gpointer            user_data;
1664     int                 *child_process;
1665     pipe_input_cb_t     input_cb;
1666     guint               pipe_input_id;
1667 #ifdef _WIN32
1668     GStaticMutex                callback_running;
1669 #endif
1670 } pipe_input_t;
1671
1672 static pipe_input_t pipe_input;
1673
1674 #ifdef _WIN32
1675 /* The timer has expired, see if there's stuff to read from the pipe,
1676    if so, do the callback */
1677 static gint
1678 pipe_timer_cb(gpointer data)
1679 {
1680   HANDLE handle;
1681   DWORD avail = 0;
1682   gboolean result, result1;
1683   DWORD childstatus;
1684   pipe_input_t *pipe_input = data;
1685   gint iterations = 0;
1686
1687
1688   g_static_mutex_lock (&pipe_input->callback_running);
1689
1690   /* try to read data from the pipe only 5 times, to avoid blocking */
1691   while(iterations < 5) {
1692           /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: new iteration");*/
1693
1694           /* Oddly enough although Named pipes don't work on win9x,
1695                  PeekNamedPipe does !!! */
1696           handle = (HANDLE) _get_osfhandle (pipe_input->source);
1697           result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1698
1699           /* Get the child process exit status */
1700           result1 = GetExitCodeProcess((HANDLE)*(pipe_input->child_process),
1701                                                                    &childstatus);
1702
1703           /* If the Peek returned an error, or there are bytes to be read
1704                  or the childwatcher thread has terminated then call the normal
1705                  callback */
1706           if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
1707
1708                 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: data avail");*/
1709
1710                 /* And call the real handler */
1711                 if (!pipe_input->input_cb(pipe_input->source, pipe_input->user_data)) {
1712                         g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: input pipe closed, iterations: %u", iterations);
1713                         /* pipe closed, return false so that the timer is stopped */
1714                         g_static_mutex_unlock (&pipe_input->callback_running);
1715                         return FALSE;
1716                 }
1717           }
1718           else {
1719                 /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: no data avail");*/
1720                 /* No data, stop now */
1721                 break;
1722           }
1723
1724           iterations++;
1725   }
1726
1727         /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_timer_cb: finished with iterations: %u, new timer", iterations);*/
1728
1729         g_static_mutex_unlock (&pipe_input->callback_running);
1730
1731         /* we didn't stopped the timer, so let it run */
1732         return TRUE;
1733 }
1734 #endif
1735
1736
1737 void
1738 pipe_input_set_handler(gint source, gpointer user_data, int *child_process, pipe_input_cb_t input_cb)
1739 {
1740
1741     pipe_input.source                   = source;
1742     pipe_input.child_process            = child_process;
1743     pipe_input.user_data                = user_data;
1744     pipe_input.input_cb                 = input_cb;
1745
1746 #ifdef _WIN32
1747     g_static_mutex_init(&pipe_input.callback_running);
1748     /* Tricky to use pipes in win9x, as no concept of wait.  NT can
1749        do this but that doesn't cover all win32 platforms.  GTK can do
1750        this but doesn't seem to work over processes.  Attempt to do
1751        something similar here, start a timer and check for data on every
1752        timeout. */
1753         /*g_log(NULL, G_LOG_LEVEL_DEBUG, "pipe_input_set_handler: new");*/
1754     pipe_input.pipe_input_id = g_timeout_add(200, pipe_timer_cb, &pipe_input);
1755 #endif
1756 }
1757
1758
1759 #ifdef HAVE_LIBPCAP
1760 static int
1761 capture(void)
1762 {
1763   gboolean ret;
1764 #ifdef USE_TSHARK_SELECT
1765   fd_set readfds;
1766 #endif
1767 #ifndef _WIN32
1768   struct sigaction action, oldaction;
1769 #endif
1770
1771   /*
1772    * XXX - dropping privileges is still required, until code cleanup is done
1773    *
1774    * remove all dependencies to pcap specific code and using only dumpcap is almost done.
1775    * when it's done, we don't need special privileges to run tshark at all,
1776    * therefore we don't need to drop these privileges
1777    * The only thing we might want to keep is a warning if tshark is run as root,
1778    * as it's no longer necessary and potentially dangerous.
1779    *
1780    * THE FOLLOWING IS THE FORMER COMMENT WHICH IS NO LONGER REALLY VALID:
1781    * We've opened the capture device, so we shouldn't need any special
1782    * privileges any more; relinquish those privileges.
1783    *
1784    * XXX - if we have saved set-user-ID support, we should give up those
1785    * privileges immediately, and then reclaim them long enough to get
1786    * a list of network interfaces and to open one, and then give them
1787    * up again, so that stuff we do while processing the argument list,
1788    * reading the user's preferences, loading and starting plugins
1789    * (especially *user* plugins), etc. is done with the user's privileges,
1790    * not special privileges.
1791    */
1792   relinquish_special_privs_perm();
1793   print_current_user();
1794
1795   /* Cleanup all data structures used for dissection. */
1796   cleanup_dissection();
1797   /* Initialize all data structures used for dissection. */
1798   init_dissection();
1799
1800 #ifdef _WIN32
1801   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1802   SetConsoleCtrlHandler(capture_cleanup, TRUE);
1803 #else /* _WIN32 */
1804   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1805      and exit. */
1806   action.sa_handler = capture_cleanup;
1807   action.sa_flags = 0;
1808   sigemptyset(&action.sa_mask);
1809   sigaction(SIGTERM, &action, NULL);
1810   sigaction(SIGINT, &action, NULL);
1811   sigaction(SIGHUP, NULL, &oldaction);
1812   if (oldaction.sa_handler == SIG_DFL)
1813     sigaction(SIGHUP, &action, NULL);
1814
1815 #ifdef SIGINFO
1816   /* Catch SIGINFO and, if we get it and we're capturing to a file in
1817      quiet mode, report the number of packets we've captured. */
1818   action.sa_handler = report_counts_siginfo;
1819   action.sa_flags = 0;
1820   sigemptyset(&action.sa_mask);
1821   sigaction(SIGINFO, &action, NULL);
1822 #endif /* SIGINFO */
1823 #endif /* _WIN32 */
1824
1825   global_capture_opts.state = CAPTURE_PREPARING;
1826
1827   /* Let the user know what interface was chosen. */
1828   global_capture_opts.iface_descr = get_interface_descriptive_name(global_capture_opts.iface);
1829   fprintf(stderr, "Capturing on %s\n", global_capture_opts.iface_descr);
1830
1831   ret = sync_pipe_start(&global_capture_opts);
1832
1833   if (!ret)
1834     return FALSE;
1835
1836     /* the actual capture loop
1837      *
1838      * XXX - glib doesn't seem to provide any event based loop handling.
1839      *
1840      * XXX - for whatever reason,
1841      * calling g_main_loop_new() ends up in 100% cpu load.
1842      *
1843      * But that doesn't matter: in UNIX we can use select() to find an input
1844      * source with something to do.
1845      *
1846      * But that doesn't matter because we're in a CLI (that doesn't need to
1847      * update a GUI or something at the same time) so it's OK if we block
1848      * trying to read from the pipe.
1849      *
1850      * So all the stuff in USE_TSHARK_SELECT could be removed unless I'm
1851      * wrong (but I leave it there in case I am...).
1852      */
1853
1854 #ifdef USE_TSHARK_SELECT
1855   FD_ZERO(&readfds);
1856   FD_SET(pipe_input.source, &readfds);
1857 #endif
1858
1859   loop_running = TRUE;
1860
1861   while (loop_running)
1862   {
1863 #ifdef USE_TSHARK_SELECT
1864     ret = select(pipe_input.source+1, &readfds, NULL, NULL, NULL);
1865
1866     if (ret == -1)
1867     {
1868       perror("select()");
1869       return TRUE;
1870     } else if (ret == 1) {
1871 #endif
1872       /* Call the real handler */
1873       if (!pipe_input.input_cb(pipe_input.source, pipe_input.user_data)) {
1874         g_log(NULL, G_LOG_LEVEL_DEBUG, "input pipe closed");
1875         return FALSE;
1876       }
1877 #ifdef USE_TSHARK_SELECT
1878     }
1879 #endif
1880   }
1881
1882   return TRUE;
1883 }
1884
1885
1886 /* XXX - move the call to main_window_update() out of capture_sync.c */
1887 /* dummy for capture_sync.c to make linker happy */
1888 void main_window_update(void)
1889 {
1890 }
1891
1892 /* capture child detected an error */
1893 void
1894 capture_input_error_message(capture_options *capture_opts _U_, char *error_msg, char *secondary_error_msg)
1895 {
1896         cmdarg_err("%s", error_msg);
1897         cmdarg_err_cont("%s", secondary_error_msg);
1898 }
1899
1900
1901 /* capture child detected an capture filter related error */
1902 void
1903 capture_input_cfilter_error_message(capture_options *capture_opts, char *error_message)
1904 {
1905     dfilter_t   *rfcode = NULL;
1906
1907
1908     if (dfilter_compile(capture_opts->cfilter, &rfcode) && rfcode != NULL) {
1909       cmdarg_err(
1910         "Invalid capture filter: \"%s\"!\n"
1911         "\n"
1912         "That string looks like a valid display filter; however, it isn't a valid\n"
1913         "capture filter (%s).\n"
1914         "\n"
1915         "Note that display filters and capture filters don't have the same syntax,\n"
1916         "so you can't use most display filter expressions as capture filters.\n"
1917         "\n"
1918         "See the User's Guide for a description of the capture filter syntax.",
1919         capture_opts->cfilter, error_message);
1920       dfilter_free(rfcode);
1921     } else {
1922       cmdarg_err(
1923         "Invalid capture filter: \"%s\"!\n"
1924         "\n"
1925         "That string isn't a valid capture filter (%s).\n"
1926         "See the User's Guide for a description of the capture filter syntax.",
1927         capture_opts->cfilter, error_message);
1928     }
1929 }
1930
1931
1932 /* capture child tells us we have a new (or the first) capture file */
1933 gboolean
1934 capture_input_new_file(capture_options *capture_opts, gchar *new_file)
1935 {
1936   gboolean is_tempfile;
1937   int  err;
1938
1939
1940   if(capture_opts->state == CAPTURE_PREPARING) {
1941     g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "Capture started!");
1942   }
1943   g_log(LOG_DOMAIN_CAPTURE, G_LOG_LEVEL_MESSAGE, "File: \"%s\"", new_file);
1944
1945   g_assert(capture_opts->state == CAPTURE_PREPARING || capture_opts->state == CAPTURE_RUNNING);
1946
1947   /* free the old filename */
1948   if (capture_opts->save_file != NULL) {
1949
1950     /* we start a new capture file, close the old one (if we had one before) */
1951     if( ((capture_file *) capture_opts->cf)->state != FILE_CLOSED) {
1952       if ( ((capture_file *) capture_opts->cf)->wth != NULL) {
1953         wtap_close(((capture_file *) capture_opts->cf)->wth);
1954       }
1955       ((capture_file *) capture_opts->cf)->state = FILE_CLOSED;
1956     }
1957
1958     g_free(capture_opts->save_file);
1959     is_tempfile = FALSE;
1960   } else {
1961     /* we didn't had a save_file before, must be a tempfile */
1962     is_tempfile = TRUE;
1963   }
1964
1965   /* save the new filename */
1966   capture_opts->save_file = g_strdup(new_file);
1967
1968   /* if we are in real-time mode, open the new file now */
1969   if(do_dissection) {
1970     /* Attempt to open the capture file and set up to read from it. */
1971     switch(cf_open(capture_opts->cf, capture_opts->save_file, is_tempfile, &err)) {
1972     case CF_OK:
1973       break;
1974     case CF_ERROR:
1975       /* Don't unlink (delete) the save file - leave it around,
1976          for debugging purposes. */
1977       g_free(capture_opts->save_file);
1978       capture_opts->save_file = NULL;
1979       return FALSE;
1980     }
1981   }
1982
1983   capture_opts->state = CAPTURE_RUNNING;
1984
1985   return TRUE;
1986 }
1987
1988
1989 /* capture child tells us we have new packets to read */
1990 void
1991 capture_input_new_packets(capture_options *capture_opts, int to_read)
1992 {
1993   gboolean     ret;
1994   int          err;
1995   gchar        *err_info;
1996   gint64       data_offset;
1997   capture_file *cf = capture_opts->cf;
1998   gboolean filtering_tap_listeners;
1999   guint tap_flags;
2000
2001 #ifdef SIGINFO
2002   /*
2003    * Prevent a SIGINFO handler from writing to stdout while we're
2004    * doing so; instead, have it just set a flag telling us to print
2005    * that information when we're done.
2006    */
2007   infodelay = TRUE;
2008 #endif /* SIGINFO */
2009
2010   /* Do we have any tap listeners with filters? */
2011   filtering_tap_listeners = have_filtering_tap_listeners();
2012
2013   /* Get the union of the flags for all tap listeners. */
2014   tap_flags = union_of_tap_listener_flags();
2015
2016   if(do_dissection) {
2017     while (to_read-- && cf->wth) {
2018       ret = wtap_read(cf->wth, &err, &err_info, &data_offset);
2019       if(ret == FALSE) {
2020         /* read from file failed, tell the capture child to stop */
2021         sync_pipe_stop(capture_opts);
2022         wtap_close(cf->wth);
2023         cf->wth = NULL;
2024       } else {
2025         ret = process_packet(cf, data_offset, wtap_phdr(cf->wth),
2026                              wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2027                              filtering_tap_listeners, tap_flags);
2028       }
2029       if (ret != FALSE) {
2030         /* packet sucessfully read and gone through the "Read Filter" */
2031         packet_count++;
2032       }
2033     }
2034   } else {
2035     /*
2036      * Dumpcap's doing all the work; we're not doing any dissection.
2037      * Count all the packets it wrote.
2038      */
2039     packet_count += to_read;
2040   }
2041
2042   if (print_packet_counts) {
2043       /* We're printing packet counts. */
2044       if (packet_count != 0) {
2045         fprintf(stderr, "\r%u ", packet_count);
2046         /* stderr could be line buffered */
2047         fflush(stderr);
2048       }
2049   }
2050
2051 #ifdef SIGINFO
2052   /*
2053    * Allow SIGINFO handlers to write.
2054    */
2055   infodelay = FALSE;
2056
2057   /*
2058    * If a SIGINFO handler asked us to write out capture counts, do so.
2059    */
2060   if (infoprint)
2061     report_counts();
2062 #endif /* SIGINFO */
2063 }
2064
2065 static void
2066 report_counts(void)
2067 {
2068   if (!print_packet_counts) {
2069     /* Report the count only if we aren't printing a packet count
2070        as packets arrive. */
2071     fprintf(stderr, "%u packet%s captured\n", packet_count,
2072             plurality(packet_count, "", "s"));
2073   }
2074 #ifdef SIGINFO
2075   infoprint = FALSE; /* we just reported it */
2076 #endif /* SIGINFO */
2077 }
2078
2079 #ifdef SIGINFO
2080 static void
2081 report_counts_siginfo(int signum _U_)
2082 {
2083   int sav_errno = errno;
2084   /* If we've been told to delay printing, just set a flag asking
2085      that we print counts (if we're supposed to), otherwise print
2086      the count of packets captured (if we're supposed to). */
2087   if (infodelay)
2088     infoprint = TRUE;
2089   else
2090     report_counts();
2091   errno = sav_errno;
2092 }
2093 #endif /* SIGINFO */
2094
2095
2096 /* capture child detected any packet drops? */
2097 void
2098 capture_input_drops(capture_options *capture_opts _U_, guint32 dropped)
2099 {
2100   if (print_packet_counts) {
2101     /* We're printing packet counts to stderr.
2102        Send a newline so that we move to the line after the packet count. */
2103     fprintf(stderr, "\n");
2104   }
2105
2106   if (dropped != 0) {
2107     /* We're printing packet counts to stderr.
2108        Send a newline so that we move to the line after the packet count. */
2109     fprintf(stderr, "%u packet%s dropped\n", dropped, plurality(dropped, "", "s"));
2110   }
2111 }
2112
2113
2114 /* capture child closed its side of the pipe, do the required cleanup */
2115 void
2116 capture_input_closed(capture_options *capture_opts)
2117 {
2118   report_counts();
2119
2120   if(capture_opts->cf != NULL && ((capture_file *) capture_opts->cf)->wth != NULL) {
2121     wtap_close(((capture_file *) capture_opts->cf)->wth);
2122   }
2123 #ifdef USE_BROKEN_G_MAIN_LOOP
2124   /*g_main_loop_quit(loop);*/
2125   g_main_quit(loop);
2126 #else
2127   loop_running = FALSE;
2128 #endif
2129 }
2130
2131
2132
2133
2134 #ifdef _WIN32
2135 static BOOL WINAPI
2136 capture_cleanup(DWORD ctrltype _U_)
2137 {
2138   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
2139      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
2140      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
2141      like SIGTERM at least when the machine's shutting down.
2142
2143      For now, we handle them all as indications that we should clean up
2144      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
2145      way on UNIX.
2146
2147      However, as handlers run in a new thread, we can't just longjmp
2148      out; we have to set "ld.go" to FALSE, and must return TRUE so that
2149      no other handler - such as one that would terminate the process -
2150      gets called.
2151
2152      XXX - for some reason, typing ^C to TShark, if you run this in
2153      a Cygwin console window in at least some versions of Cygwin,
2154      causes TShark to terminate immediately; this routine gets
2155      called, but the main loop doesn't get a chance to run and
2156      exit cleanly, at least if this is compiled with Microsoft Visual
2157      C++ (i.e., it's a property of the Cygwin console window or Bash;
2158      it happens if TShark is not built with Cygwin - for all I know,
2159      building it with Cygwin may make the problem go away). */
2160
2161   /* tell the capture child to stop */
2162   sync_pipe_stop(&global_capture_opts);
2163
2164   /* don't stop our own loop already here, otherwise status messages and
2165    * cleanup wouldn't be done properly. The child will indicate the stop of
2166    * everything by calling capture_input_closed() later */
2167
2168   return TRUE;
2169 }
2170 #else
2171 static void
2172 capture_cleanup(int signum _U_)
2173 {
2174   /* tell the capture child to stop */
2175   sync_pipe_stop(&global_capture_opts);
2176 }
2177 #endif /* _WIN32 */
2178 #endif /* HAVE_LIBPCAP */
2179
2180 static int
2181 load_cap_file(capture_file *cf, char *save_file, int out_file_type,
2182     int max_packet_count, gint64 max_byte_count)
2183 {
2184   gint         linktype;
2185   int          snapshot_length;
2186   wtap_dumper *pdh;
2187   int          err;
2188   gchar        *err_info;
2189   gint64       data_offset;
2190   char         *save_file_string = NULL;
2191   gboolean     filtering_tap_listeners;
2192   guint        tap_flags;
2193
2194   linktype = wtap_file_encap(cf->wth);
2195   if (save_file != NULL) {
2196     /* Get a string that describes what we're writing to */
2197     save_file_string = output_file_description(save_file);
2198
2199     /* Set up to write to the capture file. */
2200     snapshot_length = wtap_snapshot_length(cf->wth);
2201     if (snapshot_length == 0) {
2202       /* Snapshot length of input file not known. */
2203       snapshot_length = WTAP_MAX_PACKET_SIZE;
2204     }
2205     pdh = wtap_dump_open(save_file, out_file_type, linktype, snapshot_length,
2206                          FALSE /* compressed */, &err);
2207
2208     if (pdh == NULL) {
2209       /* We couldn't set up to write to the capture file. */
2210       switch (err) {
2211
2212       case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
2213         cmdarg_err("Capture files can't be written in that format.");
2214         break;
2215
2216       case WTAP_ERR_UNSUPPORTED_ENCAP:
2217       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
2218         cmdarg_err("The capture file being read can't be written in "
2219           "that format.");
2220         break;
2221
2222       case WTAP_ERR_CANT_OPEN:
2223         cmdarg_err("The %s couldn't be created for some "
2224           "unknown reason.", save_file_string);
2225         break;
2226
2227       case WTAP_ERR_SHORT_WRITE:
2228         cmdarg_err("A full header couldn't be written to the %s.",
2229                    save_file_string);
2230         break;
2231
2232       default:
2233         cmdarg_err("The %s could not be created: %s.", save_file_string,
2234                    wtap_strerror(err));
2235         break;
2236       }
2237       goto out;
2238     }
2239   } else {
2240     if (print_packet_info) {
2241       if (!write_preamble(cf)) {
2242         err = errno;
2243         show_print_file_io_error(err);
2244         goto out;
2245       }
2246     }
2247     pdh = NULL;
2248   }
2249
2250   /* Do we have any tap listeners with filters? */
2251   filtering_tap_listeners = have_filtering_tap_listeners();
2252
2253   /* Get the union of the flags for all tap listeners. */
2254   tap_flags = union_of_tap_listener_flags();
2255
2256   while (wtap_read(cf->wth, &err, &err_info, &data_offset)) {
2257     if (process_packet(cf, data_offset, wtap_phdr(cf->wth),
2258                        wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2259                        filtering_tap_listeners, tap_flags)) {
2260       /* Either there's no read filtering or this packet passed the
2261          filter, so, if we're writing to a capture file, write
2262          this packet out. */
2263       if (pdh != NULL) {
2264         if (!wtap_dump(pdh, wtap_phdr(cf->wth),
2265                        wtap_pseudoheader(cf->wth), wtap_buf_ptr(cf->wth),
2266                        &err)) {
2267           /* Error writing to a capture file */
2268           show_capture_file_io_error(save_file, err, FALSE);
2269           wtap_dump_close(pdh, &err);
2270           exit(2);
2271         }
2272       }
2273       /* Stop reading if we have the maximum number of packets;
2274        * When the -c option has not been used, max_packet_count
2275        * starts at 0, which practically means, never stop reading.
2276        * (unless we roll over max_packet_count ?)
2277        */
2278       if( (--max_packet_count == 0) || (max_byte_count != 0 && data_offset >= max_byte_count)) {
2279         err = 0; /* This is not an error */
2280         break;
2281       }
2282     }
2283   }
2284   if (err != 0) {
2285     /* Print a message noting that the read failed somewhere along the line. */
2286     switch (err) {
2287
2288     case WTAP_ERR_UNSUPPORTED_ENCAP:
2289       cmdarg_err("\"%s\" has a packet with a network type that TShark doesn't support.\n(%s)",
2290                  cf->filename, err_info);
2291       g_free(err_info);
2292       break;
2293
2294     case WTAP_ERR_CANT_READ:
2295       cmdarg_err("An attempt to read from \"%s\" failed for some unknown reason.",
2296                  cf->filename);
2297       break;
2298
2299     case WTAP_ERR_SHORT_READ:
2300       cmdarg_err("\"%s\" appears to have been cut short in the middle of a packet.",
2301                  cf->filename);
2302       break;
2303
2304     case WTAP_ERR_BAD_RECORD:
2305       cmdarg_err("\"%s\" appears to be damaged or corrupt.\n(%s)",
2306                  cf->filename, err_info);
2307       g_free(err_info);
2308       break;
2309
2310     default:
2311       cmdarg_err("An error occurred while reading \"%s\": %s.",
2312                  cf->filename, wtap_strerror(err));
2313       break;
2314     }
2315     if (save_file != NULL) {
2316       /* Now close the capture file. */
2317       if (!wtap_dump_close(pdh, &err))
2318         show_capture_file_io_error(save_file, err, TRUE);
2319     }
2320   } else {
2321     if (save_file != NULL) {
2322       /* Now close the capture file. */
2323       if (!wtap_dump_close(pdh, &err))
2324         show_capture_file_io_error(save_file, err, TRUE);
2325     } else {
2326       if (print_packet_info) {
2327         if (!write_finale()) {
2328           err = errno;
2329           show_print_file_io_error(err);
2330         }
2331       }
2332     }
2333   }
2334
2335 out:
2336   wtap_close(cf->wth);
2337   cf->wth = NULL;
2338
2339   g_free(save_file_string);
2340
2341   return err;
2342 }
2343
2344 static void
2345 fill_in_fdata(frame_data *fdata, capture_file *cf,
2346               const struct wtap_pkthdr *phdr, gint64 offset)
2347 {
2348   fdata->next = NULL;
2349   fdata->prev = NULL;
2350   fdata->pfd = NULL;
2351   fdata->num = cf->count;
2352   fdata->pkt_len = phdr->len;
2353   cum_bytes += phdr->len;
2354   fdata->cum_bytes  = cum_bytes;
2355   fdata->cap_len = phdr->caplen;
2356   fdata->file_off = offset;
2357   /* To save some memory, we coarcese it into a gint8 */
2358   g_assert(phdr->pkt_encap <= G_MAXINT8);
2359   fdata->lnk_t = (gint8) phdr->pkt_encap;
2360   fdata->abs_ts.secs = phdr->ts.secs;
2361   fdata->abs_ts.nsecs = phdr->ts.nsecs;
2362   fdata->flags.passed_dfilter = 0;
2363   fdata->flags.encoding = CHAR_ASCII;
2364   fdata->flags.visited = 0;
2365   fdata->flags.marked = 0;
2366   fdata->flags.ref_time = 0;
2367   fdata->color_filter = NULL;
2368
2369   /* If we don't have the time stamp of the first packet in the
2370      capture, it's because this is the first packet.  Save the time
2371      stamp of this packet as the time stamp of the first packet. */
2372   if (nstime_is_unset(&first_ts)) {
2373     first_ts = fdata->abs_ts;
2374   }
2375
2376   /* If we don't have the time stamp of the previous captured packet,
2377      it's because this is the first packet.  Save the time
2378      stamp of this packet as the time stamp of the previous captured
2379      packet. */
2380   if (nstime_is_unset(&prev_cap_ts)) {
2381     prev_cap_ts = fdata->abs_ts;
2382   }
2383
2384   /* Get the time elapsed between the first packet and this packet. */
2385   nstime_delta(&fdata->rel_ts, &fdata->abs_ts, &first_ts);
2386
2387   /* If it's greater than the current elapsed time, set the elapsed time
2388      to it (we check for "greater than" so as not to be confused by
2389      time moving backwards). */
2390   if ((gint32)cf->elapsed_time.secs < fdata->rel_ts.secs
2391         || ((gint32)cf->elapsed_time.secs == fdata->rel_ts.secs && (gint32)cf->elapsed_time.nsecs < fdata->rel_ts.nsecs)) {
2392     cf->elapsed_time = fdata->rel_ts;
2393   }
2394
2395   /* If we don't have the time stamp of the previous displayed packet,
2396      it's because this is the first packet that's being displayed.  Save the time
2397      stamp of this packet as the time stamp of the previous displayed
2398      packet. */
2399   if (nstime_is_unset(&prev_dis_ts))
2400     prev_dis_ts = fdata->abs_ts;
2401
2402   /* Get the time elapsed between the previous displayed packet and
2403      this packet. */
2404   nstime_delta(&fdata->del_dis_ts, &fdata->abs_ts, &prev_dis_ts);
2405
2406   /* Get the time elapsed between the previous captured packet and
2407      this packet. */
2408   nstime_delta(&fdata->del_cap_ts, &fdata->abs_ts, &prev_cap_ts);
2409   prev_cap_ts = fdata->abs_ts;
2410 }
2411
2412 /* Free up all data attached to a "frame_data" structure. */
2413 static void
2414 clear_fdata(frame_data *fdata)
2415 {
2416   if (fdata->pfd)
2417     g_slist_free(fdata->pfd);
2418 }
2419
2420 static gboolean
2421 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
2422                union wtap_pseudo_header *pseudo_header, const guchar *pd,
2423                gboolean filtering_tap_listeners, guint tap_flags)
2424 {
2425   frame_data fdata;
2426   gboolean create_proto_tree;
2427   column_info *cinfo;
2428   epan_dissect_t edt;
2429   gboolean passed;
2430
2431   /* Count this packet. */
2432   cf->count++;
2433
2434   /* If we're going to print packet information, or we're going to
2435      run a read filter, or we're going to process taps, set up to
2436      do a dissection and do so. */
2437   if (do_dissection) {
2438     fill_in_fdata(&fdata, cf, whdr, offset);
2439
2440     if (print_packet_info) {
2441       /* Grab any resolved addresses */
2442
2443       if (g_resolv_flags) {
2444         host_name_lookup_process(NULL);
2445       }
2446     }
2447
2448     passed = TRUE;
2449     if (cf->rfcode || verbose || filtering_tap_listeners ||
2450         (tap_flags & TL_REQUIRES_PROTO_TREE) || have_custom_cols(&cf->cinfo))
2451       create_proto_tree = TRUE;
2452     else
2453       create_proto_tree = FALSE;
2454     /* The protocol tree will be "visible", i.e., printed, only if we're
2455        printing packet details, which is true if we're printing stuff
2456        ("print_packet_info" is true) and we're in verbose mode ("verbose"
2457        is true). */
2458     epan_dissect_init(&edt, create_proto_tree, print_packet_info && verbose);
2459
2460     /* If we're running a read filter, prime the epan_dissect_t with that
2461        filter. */
2462     if (cf->rfcode)
2463       epan_dissect_prime_dfilter(&edt, cf->rfcode);
2464
2465     col_custom_prime_edt(&edt, &cf->cinfo);
2466
2467     tap_queue_init(&edt);
2468
2469     /* We only need the columns if either
2470
2471          1) some tap needs the columns
2472
2473        or
2474
2475          2) we're printing packet info but we're *not* verbose; in verbose
2476             mode, we print the protocol tree, not the protocol summary. */
2477     if ((tap_flags & TL_REQUIRES_COLUMNS) || (print_packet_info && !verbose))
2478       cinfo = &cf->cinfo;
2479     else
2480       cinfo = NULL;
2481     epan_dissect_run(&edt, pseudo_header, pd, &fdata, cinfo);
2482
2483     tap_push_tapped_queue(&edt);
2484
2485     /* Run the read filter if we have one. */
2486     if (cf->rfcode)
2487       passed = dfilter_apply_edt(cf->rfcode, &edt);
2488     else
2489       passed = TRUE;
2490   } else {
2491     /* We're not running a display filter and we're not printing any
2492        packet information, so we don't need to do a dissection, and all
2493        packets are processed. */
2494     passed = TRUE;
2495   }
2496
2497   if (passed) {
2498     /* Keep the time of the current packet if the packet passed
2499        the read filter so that the delta time since last displayed
2500        packet can be calculated */
2501     prev_dis_ts = fdata.abs_ts;
2502
2503     /* Process this packet. */
2504     if (print_packet_info) {
2505       /* We're printing packet information; print the information for
2506          this packet. */
2507       if (do_dissection)
2508         print_packet(cf, &edt);
2509       else
2510         print_packet(cf, NULL);
2511
2512       /* The ANSI C standard does not appear to *require* that a line-buffered
2513          stream be flushed to the host environment whenever a newline is
2514          written, it just says that, on such a stream, characters "are
2515          intended to be transmitted to or from the host environment as a
2516          block when a new-line character is encountered".
2517
2518          The Visual C++ 6.0 C implementation doesn't do what is intended;
2519          even if you set a stream to be line-buffered, it still doesn't
2520          flush the buffer at the end of every line.
2521
2522          So, if the "-l" flag was specified, we flush the standard output
2523          at the end of a packet.  This will do the right thing if we're
2524          printing packet summary lines, and, as we print the entire protocol
2525          tree for a single packet without waiting for anything to happen,
2526          it should be as good as line-buffered mode if we're printing
2527          protocol trees.  (The whole reason for the "-l" flag in either
2528          tcpdump or TShark is to allow the output of a live capture to
2529          be piped to a program or script and to have that script see the
2530          information for the packet as soon as it's printed, rather than
2531          having to wait until a standard I/O buffer fills up. */
2532       if (line_buffered)
2533         fflush(stdout);
2534
2535       if (ferror(stdout)) {
2536         show_print_file_io_error(errno);
2537         exit(2);
2538       }
2539     }
2540   }
2541
2542   if (do_dissection) {
2543     epan_dissect_cleanup(&edt);
2544     clear_fdata(&fdata);
2545   }
2546   return passed;
2547 }
2548
2549 static void
2550 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
2551 {
2552   char *save_file_string;
2553
2554   save_file_string = output_file_description(fname);
2555
2556   switch (err) {
2557
2558   case ENOSPC:
2559     cmdarg_err("Not all the packets could be written to the %s because there is "
2560                "no space left on the file system.",
2561                save_file_string);
2562     break;
2563
2564 #ifdef EDQUOT
2565   case EDQUOT:
2566     cmdarg_err("Not all the packets could be written to the %s because you are "
2567                "too close to, or over your disk quota.",
2568                save_file_string);
2569   break;
2570 #endif
2571
2572   case WTAP_ERR_CANT_CLOSE:
2573     cmdarg_err("The %s couldn't be closed for some unknown reason.",
2574                save_file_string);
2575     break;
2576
2577   case WTAP_ERR_SHORT_WRITE:
2578     cmdarg_err("Not all the packets could be written to the %s.",
2579                save_file_string);
2580     break;
2581
2582   default:
2583     if (is_close) {
2584       cmdarg_err("The %s could not be closed: %s.", save_file_string,
2585                  wtap_strerror(err));
2586     } else {
2587       cmdarg_err("An error occurred while writing to the %s: %s.",
2588                  save_file_string, wtap_strerror(err));
2589     }
2590     break;
2591   }
2592   g_free(save_file_string);
2593 }
2594
2595 static gboolean
2596 write_preamble(capture_file *cf)
2597 {
2598   switch (output_action) {
2599
2600   case WRITE_TEXT:
2601     return print_preamble(print_stream, cf ? cf->filename : NULL);
2602
2603   case WRITE_XML:
2604     if (verbose)
2605       write_pdml_preamble(stdout);
2606     else
2607       write_psml_preamble(stdout);
2608     return !ferror(stdout);
2609
2610   case WRITE_FIELDS:
2611     write_fields_preamble(output_fields, stdout);
2612     return !ferror(stdout);
2613
2614   default:
2615     g_assert_not_reached();
2616     return FALSE;
2617   }
2618 }
2619
2620 static char *
2621 get_line_buf(size_t len)
2622 {
2623   static char *line_bufp = NULL;
2624   static size_t line_buf_len = 256;
2625   size_t new_line_buf_len;
2626
2627   for (new_line_buf_len = line_buf_len; len > new_line_buf_len;
2628        new_line_buf_len *= 2)
2629     ;
2630   if (line_bufp == NULL) {
2631     line_buf_len = new_line_buf_len;
2632     line_bufp = g_malloc(line_buf_len + 1);
2633   } else {
2634     if (new_line_buf_len > line_buf_len) {
2635       line_buf_len = new_line_buf_len;
2636       line_bufp = g_realloc(line_bufp, line_buf_len + 1);
2637     }
2638   }
2639   return line_bufp;
2640 }
2641
2642 static gboolean
2643 print_columns(capture_file *cf)
2644 {
2645   char *line_bufp;
2646   int i;
2647   size_t buf_offset;
2648   size_t column_len;
2649
2650   line_bufp = get_line_buf(256);
2651   buf_offset = 0;
2652   *line_bufp = '\0';
2653   for (i = 0; i < cf->cinfo.num_cols; i++) {
2654     switch (cf->cinfo.col_fmt[i]) {
2655     case COL_NUMBER:
2656 #ifdef HAVE_LIBPCAP
2657       /*
2658        * Don't print this if we're doing a live capture from a network
2659        * interface - if we're doing a live capture, you won't be
2660        * able to look at the capture in the future (it's not being
2661        * saved anywhere), so the frame numbers are unlikely to be
2662        * useful.
2663        *
2664        * (XXX - it might be nice to be able to save and print at
2665        * the same time, sort of like an "Update list of packets
2666        * in real time" capture in Wireshark.)
2667        */
2668       if (global_capture_opts.iface != NULL)
2669         continue;
2670 #endif
2671       column_len = strlen(cf->cinfo.col_data[i]);
2672       if (column_len < 3)
2673         column_len = 3;
2674       line_bufp = get_line_buf(buf_offset + column_len);
2675       sprintf(line_bufp + buf_offset, "%3s", cf->cinfo.col_data[i]);
2676       break;
2677
2678     case COL_CLS_TIME:
2679     case COL_REL_TIME:
2680     case COL_ABS_TIME:
2681     case COL_ABS_DATE_TIME: /* XXX - wider */
2682       column_len = strlen(cf->cinfo.col_data[i]);
2683       if (column_len < 10)
2684         column_len = 10;
2685       line_bufp = get_line_buf(buf_offset + column_len);
2686       sprintf(line_bufp + buf_offset, "%10s", cf->cinfo.col_data[i]);
2687       break;
2688
2689     case COL_DEF_SRC:
2690     case COL_RES_SRC:
2691     case COL_UNRES_SRC:
2692     case COL_DEF_DL_SRC:
2693     case COL_RES_DL_SRC:
2694     case COL_UNRES_DL_SRC:
2695     case COL_DEF_NET_SRC:
2696     case COL_RES_NET_SRC:
2697     case COL_UNRES_NET_SRC:
2698       column_len = strlen(cf->cinfo.col_data[i]);
2699       if (column_len < 12)
2700         column_len = 12;
2701       line_bufp = get_line_buf(buf_offset + column_len);
2702       sprintf(line_bufp + buf_offset, "%12s", cf->cinfo.col_data[i]);
2703       break;
2704
2705     case COL_DEF_DST:
2706     case COL_RES_DST:
2707     case COL_UNRES_DST:
2708     case COL_DEF_DL_DST:
2709     case COL_RES_DL_DST:
2710     case COL_UNRES_DL_DST:
2711     case COL_DEF_NET_DST:
2712     case COL_RES_NET_DST:
2713     case COL_UNRES_NET_DST:
2714       column_len = strlen(cf->cinfo.col_data[i]);
2715       if (column_len < 12)
2716         column_len = 12;
2717       line_bufp = get_line_buf(buf_offset + column_len);
2718       sprintf(line_bufp + buf_offset, "%-12s", cf->cinfo.col_data[i]);
2719       break;
2720
2721     default:
2722       column_len = strlen(cf->cinfo.col_data[i]);
2723       line_bufp = get_line_buf(buf_offset + column_len);
2724       strcat(line_bufp + buf_offset, cf->cinfo.col_data[i]);
2725       break;
2726     }
2727     buf_offset += column_len;
2728     if (i != cf->cinfo.num_cols - 1) {
2729       /*
2730        * This isn't the last column, so we need to print a
2731        * separator between this column and the next.
2732        *
2733        * If we printed a network source and are printing a
2734        * network destination of the same type next, separate
2735        * them with "->"; if we printed a network destination
2736        * and are printing a network source of the same type
2737        * next, separate them with "<-"; otherwise separate them
2738        * with a space.
2739        *
2740        * We add enough space to the buffer for " <- " or " -> ",
2741        * even if we're only adding " ".
2742        */
2743       line_bufp = get_line_buf(buf_offset + 4);
2744       switch (cf->cinfo.col_fmt[i]) {
2745
2746       case COL_DEF_SRC:
2747       case COL_RES_SRC:
2748       case COL_UNRES_SRC:
2749         switch (cf->cinfo.col_fmt[i + 1]) {
2750
2751         case COL_DEF_DST:
2752         case COL_RES_DST:
2753         case COL_UNRES_DST:
2754           strcat(line_bufp + buf_offset, " -> ");
2755           buf_offset += 4;
2756           break;
2757
2758         default:
2759           strcat(line_bufp + buf_offset, " ");
2760           buf_offset += 1;
2761           break;
2762         }
2763         break;
2764
2765       case COL_DEF_DL_SRC:
2766       case COL_RES_DL_SRC:
2767       case COL_UNRES_DL_SRC:
2768         switch (cf->cinfo.col_fmt[i + 1]) {
2769
2770         case COL_DEF_DL_DST:
2771         case COL_RES_DL_DST:
2772         case COL_UNRES_DL_DST:
2773           strcat(line_bufp + buf_offset, " -> ");
2774           buf_offset += 4;
2775           break;
2776
2777         default:
2778           strcat(line_bufp + buf_offset, " ");
2779           buf_offset += 1;
2780           break;
2781         }
2782         break;
2783
2784       case COL_DEF_NET_SRC:
2785       case COL_RES_NET_SRC:
2786       case COL_UNRES_NET_SRC:
2787         switch (cf->cinfo.col_fmt[i + 1]) {
2788
2789         case COL_DEF_NET_DST:
2790         case COL_RES_NET_DST:
2791         case COL_UNRES_NET_DST:
2792           strcat(line_bufp + buf_offset, " -> ");
2793           buf_offset += 4;
2794           break;
2795
2796         default:
2797           strcat(line_bufp + buf_offset, " ");
2798           buf_offset += 1;
2799           break;
2800         }
2801         break;
2802
2803       case COL_DEF_DST:
2804       case COL_RES_DST:
2805       case COL_UNRES_DST:
2806         switch (cf->cinfo.col_fmt[i + 1]) {
2807
2808         case COL_DEF_SRC:
2809         case COL_RES_SRC:
2810         case COL_UNRES_SRC:
2811           strcat(line_bufp + buf_offset, " <- ");
2812           buf_offset += 4;
2813           break;
2814
2815         default:
2816           strcat(line_bufp + buf_offset, " ");
2817           buf_offset += 1;
2818           break;
2819         }
2820         break;
2821
2822       case COL_DEF_DL_DST:
2823       case COL_RES_DL_DST:
2824       case COL_UNRES_DL_DST:
2825         switch (cf->cinfo.col_fmt[i + 1]) {
2826
2827         case COL_DEF_DL_SRC:
2828         case COL_RES_DL_SRC:
2829         case COL_UNRES_DL_SRC:
2830           strcat(line_bufp + buf_offset, " <- ");
2831           buf_offset += 4;
2832           break;
2833
2834         default:
2835           strcat(line_bufp + buf_offset, " ");
2836           buf_offset += 1;
2837           break;
2838         }
2839         break;
2840
2841       case COL_DEF_NET_DST:
2842       case COL_RES_NET_DST:
2843       case COL_UNRES_NET_DST:
2844         switch (cf->cinfo.col_fmt[i + 1]) {
2845
2846         case COL_DEF_NET_SRC:
2847         case COL_RES_NET_SRC:
2848         case COL_UNRES_NET_SRC:
2849           strcat(line_bufp + buf_offset, " <- ");
2850           buf_offset += 4;
2851           break;
2852
2853         default:
2854           strcat(line_bufp + buf_offset, " ");
2855           buf_offset += 1;
2856           break;
2857         }
2858         break;
2859
2860       default:
2861         strcat(line_bufp + buf_offset, " ");
2862         buf_offset += 1;
2863         break;
2864       }
2865     }
2866   }
2867   return print_line(print_stream, 0, line_bufp);
2868 }
2869
2870 static gboolean
2871 print_packet(capture_file *cf, epan_dissect_t *edt)
2872 {
2873   print_args_t  print_args;
2874
2875   if (verbose) {
2876     /* Print the information in the protocol tree. */
2877     switch (output_action) {
2878
2879     case WRITE_TEXT:
2880       print_args.to_file = TRUE;
2881       print_args.format = print_format;
2882       print_args.print_summary = !verbose;
2883       print_args.print_hex = verbose && print_hex;
2884       print_args.print_formfeed = FALSE;
2885       print_args.print_dissections = verbose ? print_dissections_expanded : print_dissections_none;
2886
2887       /* init the packet range */
2888       packet_range_init(&print_args.range);
2889
2890       if (!proto_tree_print(&print_args, edt, print_stream))
2891         return FALSE;
2892       if (!print_hex) {
2893         /* "print_hex_data()" will put out a leading blank line, as well
2894          as a trailing one; print one here, to separate the packets,
2895          only if "print_hex_data()" won't be called. */
2896         if (!print_line(print_stream, 0, ""))
2897           return FALSE;
2898       }
2899       break;
2900
2901     case WRITE_XML:
2902       proto_tree_write_pdml(edt, stdout);
2903       printf("\n");
2904       return !ferror(stdout);
2905     case WRITE_FIELDS:
2906       proto_tree_write_fields(output_fields, edt, stdout);
2907       printf("\n");
2908       return !ferror(stdout);
2909     }
2910   } else {
2911     /* Just fill in the columns. */
2912     epan_dissect_fill_in_columns(edt, FALSE, TRUE);
2913
2914     /* Now print them. */
2915     switch (output_action) {
2916
2917     case WRITE_TEXT:
2918         if (!print_columns(cf))
2919           return FALSE;
2920         break;
2921
2922     case WRITE_XML:
2923         proto_tree_write_psml(edt, stdout);
2924         return !ferror(stdout);
2925     case WRITE_FIELDS: /*No non-verbose "fields" format */
2926         g_assert_not_reached();
2927         break;
2928     }
2929   }
2930   if (print_hex) {
2931     if (!print_hex_data(print_stream, edt))
2932       return FALSE;
2933     if (!print_line(print_stream, 0, ""))
2934       return FALSE;
2935   }
2936   return TRUE;
2937 }
2938
2939 static gboolean
2940 write_finale(void)
2941 {
2942   switch (output_action) {
2943
2944   case WRITE_TEXT:
2945     return print_finale(print_stream);
2946
2947   case WRITE_XML:
2948     if (verbose)
2949       write_pdml_finale(stdout);
2950     else
2951       write_psml_finale(stdout);
2952     return !ferror(stdout);
2953
2954   case WRITE_FIELDS:
2955     write_fields_finale(output_fields, stdout);
2956     return !ferror(stdout);
2957
2958   default:
2959     g_assert_not_reached();
2960     return FALSE;
2961   }
2962 }
2963
2964 static void
2965 show_print_file_io_error(int err)
2966 {
2967   switch (err) {
2968
2969   case ENOSPC:
2970     cmdarg_err("Not all the packets could be printed because there is "
2971 "no space left on the file system.");
2972     break;
2973
2974 #ifdef EDQUOT
2975   case EDQUOT:
2976     cmdarg_err("Not all the packets could be printed because you are "
2977 "too close to, or over your disk quota.");
2978   break;
2979 #endif
2980
2981   default:
2982     cmdarg_err("An error occurred while printing packets: %s.",
2983       strerror(err));
2984     break;
2985   }
2986 }
2987
2988 static const char *
2989 cf_open_error_message(int err, gchar *err_info, gboolean for_writing,
2990                       int file_type)
2991 {
2992   const char *errmsg;
2993   static char errmsg_errno[1024+1];
2994
2995   if (err < 0) {
2996     /* Wiretap error. */
2997     switch (err) {
2998
2999     case WTAP_ERR_NOT_REGULAR_FILE:
3000       errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
3001       break;
3002
3003     case WTAP_ERR_FILE_UNKNOWN_FORMAT:
3004       /* Seen only when opening a capture file for reading. */
3005       errmsg = "The file \"%s\" isn't a capture file in a format TShark understands.";
3006       break;
3007
3008     case WTAP_ERR_UNSUPPORTED:
3009       /* Seen only when opening a capture file for reading. */
3010       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3011                "The file \"%%s\" isn't a capture file in a format TShark understands.\n"
3012                "(%s)", err_info);
3013       g_free(err_info);
3014       errmsg = errmsg_errno;
3015       break;
3016
3017     case WTAP_ERR_CANT_WRITE_TO_PIPE:
3018       /* Seen only when opening a capture file for writing. */
3019       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3020                  "The file \"%%s\" is a pipe, and %s capture files can't be "
3021                  "written to a pipe.", wtap_file_type_string(file_type));
3022       errmsg = errmsg_errno;
3023       break;
3024
3025     case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
3026       /* Seen only when opening a capture file for writing. */
3027       errmsg = "TShark doesn't support writing capture files in that format.";
3028       break;
3029
3030     case WTAP_ERR_UNSUPPORTED_ENCAP:
3031       if (for_writing)
3032         errmsg = "TShark can't save this capture in that format.";
3033       else {
3034         g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3035                  "The file \"%%s\" is a capture for a network type that TShark doesn't support.\n"
3036                  "(%s)", err_info);
3037         g_free(err_info);
3038         errmsg = errmsg_errno;
3039       }
3040       break;
3041
3042     case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
3043       if (for_writing)
3044         errmsg = "TShark can't save this capture in that format.";
3045       else
3046         errmsg = "The file \"%s\" is a capture for a network type that TShark doesn't support.";
3047       break;
3048
3049     case WTAP_ERR_BAD_RECORD:
3050       /* Seen only when opening a capture file for reading. */
3051       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3052                "The file \"%%s\" appears to be damaged or corrupt.\n"
3053                "(%s)", err_info);
3054       g_free(err_info);
3055       errmsg = errmsg_errno;
3056       break;
3057
3058     case WTAP_ERR_CANT_OPEN:
3059       if (for_writing)
3060         errmsg = "The file \"%s\" could not be created for some unknown reason.";
3061       else
3062         errmsg = "The file \"%s\" could not be opened for some unknown reason.";
3063       break;
3064
3065     case WTAP_ERR_SHORT_READ:
3066       errmsg = "The file \"%s\" appears to have been cut short"
3067                " in the middle of a packet or other data.";
3068       break;
3069
3070     case WTAP_ERR_SHORT_WRITE:
3071       errmsg = "A full header couldn't be written to the file \"%s\".";
3072       break;
3073
3074     default:
3075       g_snprintf(errmsg_errno, sizeof(errmsg_errno),
3076                  "The file \"%%s\" could not be %s: %s.",
3077                  for_writing ? "created" : "opened",
3078                  wtap_strerror(err));
3079       errmsg = errmsg_errno;
3080       break;
3081     }
3082   } else
3083     errmsg = file_open_error_message(err, for_writing);
3084   return errmsg;
3085 }
3086
3087 /*
3088  * Open/create errors are reported with an console message in TShark.
3089  */
3090 static void
3091 open_failure_message(const char *filename, int err, gboolean for_writing)
3092 {
3093   fprintf(stderr, "tshark: ");
3094   fprintf(stderr, file_open_error_message(err, for_writing), filename);
3095   fprintf(stderr, "\n");
3096 }
3097
3098 cf_status_t
3099 cf_open(capture_file *cf, const char *fname, gboolean is_tempfile, int *err)
3100 {
3101   wtap       *wth;
3102   gchar       *err_info;
3103   char        err_msg[2048+1];
3104
3105   wth = wtap_open_offline(fname, err, &err_info, FALSE);
3106   if (wth == NULL)
3107     goto fail;
3108
3109   /* The open succeeded.  Fill in the information for this file. */
3110
3111   /* Cleanup all data structures used for dissection. */
3112   cleanup_dissection();
3113   /* Initialize all data structures used for dissection. */
3114   init_dissection();
3115
3116   cf->wth = wth;
3117   cf->f_datalen = 0; /* not used, but set it anyway */
3118
3119   /* Set the file name because we need it to set the follow stream filter.
3120      XXX - is that still true?  We need it for other reasons, though,
3121      in any case. */
3122   cf->filename = g_strdup(fname);
3123
3124   /* Indicate whether it's a permanent or temporary file. */
3125   cf->is_tempfile = is_tempfile;
3126
3127   /* If it's a temporary capture buffer file, mark it as not saved. */
3128   cf->user_saved = !is_tempfile;
3129
3130   cf->cd_t      = wtap_file_type(cf->wth);
3131   cf->count     = 0;
3132   cf->drops_known = FALSE;
3133   cf->drops     = 0;
3134   cf->snap      = wtap_snapshot_length(cf->wth);
3135   if (cf->snap == 0) {
3136     /* Snapshot length not known. */
3137     cf->has_snap = FALSE;
3138     cf->snap = WTAP_MAX_PACKET_SIZE;
3139   } else
3140     cf->has_snap = TRUE;
3141   nstime_set_zero(&cf->elapsed_time);
3142   nstime_set_unset(&first_ts);
3143   nstime_set_unset(&prev_dis_ts);
3144   nstime_set_unset(&prev_cap_ts);
3145
3146   cf->state = FILE_READ_IN_PROGRESS;
3147
3148   return CF_OK;
3149
3150 fail:
3151   g_snprintf(err_msg, sizeof err_msg,
3152              cf_open_error_message(*err, err_info, FALSE, cf->cd_t), fname);
3153   cmdarg_err("%s", err_msg);
3154   return CF_ERROR;
3155 }
3156
3157
3158 /*
3159  * General errors are reported with an console message in TShark.
3160  */
3161 static void
3162 failure_message(const char *msg_format, va_list ap)
3163 {
3164   fprintf(stderr, "tshark: ");
3165   vfprintf(stderr, msg_format, ap);
3166   fprintf(stderr, "\n");
3167 }
3168
3169 /*
3170  * Read errors are reported with an console message in TShark.
3171  */
3172 static void
3173 read_failure_message(const char *filename, int err)
3174 {
3175   cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
3176           filename, strerror(err));
3177 }
3178
3179 /*
3180  * Write errors are reported with an console message in TShark.
3181  */
3182 static void
3183 write_failure_message(const char *filename, int err)
3184 {
3185   cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
3186           filename, strerror(err));
3187 }
3188
3189 /*
3190  * Report an error in command-line arguments.
3191  */
3192 void
3193 cmdarg_err(const char *fmt, ...)
3194 {
3195   va_list ap;
3196
3197   va_start(ap, fmt);
3198   failure_message(fmt, ap);
3199   va_end(ap);
3200 }
3201
3202 /*
3203  * Report additional information for an error in command-line arguments.
3204  */
3205 void
3206 cmdarg_err_cont(const char *fmt, ...)
3207 {
3208   va_list ap;
3209
3210   va_start(ap, fmt);
3211   vfprintf(stderr, fmt, ap);
3212   fprintf(stderr, "\n");
3213   va_end(ap);
3214 }