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