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