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