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