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