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