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