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