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