7df9475fb2a0982507648b15c582da2e29c256ab
[metze/wireshark/wip.git] / rawshark.c
1 /* rawshark.c
2  *
3  * $Id$
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * Rawshark - Raw field extractor by Gerald Combs <gerald@wireshark.org>
10  * and Loris Degioanni <loris.degioanni@cacetech.com>
11  * Based on TShark, by Gilbert Ramirez <gram@alumni.rice.edu> and Guy Harris
12  * <guy@alum.mit.edu>.
13  *
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27  */
28
29 /*
30  * Rawshark does the following:
31  * - Opens a specified file or named pipe
32  * - Applies a specfied DLT or "decode as" encapsulation
33  * - Reads frames prepended with a libpcap packet header.
34  * - Prints a status line, followed by fields from a specified list.
35  */
36
37 #include "config.h"
38
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include <locale.h>
44 #include <limits.h>
45
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49
50 #include <errno.h>
51
52 #ifdef HAVE_FCNTL_H
53 #include <fcntl.h>
54 #endif
55
56 #include <signal.h>
57
58 #ifdef HAVE_SYS_STAT_H
59 # include <sys/stat.h>
60 #endif
61
62 #ifndef HAVE_GETOPT
63 #include "wsutil/wsgetopt.h"
64 #endif
65
66 #include <glib.h>
67 #include <epan/epan.h>
68 #include <epan/filesystem.h>
69 #include <wsutil/privileges.h>
70 #include <wsutil/file_util.h>
71
72 #include "globals.h"
73 #include <epan/packet.h>
74 #include "file.h"
75 #include "disabled_protos.h"
76 #include <epan/prefs.h>
77 #include <epan/column.h>
78 #include "print.h"
79 #include <epan/addr_resolv.h>
80 #include "ui/util.h"
81 #include "clopts_common.h"
82 #include "cmdarg_err.h"
83 #include "version_info.h"
84 #include <epan/plugins.h>
85 #include "register.h"
86 #include "conditions.h"
87 #include "capture_stop_conditions.h"
88 #include "capture_ui_utils.h"
89 #include <epan/epan_dissect.h>
90 #include <epan/stat_cmd_args.h>
91 #include <epan/timestamp.h>
92 #include <wsutil/unicode-utils.h>
93 #include "epan/column-utils.h"
94 #include "epan/proto.h"
95 #include <epan/tap.h>
96
97 #include <wiretap/wtap.h>
98 #include <wiretap/libpcap.h>
99 #include <wiretap/pcap-encap.h>
100
101 #ifdef HAVE_LIBPCAP
102 #include <setjmp.h>
103 #include "capture-pcap-util.h"
104 #include "pcapio.h"
105 #ifdef _WIN32
106 #include "capture-wpcap.h"
107 #endif /* _WIN32 */
108 #endif /* HAVE_LIBPCAP */
109 #include "log.h"
110
111 #ifdef _WIN32
112 #include <wsutil/unicode-utils.h>
113 #endif /* _WIN32 */
114
115 /*
116  * This is the template for the decode as option; it is shared between the
117  * various functions that output the usage for this parameter.
118  */
119 static const gchar decode_as_arg_template[] = "<layer_type>==<selector>,<decode_as_protocol>";
120
121 static guint32 cum_bytes;
122 static nstime_t first_ts;
123 static nstime_t prev_dis_ts;
124 static nstime_t prev_cap_ts;
125
126 /*
127  * The way the packet decode is to be written.
128  */
129 typedef enum {
130     WRITE_TEXT, /* summary or detail text */
131     WRITE_XML   /* PDML or PSML */
132     /* Add CSV and the like here */
133 } output_action_e;
134
135 static gboolean line_buffered;
136 static print_format_e print_format = PR_FMT_TEXT;
137
138 static gboolean want_pcap_pkthdr;
139
140 cf_status_t raw_cf_open(capture_file *cf, const char *fname);
141 static int load_cap_file(capture_file *cf);
142 static gboolean process_packet(capture_file *cf, gint64 offset,
143                                const struct wtap_pkthdr *whdr, const guchar *pd);
144 static void show_print_file_io_error(int err);
145
146 static void open_failure_message(const char *filename, int err,
147                                  gboolean for_writing);
148 static void failure_message(const char *msg_format, va_list ap);
149 static void read_failure_message(const char *filename, int err);
150 static void write_failure_message(const char *filename, int err);
151 static void protocolinfo_init(char *field);
152 static gboolean parse_field_string_format(char *format);
153
154 typedef enum {
155     SF_NONE,    /* No format (placeholder) */
156     SF_NAME,    /* %D Field name / description */
157     SF_NUMVAL,  /* %N Numeric value */
158     SF_STRVAL   /* %S String value */
159 } string_fmt_e;
160
161 typedef struct string_fmt_s {
162     gchar *plain;
163     string_fmt_e format;    /* Valid if plain is NULL */
164 } string_fmt_t;
165
166 capture_file cfile;
167 int n_rfilters;
168 int n_rfcodes;
169 dfilter_t *rfcodes[64];
170 int n_rfieldfilters;
171 dfilter_t *rfieldfcodes[64];
172 int fd;
173 int encap;
174 GPtrArray *string_fmts;
175
176 static void
177 print_usage(gboolean print_ver)
178 {
179     FILE *output;
180
181     if (print_ver) {
182         output = stdout;
183         fprintf(output,
184                 "Rawshark " VERSION "%s\n"
185                 "Dump and analyze network traffic.\n"
186                 "See http://www.wireshark.org for more information.\n"
187                 "\n"
188                 "%s",
189                 wireshark_svnversion, get_copyright_info());
190     } else {
191         output = stderr;
192     }
193     fprintf(output, "\n");
194     fprintf(output, "Usage: rawshark [options] ...\n");
195     fprintf(output, "\n");
196
197     fprintf(output, "Input file:\n");
198     fprintf(output, "  -r <infile>              set the pipe or file name to read from\n");
199
200     fprintf(output, "\n");
201     fprintf(output, "Processing:\n");
202     fprintf(output, "  -d <encap:dlt>|<proto:protoname>\n");
203     fprintf(output, "                           packet encapsulation or protocol\n");
204     fprintf(output, "  -F <field>               field to display\n");
205     fprintf(output, "  -n                       disable all name resolution (def: all enabled)\n");
206     fprintf(output, "  -N <name resolve flags>  enable specific name resolution(s): \"mntC\"\n");
207     fprintf(output, "  -p                       use the system's packet header format\n");
208     fprintf(output, "                           (which may have 64-bit timestamps)\n");
209     fprintf(output, "  -R <read filter>         packet filter in Wireshark display filter syntax\n");
210     fprintf(output, "  -s                       skip PCAP header on input\n");
211
212     fprintf(output, "\n");
213     fprintf(output, "Output:\n");
214     fprintf(output, "  -l                       flush output after each packet\n");
215     fprintf(output, "  -S                       format string for fields\n");
216     fprintf(output, "                           (%%D - name, %%S - stringval, %%N numval)\n");
217     fprintf(output, "  -t ad|a|r|d|dd|e         output format of time stamps (def: r: rel. to first)\n");
218
219     fprintf(output, "\n");
220     fprintf(output, "Miscellaneous:\n");
221     fprintf(output, "  -h                       display this help and exit\n");
222     fprintf(output, "  -o <name>:<value> ...    override preference setting\n");
223     fprintf(output, "  -v                       display version info and exit\n");
224 }
225
226 static void
227 log_func_ignore (const gchar *log_domain _U_, GLogLevelFlags log_level _U_,
228                  const gchar *message _U_, gpointer user_data _U_)
229 {
230 }
231
232 /**
233  * Open a pipe for raw input.  This is a stripped-down version of
234  * pcap_loop.c:cap_pipe_open_live().
235  * We check if "pipe_name" is "-" (stdin) or a FIFO, and open it.
236  * @param pipe_name The name of the pipe or FIFO.
237  * @return A POSIX file descriptor on success, or -1 on failure.
238  */
239 static int
240 raw_pipe_open(const char *pipe_name)
241 {
242 #ifndef _WIN32
243     ws_statb64 pipe_stat;
244 #else
245     char *pncopy, *pos = NULL;
246     DWORD err;
247     wchar_t *err_str;
248     HANDLE hPipe = NULL;
249 #endif
250     int          rfd;
251
252     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_raw_pipe: %s", pipe_name);
253
254     /*
255      * XXX Rawshark blocks until we return
256      */
257     if (strcmp(pipe_name, "-") == 0) {
258         rfd = 0; /* read from stdin */
259 #ifdef _WIN32
260         /*
261          * This is needed to set the stdin pipe into binary mode, otherwise
262          * CR/LF are mangled...
263          */
264         _setmode(0, _O_BINARY);
265 #endif  /* _WIN32 */
266     } else {
267 #ifndef _WIN32
268         if (ws_stat64(pipe_name, &pipe_stat) < 0) {
269             fprintf(stderr, "rawshark: The pipe %s could not be checked: %s\n",
270                     pipe_name, g_strerror(errno));
271             return -1;
272         }
273         if (! S_ISFIFO(pipe_stat.st_mode)) {
274             if (S_ISCHR(pipe_stat.st_mode)) {
275                 /*
276                  * Assume the user specified an interface on a system where
277                  * interfaces are in /dev.  Pretend we haven't seen it.
278                  */
279             } else
280             {
281                 fprintf(stderr, "rawshark: \"%s\" is neither an interface nor a pipe\n",
282                         pipe_name);
283             }
284             return -1;
285         }
286         rfd = ws_open(pipe_name, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
287         if (rfd == -1) {
288             fprintf(stderr, "rawshark: \"%s\" could not be opened: %s\n",
289                     pipe_name, g_strerror(errno));
290             return -1;
291         }
292 #else /* _WIN32 */
293 #define PIPE_STR "\\pipe\\"
294         /* Under Windows, named pipes _must_ have the form
295          * "\\<server>\pipe\<pipe_name>".  <server> may be "." for localhost.
296          */
297         pncopy = g_strdup(pipe_name);
298         if (strstr(pncopy, "\\\\") == pncopy) {
299             pos = strchr(pncopy + 3, '\\');
300             if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
301                 pos = NULL;
302         }
303
304         g_free(pncopy);
305
306         if (!pos) {
307             fprintf(stderr, "rawshark: \"%s\" is neither an interface nor a pipe\n",
308                     pipe_name);
309             return -1;
310         }
311
312         /* Wait for the pipe to appear */
313         while (1) {
314             hPipe = CreateFile(utf_8to16(pipe_name), GENERIC_READ, 0, NULL,
315                                OPEN_EXISTING, 0, NULL);
316
317             if (hPipe != INVALID_HANDLE_VALUE)
318                 break;
319
320             err = GetLastError();
321             if (err != ERROR_PIPE_BUSY) {
322                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
323                               NULL, err, 0, (LPTSTR) &err_str, 0, NULL);
324                 fprintf(stderr, "rawshark: \"%s\" could not be opened: %s (error %d)\n",
325                         pipe_name, utf_16to8(err_str), err);
326                 LocalFree(err_str);
327                 return -1;
328             }
329
330             if (!WaitNamedPipe(utf_8to16(pipe_name), 30 * 1000)) {
331                 err = GetLastError();
332                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
333                               NULL, err, 0, (LPTSTR) &err_str, 0, NULL);
334                 fprintf(stderr, "rawshark: \"%s\" could not be waited for: %s (error %d)\n",
335                         pipe_name, utf_16to8(err_str), err);
336                 LocalFree(err_str);
337                 return -1;
338             }
339         }
340
341         rfd = _open_osfhandle((long) hPipe, _O_RDONLY);
342         if (rfd == -1) {
343             fprintf(stderr, "rawshark: \"%s\" could not be opened: %s\n",
344                     pipe_name, g_strerror(errno));
345             return -1;
346         }
347 #endif /* _WIN32 */
348     }
349
350     return rfd;
351 }
352
353 /**
354  * Parse a link-type argument of the form "encap:<pcap dlt>" or
355  * "proto:<proto name>".  "Pcap dlt" must be a name conforming to
356  * pcap_datalink_name_to_val() or an integer.  "Proto name" must be
357  * a protocol name, e.g. "http".
358  */
359 static gboolean
360 set_link_type(const char *lt_arg) {
361     char *spec_ptr = strchr(lt_arg, ':');
362     char *p;
363     int dlt_val;
364     long val;
365     dissector_handle_t dhandle;
366     GString *pref_str;
367
368     if (!spec_ptr)
369         return FALSE;
370
371     spec_ptr++;
372
373     if (strncmp(lt_arg, "encap:", strlen("encap:")) == 0) {
374         dlt_val = linktype_name_to_val(spec_ptr);
375         if (dlt_val == -1) {
376             errno = 0;
377             val = strtol(spec_ptr, &p, 10);
378             if (p == spec_ptr || *p != '\0' || errno != 0 || val > INT_MAX) {
379                 return FALSE;
380             }
381             dlt_val = (int)val;
382         }
383         encap = wtap_pcap_encap_to_wtap_encap(dlt_val);
384         if (encap == WTAP_ENCAP_UNKNOWN) {
385             return FALSE;
386         }
387         return TRUE;
388     } else if (strncmp(lt_arg, "proto:", strlen("proto:")) == 0) {
389         dhandle = find_dissector(spec_ptr);
390         if (dhandle) {
391             encap = WTAP_ENCAP_USER0;
392             pref_str = g_string_new("uat:user_dlts:");
393             /* This must match the format used in the user_dlts file */
394             g_string_append_printf(pref_str,
395                                    "\"User 0 (DLT=147)\",\"%s\",\"0\",\"\",\"0\",\"\"",
396                                    spec_ptr);
397             if (prefs_set_pref(pref_str->str) != PREFS_SET_OK) {
398                 g_string_free(pref_str, TRUE);
399                 return FALSE;
400             }
401             g_string_free(pref_str, TRUE);
402             return TRUE;
403         }
404     }
405     return FALSE;
406 }
407
408 static void
409 show_version(GString *comp_info_str, GString *runtime_info_str)
410 {
411     printf("Rawshark " VERSION "%s\n"
412            "\n"
413            "%s"
414            "\n"
415            "%s"
416            "\n"
417            "%s",
418            wireshark_svnversion, get_copyright_info(), comp_info_str->str,
419            runtime_info_str->str);
420 }
421
422 int
423 main(int argc, char *argv[])
424 {
425     char                *init_progfile_dir_error;
426     int                  opt, i;
427     gboolean             arg_error = FALSE;
428
429 #ifdef _WIN32
430     WSADATA              wsaData;
431 #endif  /* _WIN32 */
432
433     char                *gpf_path, *pf_path;
434     char                *gdp_path, *dp_path;
435     int                  gpf_open_errno, gpf_read_errno;
436     int                  pf_open_errno, pf_read_errno;
437     int                  gdp_open_errno, gdp_read_errno;
438     int                  dp_open_errno, dp_read_errno;
439     int                  err;
440     gchar               *pipe_name = NULL;
441     gchar               *rfilters[64];
442     e_prefs             *prefs_p;
443     char                 badopt;
444     GLogLevelFlags       log_flags;
445     GPtrArray           *disp_fields = g_ptr_array_new();
446     guint                fc;
447     gboolean             skip_pcap_header = FALSE;
448
449 #define OPTSTRING_INIT "d:F:hlnN:o:pr:R:sS:t:v"
450
451     static const char    optstring[] = OPTSTRING_INIT;
452
453 #ifdef _WIN32
454     arg_list_utf_16to8(argc, argv);
455 #endif /* _WIN32 */
456
457     /*
458      * Get credential information for later use.
459      */
460     init_process_policies();
461
462     /*
463      * Clear the filters arrays
464      */
465     memset(rfilters, 0, sizeof(rfilters));
466     memset(rfcodes, 0, sizeof(rfcodes));
467     n_rfilters = 0;
468     n_rfcodes = 0;
469
470     /*
471      * Initialize our string format
472      */
473     string_fmts = g_ptr_array_new();
474
475     /*
476      * Attempt to get the pathname of the executable file.
477      */
478     init_progfile_dir_error = init_progfile_dir(argv[0], main);
479     if (init_progfile_dir_error != NULL) {
480         fprintf(stderr, "rawshark: Can't get pathname of rawshark program: %s.\n",
481                 init_progfile_dir_error);
482     }
483
484     /*
485      * Get credential information for later use.
486      */
487     init_process_policies();
488
489     /* nothing more than the standard GLib handler, but without a warning */
490     log_flags =
491         G_LOG_LEVEL_WARNING |
492         G_LOG_LEVEL_MESSAGE |
493         G_LOG_LEVEL_INFO |
494         G_LOG_LEVEL_DEBUG;
495
496     g_log_set_handler(NULL,
497                       log_flags,
498                       log_func_ignore, NULL /* user_data */);
499     g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
500                       log_flags,
501                       log_func_ignore, NULL /* user_data */);
502
503     timestamp_set_type(TS_RELATIVE);
504     timestamp_set_precision(TS_PREC_AUTO);
505     timestamp_set_seconds_type(TS_SECONDS_DEFAULT);
506
507     /* Register all dissectors; we must do this before checking for the
508        "-G" flag, as the "-G" flag dumps information registered by the
509        dissectors, and we must do it before we read the preferences, in
510        case any dissectors register preferences. */
511     epan_init(register_all_protocols, register_all_protocol_handoffs, NULL, NULL,
512               failure_message, open_failure_message, read_failure_message,
513               write_failure_message);
514
515     /* Set the C-language locale to the native environment. */
516     setlocale(LC_ALL, "");
517
518     prefs_p = read_prefs(&gpf_open_errno, &gpf_read_errno, &gpf_path,
519                          &pf_open_errno, &pf_read_errno, &pf_path);
520     if (gpf_path != NULL) {
521         if (gpf_open_errno != 0) {
522             cmdarg_err("Can't open global preferences file \"%s\": %s.",
523                        pf_path, g_strerror(gpf_open_errno));
524         }
525         if (gpf_read_errno != 0) {
526             cmdarg_err("I/O error reading global preferences file \"%s\": %s.",
527                        pf_path, g_strerror(gpf_read_errno));
528         }
529     }
530     if (pf_path != NULL) {
531         if (pf_open_errno != 0) {
532             cmdarg_err("Can't open your preferences file \"%s\": %s.", pf_path,
533                        g_strerror(pf_open_errno));
534         }
535         if (pf_read_errno != 0) {
536             cmdarg_err("I/O error reading your preferences file \"%s\": %s.",
537                        pf_path, g_strerror(pf_read_errno));
538         }
539         g_free(pf_path);
540         pf_path = NULL;
541     }
542
543     /* Read the disabled protocols file. */
544     read_disabled_protos_list(&gdp_path, &gdp_open_errno, &gdp_read_errno,
545                               &dp_path, &dp_open_errno, &dp_read_errno);
546     if (gdp_path != NULL) {
547         if (gdp_open_errno != 0) {
548             cmdarg_err("Could not open global disabled protocols file\n\"%s\": %s.",
549                        gdp_path, g_strerror(gdp_open_errno));
550         }
551         if (gdp_read_errno != 0) {
552             cmdarg_err("I/O error reading global disabled protocols file\n\"%s\": %s.",
553                        gdp_path, g_strerror(gdp_read_errno));
554         }
555         g_free(gdp_path);
556     }
557     if (dp_path != NULL) {
558         if (dp_open_errno != 0) {
559             cmdarg_err(
560                 "Could not open your disabled protocols file\n\"%s\": %s.", dp_path,
561                 g_strerror(dp_open_errno));
562         }
563         if (dp_read_errno != 0) {
564             cmdarg_err(
565                 "I/O error reading your disabled protocols file\n\"%s\": %s.", dp_path,
566                 g_strerror(dp_read_errno));
567         }
568         g_free(dp_path);
569     }
570
571 #ifdef _WIN32
572     /* Load Wpcap, if possible */
573     load_wpcap();
574 #endif
575
576     cap_file_init(&cfile);
577
578     /* Print format defaults to this. */
579     print_format = PR_FMT_TEXT;
580
581     /* Initialize our encapsulation type */
582     encap = WTAP_ENCAP_UNKNOWN;
583
584     /* Now get our args */
585     /* XXX - We should probably have an option to dump libpcap link types */
586     while ((opt = getopt(argc, argv, optstring)) != -1) {
587         switch (opt) {
588             case 'd':        /* Payload type */
589                 if (!set_link_type(optarg)) {
590                     cmdarg_err("Invalid link type or protocol \"%s\"", optarg);
591                     exit(1);
592                 }
593                 break;
594             case 'F':        /* Read field to display */
595                 g_ptr_array_add(disp_fields, g_strdup(optarg));
596                 break;
597             case 'h':        /* Print help and exit */
598                 print_usage(TRUE);
599                 exit(0);
600                 break;
601             case 'l':        /* "Line-buffer" standard output */
602                 /* This isn't line-buffering, strictly speaking, it's just
603                    flushing the standard output after the information for
604                    each packet is printed; however, that should be good
605                    enough for all the purposes to which "-l" is put (and
606                    is probably actually better for "-V", as it does fewer
607                    writes).
608
609                    See the comment in "process_packet()" for an explanation of
610                    why we do that, and why we don't just use "setvbuf()" to
611                    make the standard output line-buffered (short version: in
612                    Windows, "line-buffered" is the same as "fully-buffered",
613                    and the output buffer is only flushed when it fills up). */
614                 line_buffered = TRUE;
615                 break;
616             case 'n':        /* No name resolution */
617                 gbl_resolv_flags.mac_name = FALSE;
618                 gbl_resolv_flags.network_name = FALSE;
619                 gbl_resolv_flags.transport_name = FALSE;
620                 gbl_resolv_flags.concurrent_dns = FALSE;
621                 break;
622             case 'N':        /* Select what types of addresses/port #s to resolve */
623                 badopt = string_to_name_resolve(optarg, &gbl_resolv_flags);
624                 if (badopt != '\0') {
625                     cmdarg_err("-N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'",
626                                badopt);
627                     exit(1);
628                 }
629                 break;
630             case 'o':        /* Override preference from command line */
631                 switch (prefs_set_pref(optarg)) {
632
633                     case PREFS_SET_OK:
634                         break;
635
636                     case PREFS_SET_SYNTAX_ERR:
637                         cmdarg_err("Invalid -o flag \"%s\"", optarg);
638                         exit(1);
639                         break;
640
641                     case PREFS_SET_NO_SUCH_PREF:
642                     case PREFS_SET_OBSOLETE:
643                         cmdarg_err("-o flag \"%s\" specifies unknown preference", optarg);
644                         exit(1);
645                         break;
646                 }
647                 break;
648             case 'p':        /* Expect pcap_pkthdr packet headers, which may have 64-bit timestamps */
649                 want_pcap_pkthdr = TRUE;
650                 break;
651             case 'r':        /* Read capture file xxx */
652                 pipe_name = g_strdup(optarg);
653                 break;
654             case 'R':        /* Read file filter */
655                 if(n_rfilters < (int) sizeof(rfilters) / (int) sizeof(rfilters[0])) {
656                     rfilters[n_rfilters++] = optarg;
657                 }
658                 else {
659                     cmdarg_err("Too many display filters");
660                     exit(1);
661                 }
662                 break;
663             case 's':        /* Skip PCAP header */
664                 skip_pcap_header = TRUE;
665                 break;
666             case 'S':        /* Print string representations */
667                 if (!parse_field_string_format(optarg)) {
668                     cmdarg_err("Invalid field string format");
669                     exit(1);
670                 }
671                 break;
672             case 't':        /* Time stamp type */
673                 if (strcmp(optarg, "r") == 0)
674                     timestamp_set_type(TS_RELATIVE);
675                 else if (strcmp(optarg, "a") == 0)
676                     timestamp_set_type(TS_ABSOLUTE);
677                 else if (strcmp(optarg, "ad") == 0)
678                     timestamp_set_type(TS_ABSOLUTE_WITH_DATE);
679                 else if (strcmp(optarg, "d") == 0)
680                     timestamp_set_type(TS_DELTA);
681                 else if (strcmp(optarg, "dd") == 0)
682                     timestamp_set_type(TS_DELTA_DIS);
683                 else if (strcmp(optarg, "e") == 0)
684                     timestamp_set_type(TS_EPOCH);
685                 else if (strcmp(optarg, "u") == 0)
686                     timestamp_set_type(TS_UTC);
687                 else if (strcmp(optarg, "ud") == 0)
688                     timestamp_set_type(TS_UTC_WITH_DATE);
689                 else {
690                     cmdarg_err("Invalid time stamp type \"%s\"",
691                                optarg);
692                     cmdarg_err_cont("It must be \"r\" for relative, \"a\" for absolute,");
693                     cmdarg_err_cont("\"ad\" for absolute with date, or \"d\" for delta.");
694                     exit(1);
695                 }
696                 break;
697             case 'v':        /* Show version and exit */
698             {
699                 GString             *comp_info_str;
700                 GString             *runtime_info_str;
701                 /* Assemble the compile-time version information string */
702                 comp_info_str = g_string_new("Compiled ");
703                 get_compiled_version_info(comp_info_str, NULL, epan_get_compiled_version_info);
704
705                 /* Assemble the run-time version information string */
706                 runtime_info_str = g_string_new("Running ");
707                 get_runtime_version_info(runtime_info_str, NULL);
708                 show_version(comp_info_str, runtime_info_str);
709                 g_string_free(comp_info_str, TRUE);
710                 g_string_free(runtime_info_str, TRUE);
711                 exit(0);
712                 break;
713             }
714             default:
715             case '?':        /* Bad flag - print usage message */
716                 print_usage(TRUE);
717             exit(1);
718             break;
719         }
720     }
721
722     /* Notify all registered modules that have had any of their preferences
723        changed either from one of the preferences file or from the command
724        line that their preferences have changed.
725        Initialize preferences before display filters, otherwise modules
726        like MATE won't work. */
727     prefs_apply_all();
728
729     /* Initialize our display fields */
730     for (fc = 0; fc < disp_fields->len; fc++) {
731         protocolinfo_init((char *)g_ptr_array_index(disp_fields, fc));
732     }
733     g_ptr_array_free(disp_fields, TRUE);
734     printf("\n");
735     fflush(stdout);
736
737     /* If no capture filter or read filter has been specified, and there are
738        still command-line arguments, treat them as the tokens of a capture
739        filter (if no "-r" flag was specified) or a read filter (if a "-r"
740        flag was specified. */
741     if (optind < argc) {
742         if (pipe_name != NULL) {
743             if (n_rfilters != 0) {
744                 cmdarg_err("Read filters were specified both with \"-R\" "
745                            "and with additional command-line arguments");
746                 exit(1);
747             }
748             rfilters[n_rfilters] = get_args_as_string(argc, argv, optind);
749         }
750     }
751
752     /* Make sure we got a dissector handle for our payload. */
753     if (encap == WTAP_ENCAP_UNKNOWN) {
754         cmdarg_err("No valid payload dissector specified.");
755         exit(1);
756     }
757
758     if (arg_error) {
759         print_usage(FALSE);
760         exit(1);
761     }
762
763
764 #ifdef _WIN32
765     /* Start windows sockets */
766     WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
767 #endif /* _WIN32 */
768
769     /* At this point MATE will have registered its field array so we can
770        have a tap filter with one of MATE's late-registered fields as part
771        of the filter.  We can now process all the "-z" arguments. */
772     start_requested_stats();
773
774     /* disabled protocols as per configuration file */
775     if (gdp_path == NULL && dp_path == NULL) {
776         set_disabled_protos_list();
777     }
778
779     /* Build the column format array */
780     build_column_format_array(&cfile.cinfo, prefs_p->num_cols, TRUE);
781
782     if (n_rfilters != 0) {
783         for (i = 0; i < n_rfilters; i++) {
784             if (!dfilter_compile(rfilters[i], &rfcodes[n_rfcodes])) {
785                 cmdarg_err("%s", dfilter_error_msg);
786                 epan_cleanup();
787                 exit(2);
788             }
789             n_rfcodes++;
790         }
791     }
792
793     if (pipe_name) {
794         /*
795          * We're reading a pipe (or capture file).
796          */
797
798         /*
799          * Immediately relinquish any special privileges we have; we must not
800          * be allowed to read any capture files the user running Rawshark
801          * can't open.
802          */
803         relinquish_special_privs_perm();
804
805         if (raw_cf_open(&cfile, pipe_name) != CF_OK) {
806             epan_cleanup();
807             exit(2);
808         }
809
810         /* Do we need to PCAP header and magic? */
811         if (skip_pcap_header) {
812             guint bytes_left = sizeof(struct pcap_hdr) + sizeof(guint32);
813             gchar buf[sizeof(struct pcap_hdr) + sizeof(guint32)];
814             while (bytes_left > 0) {
815                 guint bytes = read(fd, buf, bytes_left);
816                 if (bytes <= 0) {
817                     cmdarg_err("Not enough bytes for pcap header.");
818                     exit(2);
819                 }
820                 bytes_left -= bytes;
821             }
822         }
823
824         /* Set timestamp precision; there should arguably be a command-line
825            option to let the user set this. */
826 #if 0
827         switch(wtap_file_tsprecision(cfile.wth)) {
828             case(WTAP_FILE_TSPREC_SEC):
829                 timestamp_set_precision(TS_PREC_AUTO_SEC);
830                 break;
831             case(WTAP_FILE_TSPREC_DSEC):
832                 timestamp_set_precision(TS_PREC_AUTO_DSEC);
833                 break;
834             case(WTAP_FILE_TSPREC_CSEC):
835                 timestamp_set_precision(TS_PREC_AUTO_CSEC);
836                 break;
837             case(WTAP_FILE_TSPREC_MSEC):
838                 timestamp_set_precision(TS_PREC_AUTO_MSEC);
839                 break;
840             case(WTAP_FILE_TSPREC_USEC):
841                 timestamp_set_precision(TS_PREC_AUTO_USEC);
842                 break;
843             case(WTAP_FILE_TSPREC_NSEC):
844                 timestamp_set_precision(TS_PREC_AUTO_NSEC);
845                 break;
846             default:
847                 g_assert_not_reached();
848         }
849 #else
850         timestamp_set_precision(TS_PREC_AUTO_USEC);
851 #endif
852
853         /* Process the packets in the file */
854         err = load_cap_file(&cfile);
855
856         if (err != 0) {
857             epan_cleanup();
858             exit(2);
859         }
860     } else {
861         /* If you want to capture live packets, use TShark. */
862         cmdarg_err("Input file or pipe name not specified.");
863         exit(2);
864     }
865
866     epan_cleanup();
867
868     return 0;
869 }
870
871 /**
872  * Read data from a raw pipe.  The "raw" data consists of a libpcap
873  * packet header followed by the payload.
874  * @param fd [IN] A POSIX file descriptor.  Because that's _exactly_ the sort
875  *           of thing you want to use in Windows.
876  * @param phdr [OUT] Packet header information.
877  * @param err [OUT] Error indicator.  Uses wiretap values.
878  * @param err_info [OUT] Error message.
879  * @param data_offset [OUT] data offset in the pipe.
880  * @return TRUE on success, FALSE on failure.
881  */
882 static gboolean
883 raw_pipe_read(struct wtap_pkthdr *phdr, guchar * pd, int *err, const gchar **err_info, gint64 *data_offset) {
884     struct pcap_pkthdr mem_hdr;
885     struct pcaprec_hdr disk_hdr;
886     int bytes_read = 0;
887     int bytes_needed = sizeof(disk_hdr);
888     guchar *ptr = (guchar*) &disk_hdr;
889     static gchar err_str[100];
890
891     if (want_pcap_pkthdr) {
892         bytes_needed = sizeof(mem_hdr);
893         ptr = (guchar*) &mem_hdr;
894     }
895
896     /* Copied from capture_loop.c */
897     while (bytes_needed > 0) {
898         bytes_read = read(fd, ptr, bytes_needed);
899         if (bytes_read == 0) {
900             *err = 0;
901             return FALSE;
902         } else if (bytes_read < 0) {
903             *err = WTAP_ERR_CANT_READ;
904             *err_info = "Error reading header from pipe";
905             return FALSE;
906         }
907         bytes_needed -= bytes_read;
908         *data_offset += bytes_read;
909         ptr += bytes_read;
910     }
911
912     if (want_pcap_pkthdr) {
913         phdr->ts.secs = mem_hdr.ts.tv_sec;
914         phdr->ts.nsecs = mem_hdr.ts.tv_usec * 1000;
915         phdr->caplen = bytes_needed = mem_hdr.caplen;
916         phdr->len = mem_hdr.len;
917     } else {
918         phdr->ts.secs = disk_hdr.ts_sec;
919         phdr->ts.nsecs = disk_hdr.ts_usec * 1000;
920         phdr->caplen = bytes_needed = disk_hdr.incl_len;
921         phdr->len = disk_hdr.orig_len;
922     }
923
924     phdr->pkt_encap = encap;
925
926 #if 0
927     printf("tv_sec: %d (%04x)\n", hdr.ts.tv_sec, hdr.ts.tv_sec);
928     printf("tv_usec: %d (%04x)\n", hdr.ts.tv_usec, hdr.ts.tv_usec);
929     printf("caplen: %d (%04x)\n", hdr.caplen, hdr.caplen);
930     printf("len: %d (%04x)\n", hdr.len, hdr.len);
931 #endif
932     if (bytes_needed > WTAP_MAX_PACKET_SIZE) {
933         *err = WTAP_ERR_BAD_FILE;
934         g_snprintf(err_str, 100, "Bad packet length: %d (%04x)", bytes_needed, bytes_needed);
935         *err_info = err_str;
936         return FALSE;
937     }
938
939     ptr = pd;
940     while (bytes_needed > 0) {
941         bytes_read = read(fd, ptr, bytes_needed);
942         if (bytes_read == 0) {
943             *err = WTAP_ERR_SHORT_READ;
944             *err_info = "Got zero bytes reading data from pipe";
945             return FALSE;
946         } else if (bytes_read < 0) {
947             *err = WTAP_ERR_CANT_READ;
948             *err_info = "Error reading data from pipe";
949             return FALSE;
950         }
951         bytes_needed -= bytes_read;
952         *data_offset += bytes_read;
953         ptr += bytes_read;
954     }
955     return TRUE;
956 }
957
958 static int
959 load_cap_file(capture_file *cf)
960 {
961     int          err;
962     const gchar  *err_info;
963     gint64       data_offset = 0;
964     struct wtap_pkthdr  phdr;
965     guchar       pd[WTAP_MAX_PACKET_SIZE];
966
967     while (raw_pipe_read(&phdr, pd, &err, &err_info, &data_offset)) {
968         process_packet(cf, data_offset, &phdr, pd);
969     }
970
971     if (err != 0) {
972         /* Print a message noting that the read failed somewhere along the line. */
973         switch (err) {
974
975             case WTAP_ERR_UNSUPPORTED_ENCAP:
976                 cmdarg_err("The file \"%s\" has a packet with a network type that Rawshark doesn't support.\n(%s)",
977                            cf->filename, err_info);
978                 break;
979
980             case WTAP_ERR_CANT_READ:
981                 cmdarg_err("An attempt to read from the file \"%s\" failed for some unknown reason.",
982                            cf->filename);
983                 break;
984
985             case WTAP_ERR_SHORT_READ:
986                 cmdarg_err("The file \"%s\" appears to have been cut short in the middle of a packet.",
987                            cf->filename);
988                 break;
989
990             case WTAP_ERR_BAD_FILE:
991                 cmdarg_err("The file \"%s\" appears to be damaged or corrupt.\n(%s)",
992                            cf->filename, err_info);
993                 break;
994
995             case WTAP_ERR_DECOMPRESS:
996                 cmdarg_err("The compressed file \"%s\" appears to be damaged or corrupt.\n(%s)",
997                            cf->filename, err_info);
998                 break;
999
1000             default:
1001                 cmdarg_err("An error occurred while reading the file \"%s\": %s.",
1002                            cf->filename, wtap_strerror(err));
1003                 break;
1004         }
1005     }
1006
1007     return err;
1008 }
1009
1010 static gboolean
1011 process_packet(capture_file *cf, gint64 offset, const struct wtap_pkthdr *whdr,
1012                const guchar *pd)
1013 {
1014     frame_data fdata;
1015     gboolean create_proto_tree;
1016     epan_dissect_t edt;
1017     gboolean passed;
1018     union wtap_pseudo_header pseudo_header;
1019     int i;
1020
1021     if(whdr->len == 0)
1022     {
1023         /* The user sends an empty packet when he wants to get output from us even if we don't currently have
1024            packets to process. We spit out a line with the timestamp and the text "void"
1025         */
1026         printf("%lu %lu %lu void -\n", (unsigned long int)cf->count,
1027                (unsigned long int)whdr->ts.secs,
1028                (unsigned long int)whdr->ts.nsecs);
1029
1030         fflush(stdout);
1031
1032         return FALSE;
1033     }
1034
1035     memset(&pseudo_header, 0, sizeof(pseudo_header));
1036
1037     /* Count this packet. */
1038     cf->count++;
1039
1040     /* If we're going to print packet information, or we're going to
1041        run a read filter, or we're going to process taps, set up to
1042        do a dissection and do so. */
1043     frame_data_init(&fdata, cf->count, whdr, offset, cum_bytes);
1044
1045     passed = TRUE;
1046     create_proto_tree = TRUE;
1047
1048     /* The protocol tree will be "visible", i.e., printed, only if we're
1049        printing packet details, which is true if we're in verbose mode ("verbose"
1050        is true). */
1051     epan_dissect_init(&edt, create_proto_tree, FALSE);
1052
1053     /* If we're running a read filter, prime the epan_dissect_t with that
1054        filter. */
1055     if (n_rfilters > 0) {
1056         for(i = 0; i < n_rfcodes; i++) {
1057             epan_dissect_prime_dfilter(&edt, rfcodes[i]);
1058         }
1059     }
1060
1061     tap_queue_init(&edt);
1062
1063     printf("%lu", (unsigned long int) cf->count);
1064
1065     frame_data_set_before_dissect(&fdata, &cf->elapsed_time,
1066                                   &first_ts, &prev_dis_ts, &prev_cap_ts);
1067
1068     /* We only need the columns if we're printing packet info but we're
1069      *not* verbose; in verbose mode, we print the protocol tree, not
1070      the protocol summary. */
1071     epan_dissect_run(&edt, &pseudo_header, pd, &fdata, &cf->cinfo);
1072
1073     tap_push_tapped_queue(&edt);
1074
1075     frame_data_set_after_dissect(&fdata, &cum_bytes, &prev_dis_ts);
1076
1077     for(i = 0; i < n_rfilters; i++) {
1078         /* Run the read filter if we have one. */
1079         if (rfcodes[i])
1080             passed = dfilter_apply_edt(rfcodes[i], &edt);
1081         else
1082             passed = TRUE;
1083
1084         /* Print a one-line summary */
1085         printf(" %u", passed ? 1 : 0);
1086     }
1087
1088     printf(" -\n");
1089
1090     /* The ANSI C standard does not appear to *require* that a line-buffered
1091        stream be flushed to the host environment whenever a newline is
1092        written, it just says that, on such a stream, characters "are
1093        intended to be transmitted to or from the host environment as a
1094        block when a new-line character is encountered".
1095
1096        The Visual C++ 6.0 C implementation doesn't do what is intended;
1097        even if you set a stream to be line-buffered, it still doesn't
1098        flush the buffer at the end of every line.
1099
1100        So, if the "-l" flag was specified, we flush the standard output
1101        at the end of a packet.  This will do the right thing if we're
1102        printing packet summary lines, and, as we print the entire protocol
1103        tree for a single packet without waiting for anything to happen,
1104        it should be as good as line-buffered mode if we're printing
1105        protocol trees.  (The whole reason for the "-l" flag in either
1106        tcpdump or Rawshark is to allow the output of a live capture to
1107        be piped to a program or script and to have that script see the
1108        information for the packet as soon as it's printed, rather than
1109        having to wait until a standard I/O buffer fills up. */
1110     if (line_buffered)
1111         fflush(stdout);
1112
1113     if (ferror(stdout)) {
1114         show_print_file_io_error(errno);
1115         exit(2);
1116     }
1117
1118     epan_dissect_cleanup(&edt);
1119     frame_data_cleanup(&fdata);
1120
1121     return passed;
1122 }
1123
1124 /****************************************************************************************
1125  * FIELD EXTRACTION ROUTINES
1126  ****************************************************************************************/
1127 typedef struct _pci_t {
1128     char *filter;
1129     int hf_index;
1130     int cmd_line_index;
1131 } pci_t;
1132
1133 static const char* ftenum_to_string(header_field_info *hfi)
1134 {
1135     if (!hfi) {
1136         return "n.a.";
1137     }
1138
1139     if (string_fmts->len > 0 && hfi->strings) {
1140         return "FT_STRING";
1141     }
1142
1143     switch(hfi->type) {
1144         case FT_NONE:
1145             return "FT_NONE";
1146         case FT_PROTOCOL:
1147             return "FT_PROTOCOL";
1148         case FT_BOOLEAN:
1149             return "FT_BOOLEAN";
1150         case FT_UINT8:
1151             return "FT_UINT8";
1152         case FT_UINT16:
1153             return "FT_UINT16";
1154         case FT_UINT24:
1155             return "FT_UINT24";
1156         case FT_UINT32:
1157             return "FT_UINT32";
1158         case FT_UINT64:
1159             return "FT_UINT64";
1160         case FT_INT8:
1161             return "FT_INT8";
1162         case FT_INT16:
1163             return "FT_INT16";
1164         case FT_INT24:
1165             return "FT_INT24";
1166         case FT_INT32:
1167             return "FT_INT32";
1168         case FT_INT64:
1169             return "FT_INT64";
1170         case FT_FLOAT:
1171             return "FT_FLOAT";
1172         case FT_DOUBLE:
1173             return "FT_DOUBLE";
1174         case FT_ABSOLUTE_TIME:
1175             return "FT_ABSOLUTE_TIME";
1176         case FT_RELATIVE_TIME:
1177             return "FT_RELATIVE_TIME";
1178         case FT_STRING:
1179             return "FT_STRING";
1180         case FT_STRINGZ:
1181             return "FT_STRINGZ";
1182         case FT_UINT_STRING:
1183             return "FT_UINT_STRING";
1184         case FT_ETHER:
1185             return "FT_ETHER";
1186         case FT_BYTES:
1187             return "FT_BYTES";
1188         case FT_UINT_BYTES:
1189             return "FT_UINT_BYTES";
1190         case FT_IPv4:
1191             return "FT_IPv4";
1192         case FT_IPv6:
1193             return "FT_IPv6";
1194         case FT_IPXNET:
1195             return "FT_IPXNET";
1196         case FT_FRAMENUM:
1197             return "FT_FRAMENUM";
1198         case FT_PCRE:
1199             return "FT_PCRE";
1200         case FT_GUID:
1201             return "FT_GUID";
1202         case FT_OID:
1203             return "FT_OID";
1204         case FT_NUM_TYPES:
1205             return "FT_NUM_TYPES";
1206         default:
1207             return "n.a.";
1208     };
1209 }
1210
1211 static const char* absolute_time_display_e_to_string(absolute_time_display_e atd)
1212 {
1213     switch(atd) {
1214         case ABSOLUTE_TIME_LOCAL:
1215             return "ABSOLUTE_TIME_LOCAL";
1216         case ABSOLUTE_TIME_UTC:
1217             return "ABSOLUTE_TIME_UTC";
1218         default:
1219             return "n.a.";
1220     }
1221 }
1222
1223 static const char* base_display_e_to_string(base_display_e bd)
1224 {
1225     switch(bd) {
1226         case BASE_NONE:
1227             return "BASE_NONE";
1228         case BASE_DEC:
1229             return "BASE_DEC";
1230         case BASE_HEX:
1231             return "BASE_HEX";
1232         case BASE_OCT:
1233             return "BASE_OCT";
1234         case BASE_DEC_HEX:
1235             return "BASE_DEC_HEX";
1236         case BASE_HEX_DEC:
1237             return "BASE_HEX_DEC";
1238         default:
1239             return "n.a.";
1240     }
1241 }
1242
1243 /*
1244  * Copied from various parts of proto.c
1245  */
1246 #define FIELD_STR_INIT_LEN 256
1247 #define cVALS(x) (const value_string*)(x)
1248 static gboolean print_field_value(field_info *finfo, int cmd_line_index)
1249 {
1250     header_field_info   *hfinfo;
1251     static char         *fs_buf = NULL;
1252     char                *fs_ptr = fs_buf;
1253     static GString     *label_s = NULL;
1254     int                 fs_buf_len = FIELD_STR_INIT_LEN, fs_len;
1255     guint              i;
1256     string_fmt_t       *sf;
1257     guint32            uvalue;
1258     gint32             svalue;
1259     const true_false_string *tfstring = &tfs_true_false;
1260
1261     hfinfo = finfo->hfinfo;
1262
1263     if (!fs_buf) {
1264         fs_buf = (char *)g_malloc(fs_buf_len + 1);
1265         fs_ptr = fs_buf;
1266     }
1267
1268     if (!label_s) {
1269         label_s = g_string_new("");
1270     }
1271
1272     if(finfo->value.ftype->val_to_string_repr)
1273     {
1274         /*
1275          * this field has an associated value,
1276          * e.g: ip.hdr_len
1277          */
1278         fs_len = fvalue_string_repr_len(&finfo->value, FTREPR_DFILTER);
1279         while (fs_buf_len < fs_len) {
1280             fs_buf_len *= 2;
1281             fs_buf = (char *)g_realloc(fs_buf, fs_buf_len + 1);
1282             fs_ptr = fs_buf;
1283         }
1284         fvalue_to_string_repr(&finfo->value,
1285                               FTREPR_DFILTER,
1286                               fs_buf);
1287
1288         /* String types are quoted. Remove them. */
1289         if ((finfo->value.ftype->ftype == FT_STRING || finfo->value.ftype->ftype == FT_STRINGZ) && fs_len > 2) {
1290             fs_buf[fs_len - 1] = '\0';
1291             fs_ptr++;
1292         }
1293     }
1294
1295     if (string_fmts->len > 0 && finfo->hfinfo->strings) {
1296         g_string_truncate(label_s, 0);
1297         for (i = 0; i < string_fmts->len; i++) {
1298             sf = (string_fmt_t *)g_ptr_array_index(string_fmts, i);
1299             if (sf->plain) {
1300                 g_string_append(label_s, sf->plain);
1301             } else {
1302                 switch (sf->format) {
1303                     case SF_NAME:
1304                         g_string_append(label_s, hfinfo->name);
1305                         break;
1306                     case SF_NUMVAL:
1307                         g_string_append(label_s, fs_ptr);
1308                         break;
1309                     case SF_STRVAL:
1310                         switch(hfinfo->type) {
1311                             case FT_BOOLEAN:
1312                                 uvalue = fvalue_get_uinteger(&finfo->value);
1313                                 tfstring = (const struct true_false_string*) hfinfo->strings;
1314                                 g_string_append(label_s, uvalue ? tfstring->true_string : tfstring->false_string);
1315                                 break;
1316                             case FT_INT8:
1317                             case FT_INT16:
1318                             case FT_INT24:
1319                             case FT_INT32:
1320                                 DISSECTOR_ASSERT(!hfinfo->bitmask);
1321                                 svalue = fvalue_get_sinteger(&finfo->value);
1322                                 if (hfinfo->display & BASE_RANGE_STRING) {
1323                                     g_string_append(label_s, rval_to_str(svalue, RVALS(hfinfo->strings), "Unknown"));
1324                                 } else if (hfinfo->display & BASE_EXT_STRING) {
1325                                     g_string_append(label_s, val_to_str_ext(svalue, (const value_string_ext *) hfinfo->strings, "Unknown"));
1326                                 } else {
1327                                     g_string_append(label_s, val_to_str(svalue, cVALS(hfinfo->strings), "Unknown"));
1328                                 }
1329                                 break;
1330                             case FT_UINT8:
1331                             case FT_UINT16:
1332                             case FT_UINT24:
1333                             case FT_UINT32:
1334                                 uvalue = fvalue_get_uinteger(&finfo->value);
1335                                 if (!hfinfo->bitmask && hfinfo->display & BASE_RANGE_STRING) {
1336                                     g_string_append(label_s, rval_to_str(uvalue, RVALS(hfinfo->strings), "Unknown"));
1337                                 } else if (hfinfo->display & BASE_EXT_STRING) {
1338                                     g_string_append(label_s, val_to_str_ext(uvalue, (const value_string_ext *) hfinfo->strings, "Unknown"));
1339                                 } else {
1340                                     g_string_append(label_s, val_to_str(uvalue, cVALS(hfinfo->strings), "Unknown"));
1341                                 }
1342                                 break;
1343                             default:
1344                                 break;
1345                         }
1346                         break;
1347                     default:
1348                         break;
1349                 }
1350             }
1351         }
1352         printf(" %u=\"%s\"", cmd_line_index, label_s->str);
1353         return TRUE;
1354     }
1355
1356     if(finfo->value.ftype->val_to_string_repr)
1357     {
1358         printf(" %u=\"%s\"", cmd_line_index, fs_ptr);
1359         return TRUE;
1360     }
1361
1362     /*
1363      * This field doesn't have an associated value,
1364      * e.g. http
1365      * We return n.a.
1366      */
1367     printf(" %u=\"n.a.\"", cmd_line_index);
1368     return TRUE;
1369 }
1370
1371 static int
1372 protocolinfo_packet(void *prs, packet_info *pinfo _U_, epan_dissect_t *edt, const void *dummy _U_)
1373 {
1374     pci_t *rs=(pci_t *)prs;
1375     GPtrArray *gp;
1376     guint i;
1377
1378     gp=proto_get_finfo_ptr_array(edt->tree, rs->hf_index);
1379     if(!gp){
1380         printf(" n.a.");
1381         return 0;
1382     }
1383
1384     /*
1385      * Print each occurrence of the field
1386      */
1387     for (i = 0; i < gp->len; i++) {
1388         print_field_value((field_info *)gp->pdata[i], rs->cmd_line_index);
1389     }
1390
1391     return 0;
1392 }
1393
1394 int g_cmd_line_index = 0;
1395
1396 /*
1397  * field must be persistent - we don't g_strdup() it below
1398  */
1399 static void
1400 protocolinfo_init(char *field)
1401 {
1402     pci_t *rs;
1403     header_field_info *hfi;
1404     GString *error_string;
1405
1406     hfi=proto_registrar_get_byname(field);
1407     if(!hfi){
1408         fprintf(stderr, "rawshark: Field \"%s\" doesn't exist.\n", field);
1409         exit(1);
1410     }
1411
1412     switch (hfi->type) {
1413
1414         case FT_ABSOLUTE_TIME:
1415             printf("%u %s %s - ",
1416                    g_cmd_line_index,
1417                    ftenum_to_string(hfi),
1418                    absolute_time_display_e_to_string(hfi->display));
1419             break;
1420
1421         default:
1422             printf("%u %s %s - ",
1423                    g_cmd_line_index,
1424                    ftenum_to_string(hfi),
1425                    base_display_e_to_string(hfi->display));
1426             break;
1427     }
1428
1429     rs=(pci_t *)g_malloc(sizeof(pci_t));
1430     rs->hf_index=hfi->id;
1431     rs->filter=field;
1432     rs->cmd_line_index = g_cmd_line_index++;
1433
1434     error_string=register_tap_listener("frame", rs, rs->filter, TL_REQUIRES_PROTO_TREE, NULL, protocolinfo_packet, NULL);
1435     if(error_string){
1436         /* error, we failed to attach to the tap. complain and clean up */
1437         fprintf(stderr, "rawshark: Couldn't register field extraction tap: %s\n",
1438                 error_string->str);
1439         g_string_free(error_string, TRUE);
1440         if(rs->filter){
1441             g_free(rs->filter);
1442         }
1443         g_free(rs);
1444
1445         exit(1);
1446     }
1447 }
1448
1449 /*
1450  * Given a format string, split it into a GPtrArray of string_fmt_t structs
1451  * and fill in string_fmt_parts.
1452  */
1453
1454 static void
1455 add_string_fmt(string_fmt_e format, gchar *plain) {
1456     string_fmt_t *sf = (string_fmt_t *)g_malloc(sizeof(string_fmt_t));
1457
1458     sf->format = format;
1459     sf->plain = g_strdup(plain);
1460
1461     g_ptr_array_add(string_fmts, sf);
1462 }
1463
1464 static gboolean
1465 parse_field_string_format(gchar *format) {
1466     GString *plain_s = g_string_new("");
1467     size_t len;
1468     size_t pos = 0;
1469
1470     if (!format) {
1471         return FALSE;
1472     }
1473
1474     len = strlen(format);
1475     g_ptr_array_set_size(string_fmts, 0);
1476
1477     while (pos < len) {
1478         if (format[pos] == '%') {
1479             if (pos >= len) { /* There should always be a following character */
1480                 return FALSE;
1481             }
1482             pos++;
1483             if (plain_s->len > 0) {
1484                 add_string_fmt(SF_NONE, plain_s->str);
1485                 g_string_truncate(plain_s, 0);
1486             }
1487             switch (format[pos]) {
1488                 case 'D':
1489                     add_string_fmt(SF_NAME, NULL);
1490                     break;
1491                 case 'N':
1492                     add_string_fmt(SF_NUMVAL, NULL);
1493                     break;
1494                 case 'S':
1495                     add_string_fmt(SF_STRVAL, NULL);
1496                     break;
1497                 case '%':
1498                     g_string_append_c(plain_s, '%');
1499                     break;
1500                 default: /* Invalid format */
1501                     return FALSE;
1502             }
1503         } else {
1504             g_string_append_c(plain_s, format[pos]);
1505         }
1506         pos++;
1507     }
1508
1509     if (plain_s->len > 0) {
1510         add_string_fmt(SF_NONE, plain_s->str);
1511     }
1512     g_string_free(plain_s, TRUE);
1513
1514     return TRUE;
1515 }
1516 /****************************************************************************************
1517  * END OF FIELD EXTRACTION ROUTINES
1518  ****************************************************************************************/
1519
1520 static void
1521 show_print_file_io_error(int err)
1522 {
1523     switch (err) {
1524
1525         case ENOSPC:
1526             cmdarg_err("Not all the packets could be printed because there is "
1527                        "no space left on the file system.");
1528             break;
1529
1530 #ifdef EDQUOT
1531         case EDQUOT:
1532             cmdarg_err("Not all the packets could be printed because you are "
1533                        "too close to, or over your disk quota.");
1534             break;
1535 #endif
1536
1537         default:
1538             cmdarg_err("An error occurred while printing packets: %s.",
1539                        g_strerror(err));
1540             break;
1541     }
1542 }
1543
1544 /*
1545  * Open/create errors are reported with an console message in Rawshark.
1546  */
1547 static void
1548 open_failure_message(const char *filename, int err, gboolean for_writing)
1549 {
1550     fprintf(stderr, "rawshark: ");
1551     fprintf(stderr, file_open_error_message(err, for_writing), filename);
1552     fprintf(stderr, "\n");
1553 }
1554
1555 cf_status_t
1556 raw_cf_open(capture_file *cf, const char *fname)
1557 {
1558     if ((fd = raw_pipe_open(fname)) < 0)
1559         return CF_ERROR;
1560
1561     /* The open succeeded.  Fill in the information for this file. */
1562
1563     /* Cleanup all data structures used for dissection. */
1564     cleanup_dissection();
1565     /* Initialize all data structures used for dissection. */
1566     init_dissection();
1567
1568     cf->wth = NULL;
1569     cf->f_datalen = 0; /* not used, but set it anyway */
1570
1571     /* Set the file name because we need it to set the follow stream filter.
1572        XXX - is that still true?  We need it for other reasons, though,
1573        in any case. */
1574     cf->filename = g_strdup(fname);
1575
1576     /* Indicate whether it's a permanent or temporary file. */
1577     cf->is_tempfile = FALSE;
1578
1579     /* No user changes yet. */
1580     cf->unsaved_changes = FALSE;
1581
1582     cf->cd_t      = WTAP_FILE_UNKNOWN;
1583     cf->count     = 0;
1584     cf->drops_known = FALSE;
1585     cf->drops     = 0;
1586     cf->has_snap = FALSE;
1587     cf->snap = WTAP_MAX_PACKET_SIZE;
1588     nstime_set_zero(&cf->elapsed_time);
1589     nstime_set_unset(&first_ts);
1590     nstime_set_unset(&prev_dis_ts);
1591     nstime_set_unset(&prev_cap_ts);
1592
1593     return CF_OK;
1594 }
1595
1596
1597 /*
1598  * General errors are reported with an console message in Rawshark.
1599  */
1600 static void
1601 failure_message(const char *msg_format, va_list ap)
1602 {
1603     fprintf(stderr, "rawshark: ");
1604     vfprintf(stderr, msg_format, ap);
1605     fprintf(stderr, "\n");
1606 }
1607
1608 /*
1609  * Read errors are reported with an console message in Rawshark.
1610  */
1611 static void
1612 read_failure_message(const char *filename, int err)
1613 {
1614     cmdarg_err("An error occurred while reading from the file \"%s\": %s.",
1615                filename, g_strerror(err));
1616 }
1617
1618 /*
1619  * Write errors are reported with an console message in Rawshark.
1620  */
1621 static void
1622 write_failure_message(const char *filename, int err)
1623 {
1624     cmdarg_err("An error occurred while writing to the file \"%s\": %s.",
1625                filename, g_strerror(err));
1626 }
1627
1628 /*
1629  * Report an error in command-line arguments.
1630  */
1631 void
1632 cmdarg_err(const char *fmt, ...)
1633 {
1634     va_list ap;
1635
1636     va_start(ap, fmt);
1637     fprintf(stderr, "rawshark: ");
1638     vfprintf(stderr, fmt, ap);
1639     fprintf(stderr, "\n");
1640     va_end(ap);
1641 }
1642
1643 /*
1644  * Report additional information for an error in command-line arguments.
1645  */
1646 void
1647 cmdarg_err_cont(const char *fmt, ...)
1648 {
1649     va_list ap;
1650
1651     va_start(ap, fmt);
1652     vfprintf(stderr, fmt, ap);
1653     fprintf(stderr, "\n");
1654     va_end(ap);
1655 }
1656
1657
1658 /*
1659  * Editor modelines
1660  *
1661  * Local Variables:
1662  * c-basic-offset: 4
1663  * tab-width: 8
1664  * indent-tabs-mode: nil
1665  * End:
1666  *
1667  * ex: set shiftwidth=4 tabstop=8 expandtab:
1668  * :indentSize=4:tabSize=8:noTabs=true:
1669  */