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