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