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