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