If we have no fields, don't try to iterate through them.
[metze/wireshark/wip.git] / epan / print.c
1 /* print.c
2  * Routines for printing packet analysis trees.
3  *
4  * Gilbert Ramirez <gram@alumni.rice.edu>
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23  */
24
25 #include "config.h"
26
27 #include <stdio.h>
28 #include <string.h>
29
30 #include <glib.h>
31 #include <glib/gprintf.h>
32
33 #include <epan/epan.h>
34 #include <epan/epan_dissect.h>
35 #include <epan/to_str.h>
36 #include <epan/tvbuff.h>
37 #include <epan/packet.h>
38 #include <ftypes/ftypes-int.h>
39 #include <epan/emem.h>
40 #include <epan/expert.h>
41
42 #include <epan/packet-range.h>
43 #include "print.h"
44 #include "ps.h"
45 #include "version_info.h"
46 #include <wsutil/file_util.h>
47 #include <epan/charsets.h>
48 #include <epan/dissectors/packet-data.h>
49 #include <epan/dissectors/packet-frame.h>
50 #include <wsutil/filesystem.h>
51
52 #define PDML_VERSION "0"
53 #define PSML_VERSION "0"
54
55 typedef struct {
56     int                  level;
57     print_stream_t      *stream;
58     gboolean             success;
59     GSList              *src_list;
60     print_dissections_e  print_dissections;
61     gboolean             print_hex_for_data;
62     packet_char_enc      encoding;
63     epan_dissect_t      *edt;
64 } print_data;
65
66 typedef struct {
67     int             level;
68     FILE           *fh;
69     GSList         *src_list;
70     epan_dissect_t *edt;
71 } write_pdml_data;
72
73 typedef struct {
74     output_fields_t *fields;
75     epan_dissect_t  *edt;
76 } write_field_data_t;
77
78 struct _output_fields {
79     gboolean     print_header;
80     gchar        separator;
81     gchar        occurrence;
82     gchar        aggregator;
83     GPtrArray   *fields;
84     GHashTable  *field_indicies;
85     GPtrArray  **field_values;
86     gchar        quote;
87     gboolean     includes_col_fields;
88 };
89
90 GHashTable *output_only_tables = NULL;
91
92 static gboolean write_headers = FALSE;
93
94 static gchar *get_field_hex_value(GSList *src_list, field_info *fi);
95 static void proto_tree_print_node(proto_node *node, gpointer data);
96 static void proto_tree_write_node_pdml(proto_node *node, gpointer data);
97 static const guint8 *get_field_data(GSList *src_list, field_info *fi);
98 static void write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi);
99 static gboolean print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
100                                       guint length, packet_char_enc encoding);
101 static void ps_clean_string(char *out, const char *in,
102                             int outbuf_size);
103 static void print_escaped_xml(FILE *fh, const char *unescaped_string);
104
105 static void print_pdml_geninfo(proto_tree *tree, FILE *fh);
106
107 static void proto_tree_get_node_field_values(proto_node *node, gpointer data);
108
109 static FILE *
110 open_print_dest(gboolean to_file, const char *dest)
111 {
112     FILE *fh;
113
114     /* Open the file or command for output */
115     if (to_file)
116         fh = ws_fopen(dest, "w");
117     else
118         fh = popen(dest, "w");
119
120     return fh;
121 }
122
123 static gboolean
124 close_print_dest(gboolean to_file, FILE *fh)
125 {
126     /* Close the file or command */
127     if (to_file)
128         return (fclose(fh) == 0);
129     else
130         return (pclose(fh) == 0);
131 }
132
133 #define MAX_PS_LINE_LENGTH 256
134
135 gboolean
136 proto_tree_print(print_args_t *print_args, epan_dissect_t *edt,
137                  print_stream_t *stream)
138 {
139     print_data data;
140
141     /* Create the output */
142     data.level              = 0;
143     data.stream             = stream;
144     data.success            = TRUE;
145     data.src_list           = edt->pi.data_src;
146     data.encoding           = (packet_char_enc)edt->pi.fd->flags.encoding;
147     data.print_dissections  = print_args->print_dissections;
148     /* If we're printing the entire packet in hex, don't
149        print uninterpreted data fields in hex as well. */
150     data.print_hex_for_data = !print_args->print_hex;
151     data.edt                = edt;
152
153     proto_tree_children_foreach(edt->tree, proto_tree_print_node, &data);
154     return data.success;
155 }
156
157 #define MAX_INDENT    160
158
159 /* Print a tree's data, and any child nodes. */
160 static void
161 proto_tree_print_node(proto_node *node, gpointer data)
162 {
163     field_info   *fi    = PNODE_FINFO(node);
164     print_data   *pdata = (print_data*) data;
165     const guint8 *pd;
166     gchar         label_str[ITEM_LABEL_LENGTH];
167     gchar        *label_ptr;
168
169     /* dissection with an invisible proto tree? */
170     g_assert(fi);
171
172     /* Don't print invisible entries. */
173     if (PROTO_ITEM_IS_HIDDEN(node))
174         return;
175
176     /* Give up if we've already gotten an error. */
177     if (!pdata->success)
178         return;
179
180     /* was a free format label produced? */
181     if (fi->rep) {
182         label_ptr = fi->rep->representation;
183     }
184     else { /* no, make a generic label */
185         label_ptr = label_str;
186         proto_item_fill_label(fi, label_str);
187     }
188
189     if (PROTO_ITEM_IS_GENERATED(node))
190         label_ptr = g_strconcat("[", label_ptr, "]", NULL);
191
192     pdata->success = print_line(pdata->stream, pdata->level, label_ptr);
193
194     if (PROTO_ITEM_IS_GENERATED(node))
195         g_free(label_ptr);
196
197     if (!pdata->success)
198         return;
199
200     /*
201      * If -O is specified, only display the protocols which are in the
202      * lookup table.  Only check on the first level: once we start printing
203      * a tree, print the rest of the subtree.  Otherwise we won't print
204      * subitems whose abbreviation doesn't match the protocol--for example
205      * text items (whose abbreviation is simply "text").
206      */
207     if ((output_only_tables != NULL) && (pdata->level == 0)
208         && (g_hash_table_lookup(output_only_tables, fi->hfinfo->abbrev) == NULL)) {
209         return;
210     }
211
212     /* If it's uninterpreted data, dump it (unless our caller will
213        be printing the entire packet in hex). */
214     if ((fi->hfinfo->id == proto_data) && (pdata->print_hex_for_data)) {
215         /*
216          * Find the data for this field.
217          */
218         pd = get_field_data(pdata->src_list, fi);
219         if (pd) {
220             if (!print_line(pdata->stream, 0, "")) {
221                 pdata->success = FALSE;
222                 return;
223             }
224             if (!print_hex_data_buffer(pdata->stream, pd,
225                                        fi->length, pdata->encoding)) {
226                 pdata->success = FALSE;
227                 return;
228             }
229         }
230     }
231
232     /* If we're printing all levels, or if this node is one with a
233        subtree and its subtree is expanded, recurse into the subtree,
234        if it exists. */
235     g_assert((fi->tree_type >= -1) && (fi->tree_type < num_tree_types));
236     if ((pdata->print_dissections == print_dissections_expanded) ||
237         ((pdata->print_dissections == print_dissections_as_displayed) &&
238          (fi->tree_type >= 0) && tree_expanded(fi->tree_type))) {
239         if (node->first_child != NULL) {
240             pdata->level++;
241             proto_tree_children_foreach(node,
242                                         proto_tree_print_node, pdata);
243             pdata->level--;
244             if (!pdata->success)
245                 return;
246         }
247     }
248 }
249
250 #define PDML2HTML_XSL "pdml2html.xsl"
251 void
252 write_pdml_preamble(FILE *fh, const gchar *filename)
253 {
254     time_t t = time(NULL);
255     char *ts = asctime(localtime(&t));
256
257     ts[strlen(ts)-1] = 0; /* overwrite \n */
258
259     fputs("<?xml version=\"1.0\"?>\n", fh);
260     fputs("<?xml-stylesheet type=\"text/xsl\" href=\"" PDML2HTML_XSL "\"?>\n", fh);
261     fprintf(fh, "<!-- You can find " PDML2HTML_XSL " in %s or at http://anonsvn.wireshark.org/trunk/wireshark/" PDML2HTML_XSL ". -->\n", get_datafile_dir());
262     fputs("<pdml version=\"" PDML_VERSION "\" ", fh);
263     fprintf(fh, "creator=\"%s/%s\" time=\"%s\" capture_file=\"%s\">\n", PACKAGE, VERSION, ts, filename ? filename : "");
264 }
265
266 void
267 proto_tree_write_pdml(epan_dissect_t *edt, FILE *fh)
268 {
269     write_pdml_data data;
270
271     /* Create the output */
272     data.level    = 0;
273     data.fh       = fh;
274     data.src_list = edt->pi.data_src;
275     data.edt      = edt;
276
277     fprintf(fh, "<packet>\n");
278
279     /* Print a "geninfo" protocol as required by PDML */
280     print_pdml_geninfo(edt->tree, fh);
281
282     proto_tree_children_foreach(edt->tree, proto_tree_write_node_pdml,
283                                 &data);
284
285     fprintf(fh, "</packet>\n\n");
286 }
287
288 /* Write out a tree's data, and any child nodes, as PDML */
289 static void
290 proto_tree_write_node_pdml(proto_node *node, gpointer data)
291 {
292     field_info      *fi    = PNODE_FINFO(node);
293     write_pdml_data *pdata = (write_pdml_data*) data;
294     const gchar     *label_ptr;
295     gchar            label_str[ITEM_LABEL_LENGTH];
296     char            *dfilter_string;
297     int              i;
298     gboolean         wrap_in_fake_protocol;
299
300     /* dissection with an invisible proto tree? */
301     g_assert(fi);
302
303     /* Will wrap up top-level field items inside a fake protocol wrapper to
304        preserve the PDML schema */
305     wrap_in_fake_protocol =
306         (((fi->hfinfo->type != FT_PROTOCOL) ||
307           (fi->hfinfo->id == proto_data)) &&
308          (pdata->level == 0));
309
310     /* Indent to the correct level */
311     for (i = -1; i < pdata->level; i++) {
312         fputs("  ", pdata->fh);
313     }
314
315     if (wrap_in_fake_protocol) {
316         /* Open fake protocol wrapper */
317         fputs("<proto name=\"fake-field-wrapper\">\n", pdata->fh);
318
319         /* Indent to increased level before writing out field */
320         pdata->level++;
321         for (i = -1; i < pdata->level; i++) {
322             fputs("  ", pdata->fh);
323         }
324     }
325
326     /* Text label. It's printed as a field with no name. */
327     if (fi->hfinfo->id == hf_text_only) {
328         /* Get the text */
329         if (fi->rep) {
330             label_ptr = fi->rep->representation;
331         }
332         else {
333             label_ptr = "";
334         }
335
336         /* Show empty name since it is a required field */
337         fputs("<field name=\"", pdata->fh);
338         fputs("\" show=\"", pdata->fh);
339         print_escaped_xml(pdata->fh, label_ptr);
340
341         fprintf(pdata->fh, "\" size=\"%d", fi->length);
342         if (node->parent && node->parent->finfo && (fi->start < node->parent->finfo->start)) {
343             fprintf(pdata->fh, "\" pos=\"%d", node->parent->finfo->start + fi->start);
344         } else {
345             fprintf(pdata->fh, "\" pos=\"%d", fi->start);
346         }
347
348         fputs("\" value=\"", pdata->fh);
349         write_pdml_field_hex_value(pdata, fi);
350
351         if (node->first_child != NULL) {
352             fputs("\">\n", pdata->fh);
353         }
354         else {
355             fputs("\"/>\n", pdata->fh);
356         }
357     }
358
359     /* Uninterpreted data, i.e., the "Data" protocol, is
360      * printed as a field instead of a protocol. */
361     else if (fi->hfinfo->id == proto_data) {
362
363         /* Write out field with data */
364         fputs("<field name=\"data\" value=\"", pdata->fh);
365         write_pdml_field_hex_value(pdata, fi);
366         fputs("\">\n", pdata->fh);
367     }
368     /* Normal protocols and fields */
369     else {
370         if ((fi->hfinfo->type == FT_PROTOCOL) && (fi->hfinfo->id != proto_expert)) {
371             fputs("<proto name=\"", pdata->fh);
372         }
373         else {
374             fputs("<field name=\"", pdata->fh);
375         }
376         print_escaped_xml(pdata->fh, fi->hfinfo->abbrev);
377
378 #if 0
379         /* PDML spec, see:
380          * http://www.nbee.org/doku.php?id=netpdl:pdml_specification
381          *
382          * the show fields contains things in 'human readable' format
383          * showname: contains only the name of the field
384          * show: contains only the data of the field
385          * showdtl: contains additional details of the field data
386          * showmap: contains mappings of the field data (e.g. the hostname to an IP address)
387          *
388          * XXX - the showname shouldn't contain the field data itself
389          * (like it's contained in the fi->rep->representation).
390          * Unfortunately, we don't have the field data representation for
391          * all fields, so this isn't currently possible */
392         fputs("\" showname=\"", pdata->fh);
393         print_escaped_xml(pdata->fh, fi->hfinfo->name);
394 #endif
395
396         if (fi->rep) {
397             fputs("\" showname=\"", pdata->fh);
398             print_escaped_xml(pdata->fh, fi->rep->representation);
399         }
400         else {
401             label_ptr = label_str;
402             proto_item_fill_label(fi, label_str);
403             fputs("\" showname=\"", pdata->fh);
404             print_escaped_xml(pdata->fh, label_ptr);
405         }
406
407         if (PROTO_ITEM_IS_HIDDEN(node))
408             fprintf(pdata->fh, "\" hide=\"yes");
409
410         fprintf(pdata->fh, "\" size=\"%d", fi->length);
411         if (node->parent && node->parent->finfo && (fi->start < node->parent->finfo->start)) {
412             fprintf(pdata->fh, "\" pos=\"%d", node->parent->finfo->start + fi->start);
413         } else {
414             fprintf(pdata->fh, "\" pos=\"%d", fi->start);
415         }
416 /*      fprintf(pdata->fh, "\" id=\"%d", fi->hfinfo->id);*/
417
418         /* show, value, and unmaskedvalue attributes */
419         switch (fi->hfinfo->type)
420         {
421         case FT_PROTOCOL:
422             break;
423         case FT_NONE:
424             fputs("\" show=\"\" value=\"",  pdata->fh);
425             break;
426         default:
427             dfilter_string = fvalue_to_string_repr(&fi->value, FTREPR_DISPLAY, NULL);
428             if (dfilter_string != NULL) {
429
430                 fputs("\" show=\"", pdata->fh);
431                 print_escaped_xml(pdata->fh, dfilter_string);
432             }
433             g_free(dfilter_string);
434
435             /*
436              * XXX - should we omit "value" for any fields?
437              * What should we do for fields whose length is 0?
438              * They might come from a pseudo-header or from
439              * the capture header (e.g., time stamps), or
440              * they might be generated fields.
441              */
442             if (fi->length > 0) {
443                 fputs("\" value=\"", pdata->fh);
444
445                 if (fi->hfinfo->bitmask!=0) {
446                     switch (fi->value.ftype->ftype) {
447                         case FT_INT8:
448                         case FT_INT16:
449                         case FT_INT24:
450                         case FT_INT32:
451                             fprintf(pdata->fh, "%X", (guint) fvalue_get_sinteger(&fi->value));
452                             break;
453                         case FT_UINT8:
454                         case FT_UINT16:
455                         case FT_UINT24:
456                         case FT_UINT32:
457                         case FT_BOOLEAN:
458                             fprintf(pdata->fh, "%X", fvalue_get_uinteger(&fi->value));
459                             break;
460                         case FT_INT64:
461                         case FT_UINT64:
462                             fprintf(pdata->fh, "%" G_GINT64_MODIFIER "X",
463                                     fvalue_get_integer64(&fi->value));
464                             break;
465                         default:
466                             g_assert_not_reached();
467                     }
468                     fputs("\" unmaskedvalue=\"", pdata->fh);
469                     write_pdml_field_hex_value(pdata, fi);
470                 }
471                 else {
472                     write_pdml_field_hex_value(pdata, fi);
473                 }
474             }
475         }
476
477         if (node->first_child != NULL) {
478             fputs("\">\n", pdata->fh);
479         }
480         else if (fi->hfinfo->id == proto_data) {
481             fputs("\">\n", pdata->fh);
482         }
483         else {
484             fputs("\"/>\n", pdata->fh);
485         }
486     }
487
488     /* We always print all levels for PDML. Recurse here. */
489     if (node->first_child != NULL) {
490         pdata->level++;
491         proto_tree_children_foreach(node,
492                                     proto_tree_write_node_pdml, pdata);
493         pdata->level--;
494     }
495
496     /* Take back the extra level we added for fake wrapper protocol */
497     if (wrap_in_fake_protocol) {
498         pdata->level--;
499     }
500
501     if (node->first_child != NULL) {
502         /* Indent to correct level */
503         for (i = -1; i < pdata->level; i++) {
504             fputs("  ", pdata->fh);
505         }
506         /* Close off current element */
507         /* Data and expert "protocols" use simple tags */
508         if ((fi->hfinfo->id != proto_data) && (fi->hfinfo->id != proto_expert)) {
509             if (fi->hfinfo->type == FT_PROTOCOL) {
510                 fputs("</proto>\n", pdata->fh);
511             }
512             else {
513                 fputs("</field>\n", pdata->fh);
514             }
515         } else {
516             fputs("</field>\n", pdata->fh);
517         }
518     }
519
520     /* Close off fake wrapper protocol */
521     if (wrap_in_fake_protocol) {
522         fputs("</proto>\n", pdata->fh);
523     }
524 }
525
526 /* Print info for a 'geninfo' pseudo-protocol. This is required by
527  * the PDML spec. The information is contained in Wireshark's 'frame' protocol,
528  * but we produce a 'geninfo' protocol in the PDML to conform to spec.
529  * The 'frame' protocol follows the 'geninfo' protocol in the PDML. */
530 static void
531 print_pdml_geninfo(proto_tree *tree, FILE *fh)
532 {
533     guint32     num, len, caplen;
534     nstime_t   *timestamp;
535     GPtrArray  *finfo_array;
536     field_info *frame_finfo;
537     gchar      *tmp;
538
539     /* Get frame protocol's finfo. */
540     finfo_array = proto_find_finfo(tree, proto_frame);
541     if (g_ptr_array_len(finfo_array) < 1) {
542         return;
543     }
544     frame_finfo = (field_info *)finfo_array->pdata[0];
545     g_ptr_array_free(finfo_array, TRUE);
546
547     /* frame.number --> geninfo.num */
548     finfo_array = proto_find_finfo(tree, hf_frame_number);
549     if (g_ptr_array_len(finfo_array) < 1) {
550         return;
551     }
552     num = fvalue_get_uinteger(&((field_info*)finfo_array->pdata[0])->value);
553     g_ptr_array_free(finfo_array, TRUE);
554
555     /* frame.frame_len --> geninfo.len */
556     finfo_array = proto_find_finfo(tree, hf_frame_len);
557     if (g_ptr_array_len(finfo_array) < 1) {
558         return;
559     }
560     len = fvalue_get_uinteger(&((field_info*)finfo_array->pdata[0])->value);
561     g_ptr_array_free(finfo_array, TRUE);
562
563     /* frame.cap_len --> geninfo.caplen */
564     finfo_array = proto_find_finfo(tree, hf_frame_capture_len);
565     if (g_ptr_array_len(finfo_array) < 1) {
566         return;
567     }
568     caplen = fvalue_get_uinteger(&((field_info*)finfo_array->pdata[0])->value);
569     g_ptr_array_free(finfo_array, TRUE);
570
571     /* frame.time --> geninfo.timestamp */
572     finfo_array = proto_find_finfo(tree, hf_frame_arrival_time);
573     if (g_ptr_array_len(finfo_array) < 1) {
574         return;
575     }
576     timestamp = (nstime_t *)fvalue_get(&((field_info*)finfo_array->pdata[0])->value);
577     g_ptr_array_free(finfo_array, TRUE);
578
579     /* Print geninfo start */
580     fprintf(fh,
581             "  <proto name=\"geninfo\" pos=\"0\" showname=\"General information\" size=\"%u\">\n",
582             frame_finfo->length);
583
584     /* Print geninfo.num */
585     fprintf(fh,
586             "    <field name=\"num\" pos=\"0\" show=\"%u\" showname=\"Number\" value=\"%x\" size=\"%u\"/>\n",
587             num, num, frame_finfo->length);
588
589     /* Print geninfo.len */
590     fprintf(fh,
591             "    <field name=\"len\" pos=\"0\" show=\"%u\" showname=\"Frame Length\" value=\"%x\" size=\"%u\"/>\n",
592             len, len, frame_finfo->length);
593
594     /* Print geninfo.caplen */
595     fprintf(fh,
596             "    <field name=\"caplen\" pos=\"0\" show=\"%u\" showname=\"Captured Length\" value=\"%x\" size=\"%u\"/>\n",
597             caplen, caplen, frame_finfo->length);
598
599     tmp = abs_time_to_str(NULL, timestamp, ABSOLUTE_TIME_LOCAL, TRUE);
600
601     /* Print geninfo.timestamp */
602     fprintf(fh,
603             "    <field name=\"timestamp\" pos=\"0\" show=\"%s\" showname=\"Captured Time\" value=\"%d.%09d\" size=\"%u\"/>\n",
604             tmp, (int) timestamp->secs, timestamp->nsecs, frame_finfo->length);
605
606     wmem_free(NULL, tmp);
607
608     /* Print geninfo end */
609     fprintf(fh,
610             "  </proto>\n");
611 }
612
613 void
614 write_pdml_finale(FILE *fh)
615 {
616     fputs("</pdml>\n", fh);
617 }
618
619 void
620 write_psml_preamble(FILE *fh)
621 {
622     fputs("<?xml version=\"1.0\"?>\n", fh);
623     fputs("<psml version=\"" PSML_VERSION "\" ", fh);
624     fprintf(fh, "creator=\"%s/%s\">\n", PACKAGE, VERSION);
625     write_headers = TRUE;
626 }
627
628 void
629 proto_tree_write_psml(epan_dissect_t *edt, FILE *fh)
630 {
631     gint i;
632
633     /* if this is the first packet, we have to create the PSML structure output */
634     if (write_headers) {
635         fprintf(fh, "<structure>\n");
636
637         for (i = 0; i < edt->pi.cinfo->num_cols; i++) {
638             fprintf(fh, "<section>");
639             print_escaped_xml(fh, edt->pi.cinfo->col_title[i]);
640             fprintf(fh, "</section>\n");
641         }
642
643         fprintf(fh, "</structure>\n\n");
644
645         write_headers = FALSE;
646     }
647
648     fprintf(fh, "<packet>\n");
649
650     for (i = 0; i < edt->pi.cinfo->num_cols; i++) {
651         fprintf(fh, "<section>");
652         print_escaped_xml(fh, edt->pi.cinfo->col_data[i]);
653         fprintf(fh, "</section>\n");
654     }
655
656     fprintf(fh, "</packet>\n\n");
657 }
658
659 void
660 write_psml_finale(FILE *fh)
661 {
662     fputs("</psml>\n", fh);
663 }
664
665 void
666 write_csv_preamble(FILE *fh _U_)
667 {
668     write_headers = TRUE;
669 }
670
671 static gchar *csv_massage_str(const gchar *source, const gchar *exceptions)
672 {
673     gchar *csv_str;
674     gchar *tmp_str;
675
676     /* In general, our output for any field can contain Unicode characters,
677        so g_strescape (which escapes any non-ASCII) is the wrong thing to do.
678        Unfortunately glib doesn't appear to provide g_unicode_strescape()... */
679     csv_str = g_strescape(source, exceptions);
680     tmp_str = csv_str;
681     /* Locate the UTF-8 right arrow character and replace it by an ASCII equivalent */
682     while ( (tmp_str = strstr(tmp_str, "\xe2\x86\x92")) != NULL ) {
683         tmp_str[0] = ' ';
684         tmp_str[1] = '>';
685         tmp_str[2] = ' ';
686     }
687     tmp_str = csv_str;
688     while ( (tmp_str = strstr(tmp_str, "\\\"")) != NULL )
689         *tmp_str = '\"';
690     return csv_str;
691 }
692
693 static void csv_write_str(const char *str, char sep, FILE *fh)
694 {
695     gchar *csv_str;
696
697     /* Do not escape the UTF-8 righ arrow character */
698     csv_str = csv_massage_str(str, "\xe2\x86\x92");
699     fprintf(fh, "\"%s\"%c", csv_str, sep);
700     g_free(csv_str);
701 }
702
703 void
704 proto_tree_write_csv(epan_dissect_t *edt, FILE *fh)
705 {
706     gint i;
707
708     /* if this is the first packet, we have to write the CSV header */
709     if (write_headers) {
710         for (i = 0; i < edt->pi.cinfo->num_cols - 1; i++)
711             csv_write_str(edt->pi.cinfo->col_title[i], ',', fh);
712         csv_write_str(edt->pi.cinfo->col_title[i], '\n', fh);
713         write_headers = FALSE;
714     }
715
716     for (i = 0; i < edt->pi.cinfo->num_cols - 1; i++)
717         csv_write_str(edt->pi.cinfo->col_data[i], ',', fh);
718     csv_write_str(edt->pi.cinfo->col_data[i], '\n', fh);
719 }
720
721 void
722 write_csv_finale(FILE *fh _U_)
723 {
724
725 }
726
727 void
728 write_carrays_preamble(FILE *fh _U_)
729 {
730
731 }
732
733 void
734 proto_tree_write_carrays(guint32 num, FILE *fh, epan_dissect_t *edt)
735 {
736     guint32       i = 0, src_num = 0;
737     GSList       *src_le;
738     tvbuff_t     *tvb;
739     const char   *name;
740     const guchar *cp;
741     guint         length;
742     char          ascii[9];
743     struct data_source *src;
744
745     for (src_le = edt->pi.data_src; src_le != NULL; src_le = src_le->next) {
746         memset(ascii, 0, sizeof(ascii));
747         src = (struct data_source *)src_le->data;
748         tvb = get_data_source_tvb(src);
749         length = tvb_length(tvb);
750         if (length == 0)
751             continue;
752
753         cp = tvb_get_ptr(tvb, 0, length);
754
755         name = get_data_source_name(src);
756         if (name)
757             fprintf(fh, "/* %s */\n", name);
758         if (src_num) {
759             fprintf(fh, "static const unsigned char pkt%u_%u[%u] = {\n",
760                     num, src_num, length);
761         } else {
762             fprintf(fh, "static const unsigned char pkt%u[%u] = {\n",
763                     num, length);
764         }
765         src_num++;
766
767         for (i = 0; i < length; i++) {
768             fprintf(fh, "0x%02x", *(cp + i));
769             ascii[i % 8] = g_ascii_isprint(*(cp + i)) ? *(cp + i) : '.';
770
771             if (i == (length - 1)) {
772                 guint rem;
773                 rem = length % 8;
774                 if (rem) {
775                     guint j;
776                     for ( j = 0; j < 8 - rem; j++ )
777                         fprintf(fh, "      ");
778                 }
779                 fprintf(fh, "  /* %s */\n};\n\n", ascii);
780                 break;
781             }
782
783             if (!((i + 1) % 8)) {
784                 fprintf(fh, ", /* %s */\n", ascii);
785                 memset(ascii, 0, sizeof(ascii));
786             }
787             else {
788                 fprintf(fh, ", ");
789             }
790         }
791     }
792 }
793
794 void
795 write_carrays_finale(FILE *fh _U_)
796 {
797
798 }
799
800 /*
801  * Find the data source for a specified field, and return a pointer
802  * to the data in it. Returns NULL if the data is out of bounds.
803  */
804 /* XXX: What am I missing ?
805  *      Why bother searching for fi->ds_tvb for the matching tvb
806  *       in the data_source list ?
807  *      IOW: Why not just use fi->ds_tvb for the arg to tvb_get_ptr() ?
808  */
809
810 static const guint8 *
811 get_field_data(GSList *src_list, field_info *fi)
812 {
813     GSList   *src_le;
814     tvbuff_t *src_tvb;
815     gint      length, tvbuff_length;
816     struct data_source *src;
817
818     for (src_le = src_list; src_le != NULL; src_le = src_le->next) {
819         src = (struct data_source *)src_le->data;
820         src_tvb = get_data_source_tvb(src);
821         if (fi->ds_tvb == src_tvb) {
822             /*
823              * Found it.
824              *
825              * XXX - a field can have a length that runs past
826              * the end of the tvbuff.  Ideally, that should
827              * be fixed when adding an item to the protocol
828              * tree, but checking the length when doing
829              * that could be expensive.  Until we fix that,
830              * we'll do the check here.
831              */
832             tvbuff_length = tvb_length_remaining(src_tvb,
833                                                  fi->start);
834             if (tvbuff_length < 0) {
835                 return NULL;
836             }
837             length = fi->length;
838             if (length > tvbuff_length)
839                 length = tvbuff_length;
840             return tvb_get_ptr(src_tvb, fi->start, length);
841         }
842     }
843     g_assert_not_reached();
844     return NULL;  /* not found */
845 }
846
847 /* Print a string, escaping out certain characters that need to
848  * escaped out for XML. */
849 static void
850 print_escaped_xml(FILE *fh, const char *unescaped_string)
851 {
852     const char *p;
853     char        temp_str[8];
854
855     for (p = unescaped_string; *p != '\0'; p++) {
856         switch (*p) {
857         case '&':
858             fputs("&amp;", fh);
859             break;
860         case '<':
861             fputs("&lt;", fh);
862             break;
863         case '>':
864             fputs("&gt;", fh);
865             break;
866         case '"':
867             fputs("&quot;", fh);
868             break;
869         case '\'':
870             fputs("&apos;", fh);
871             break;
872         default:
873             if (g_ascii_isprint(*p))
874                 fputc(*p, fh);
875             else {
876                 g_snprintf(temp_str, sizeof(temp_str), "\\x%x", (guint8)*p);
877                 fputs(temp_str, fh);
878             }
879         }
880     }
881 }
882
883 static void
884 write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi)
885 {
886     int           i;
887     const guint8 *pd;
888
889     if (!fi->ds_tvb)
890         return;
891
892     if (fi->length > tvb_length_remaining(fi->ds_tvb, fi->start)) {
893         fprintf(pdata->fh, "field length invalid!");
894         return;
895     }
896
897     /* Find the data for this field. */
898     pd = get_field_data(pdata->src_list, fi);
899
900     if (pd) {
901         /* Print a simple hex dump */
902         for (i = 0 ; i < fi->length; i++) {
903             fprintf(pdata->fh, "%02x", pd[i]);
904         }
905     }
906 }
907
908 gboolean
909 print_hex_data(print_stream_t *stream, epan_dissect_t *edt)
910 {
911     gboolean      multiple_sources;
912     GSList       *src_le;
913     tvbuff_t     *tvb;
914     const char   *name;
915     char         *line;
916     const guchar *cp;
917     guint         length;
918     struct data_source *src;
919
920     /*
921      * Set "multiple_sources" iff this frame has more than one
922      * data source; if it does, we need to print the name of
923      * the data source before printing the data from the
924      * data source.
925      */
926     multiple_sources = (edt->pi.data_src->next != NULL);
927
928     for (src_le = edt->pi.data_src; src_le != NULL;
929          src_le = src_le->next) {
930         src = (struct data_source *)src_le->data;
931         tvb = get_data_source_tvb(src);
932         if (multiple_sources) {
933             name = get_data_source_name(src);
934             line = g_strdup_printf("%s:", name);
935             print_line(stream, 0, line);
936             g_free(line);
937         }
938         length = tvb_length(tvb);
939         if (length == 0)
940             return TRUE;
941         cp = tvb_get_ptr(tvb, 0, length);
942         if (!print_hex_data_buffer(stream, cp, length,
943                                    (packet_char_enc)edt->pi.fd->flags.encoding))
944             return FALSE;
945     }
946     return TRUE;
947 }
948
949 /*
950  * This routine is based on a routine created by Dan Lasley
951  * <DLASLEY@PROMUS.com>.
952  *
953  * It was modified for Wireshark by Gilbert Ramirez and others.
954  */
955
956 #define MAX_OFFSET_LEN   8       /* max length of hex offset of bytes */
957 #define BYTES_PER_LINE  16      /* max byte values printed on a line */
958 #define HEX_DUMP_LEN    (BYTES_PER_LINE*3)
959                                 /* max number of characters hex dump takes -
960                                    2 digits plus trailing blank */
961 #define DATA_DUMP_LEN   (HEX_DUMP_LEN + 2 + BYTES_PER_LINE)
962                                 /* number of characters those bytes take;
963                                    3 characters per byte of hex dump,
964                                    2 blanks separating hex from ASCII,
965                                    1 character per byte of ASCII dump */
966 #define MAX_LINE_LEN    (MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN)
967                                 /* number of characters per line;
968                                    offset, 2 blanks separating offset
969                                    from data dump, data dump */
970
971 static gboolean
972 print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
973                       guint length, packet_char_enc encoding)
974 {
975     register unsigned int ad, i, j, k, l;
976     guchar                c;
977     gchar                 line[MAX_LINE_LEN + 1];
978     unsigned int          use_digits;
979
980     static gchar binhex[16] = {
981         '0', '1', '2', '3', '4', '5', '6', '7',
982         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
983
984     /*
985      * How many of the leading digits of the offset will we supply?
986      * We always supply at least 4 digits, but if the maximum offset
987      * won't fit in 4 digits, we use as many digits as will be needed.
988      */
989     if (((length - 1) & 0xF0000000) != 0)
990         use_digits = 8; /* need all 8 digits */
991     else if (((length - 1) & 0x0F000000) != 0)
992         use_digits = 7; /* need 7 digits */
993     else if (((length - 1) & 0x00F00000) != 0)
994         use_digits = 6; /* need 6 digits */
995     else if (((length - 1) & 0x000F0000) != 0)
996         use_digits = 5; /* need 5 digits */
997     else
998         use_digits = 4; /* we'll supply 4 digits */
999
1000     ad = 0;
1001     i = 0;
1002     j = 0;
1003     k = 0;
1004     while (i < length) {
1005         if ((i & 15) == 0) {
1006             /*
1007              * Start of a new line.
1008              */
1009             j = 0;
1010             l = use_digits;
1011             do {
1012                 l--;
1013                 c = (ad >> (l*4)) & 0xF;
1014                 line[j++] = binhex[c];
1015             } while (l != 0);
1016             line[j++] = ' ';
1017             line[j++] = ' ';
1018             memset(line+j, ' ', DATA_DUMP_LEN);
1019
1020             /*
1021              * Offset in line of ASCII dump.
1022              */
1023             k = j + HEX_DUMP_LEN + 2;
1024         }
1025         c = *cp++;
1026         line[j++] = binhex[c>>4];
1027         line[j++] = binhex[c&0xf];
1028         j++;
1029         if (encoding == PACKET_CHAR_ENC_CHAR_EBCDIC) {
1030             c = EBCDIC_to_ASCII1(c);
1031         }
1032         line[k++] = ((c >= ' ') && (c < 0x7f)) ? c : '.';
1033         i++;
1034         if (((i & 15) == 0) || (i == length)) {
1035             /*
1036              * We'll be starting a new line, or
1037              * we're finished printing this buffer;
1038              * dump out the line we've constructed,
1039              * and advance the offset.
1040              */
1041             line[k] = '\0';
1042             if (!print_line(stream, 0, line))
1043                 return FALSE;
1044             ad += 16;
1045         }
1046     }
1047     return TRUE;
1048 }
1049
1050 static
1051 void ps_clean_string(char *out, const char *in, int outbuf_size)
1052 {
1053     int  rd, wr;
1054     char c;
1055
1056     if (in == NULL) {
1057         out[0] = '\0';
1058         return;
1059     }
1060
1061     for (rd = 0, wr = 0 ; wr < outbuf_size; rd++, wr++ ) {
1062         c = in[rd];
1063         switch (c) {
1064         case '(':
1065         case ')':
1066         case '\\':
1067             out[wr] = '\\';
1068             out[++wr] = c;
1069             break;
1070
1071         default:
1072             out[wr] = c;
1073             break;
1074         }
1075
1076         if (c == 0) {
1077             break;
1078         }
1079     }
1080 }
1081
1082 /* Some formats need stuff at the beginning of the output */
1083 gboolean
1084 print_preamble(print_stream_t *self, gchar *filename, const char *version_string)
1085 {
1086     return self->ops->print_preamble ? (self->ops->print_preamble)(self, filename, version_string) : TRUE;
1087 }
1088
1089 gboolean
1090 print_line(print_stream_t *self, int indent, const char *line)
1091 {
1092     return (self->ops->print_line)(self, indent, line);
1093 }
1094
1095 /* Insert bookmark */
1096 gboolean
1097 print_bookmark(print_stream_t *self, const gchar *name, const gchar *title)
1098 {
1099     return self->ops->print_bookmark ? (self->ops->print_bookmark)(self, name, title) : TRUE;
1100 }
1101
1102 gboolean
1103 new_page(print_stream_t *self)
1104 {
1105     return self->ops->new_page ? (self->ops->new_page)(self) : TRUE;
1106 }
1107
1108 /* Some formats need stuff at the end of the output */
1109 gboolean
1110 print_finale(print_stream_t *self)
1111 {
1112     return self->ops->print_finale ? (self->ops->print_finale)(self) : TRUE;
1113 }
1114
1115 gboolean
1116 destroy_print_stream(print_stream_t *self)
1117 {
1118     return self->ops->destroy ? (self->ops->destroy)(self) : TRUE;
1119 }
1120
1121 typedef struct {
1122     gboolean  to_file;
1123     FILE     *fh;
1124 } output_text;
1125
1126 static gboolean
1127 print_line_text(print_stream_t *self, int indent, const char *line)
1128 {
1129     static char  spaces[MAX_INDENT];
1130     size_t ret;
1131
1132     output_text *output = (output_text *)self->data;
1133     unsigned int num_spaces;
1134
1135     /* should be space, if NUL -> initialize */
1136     if (!spaces[0]) {
1137         int i;
1138
1139         for (i = 0; i < MAX_INDENT; i++)
1140             spaces[i] = ' ';
1141     }
1142
1143     /* Prepare the tabs for printing, depending on tree level */
1144     num_spaces = indent * 4;
1145     if (num_spaces > MAX_INDENT)
1146         num_spaces = MAX_INDENT;
1147
1148     ret = fwrite(spaces, 1, num_spaces, output->fh);
1149     if (ret == num_spaces) {
1150         fputs(line, output->fh);
1151         putc('\n', output->fh);
1152     }
1153     return !ferror(output->fh);
1154 }
1155
1156 static gboolean
1157 new_page_text(print_stream_t *self)
1158 {
1159     output_text *output = (output_text *)self->data;
1160
1161     fputs("\f", output->fh);
1162     return !ferror(output->fh);
1163 }
1164
1165 static gboolean
1166 destroy_text(print_stream_t *self)
1167 {
1168     output_text *output = (output_text *)self->data;
1169     gboolean     ret;
1170
1171     ret = close_print_dest(output->to_file, output->fh);
1172     g_free(output);
1173     g_free(self);
1174     return ret;
1175 }
1176
1177 static const print_stream_ops_t print_text_ops = {
1178     NULL,            /* preamble */
1179     print_line_text,
1180     NULL,            /* bookmark */
1181     new_page_text,
1182     NULL,            /* finale */
1183     destroy_text
1184 };
1185
1186 static print_stream_t *
1187 print_stream_text_alloc(gboolean to_file, FILE *fh)
1188 {
1189     print_stream_t *stream;
1190     output_text    *output;
1191
1192     output          = (output_text *)g_malloc(sizeof *output);
1193     output->to_file = to_file;
1194     output->fh      = fh;
1195     stream          = (print_stream_t *)g_malloc(sizeof (print_stream_t));
1196     stream->ops     = &print_text_ops;
1197     stream->data    = output;
1198
1199     return stream;
1200 }
1201
1202 print_stream_t *
1203 print_stream_text_new(gboolean to_file, const char *dest)
1204 {
1205     FILE *fh;
1206
1207     fh = open_print_dest(to_file, dest);
1208     if (fh == NULL)
1209         return NULL;
1210
1211     return print_stream_text_alloc(to_file, fh);
1212 }
1213
1214 print_stream_t *
1215 print_stream_text_stdio_new(FILE *fh)
1216 {
1217     return print_stream_text_alloc(TRUE, fh);
1218 }
1219
1220 typedef struct {
1221     gboolean  to_file;
1222     FILE     *fh;
1223 } output_ps;
1224
1225 static gboolean
1226 print_preamble_ps(print_stream_t *self, gchar *filename, const char *version_string)
1227 {
1228     output_ps *output = (output_ps *)self->data;
1229     char       psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1230
1231     print_ps_preamble(output->fh);
1232
1233     fputs("%% the page title\n", output->fh);
1234     ps_clean_string(psbuffer, filename, MAX_PS_LINE_LENGTH);
1235     fprintf(output->fh, "/ws_pagetitle (%s - Wireshark %s) def\n", psbuffer, version_string);
1236     fputs("\n", output->fh);
1237     return !ferror(output->fh);
1238 }
1239
1240 static gboolean
1241 print_line_ps(print_stream_t *self, int indent, const char *line)
1242 {
1243     output_ps *output = (output_ps *)self->data;
1244     char       psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1245
1246     ps_clean_string(psbuffer, line, MAX_PS_LINE_LENGTH);
1247     fprintf(output->fh, "%d (%s) putline\n", indent, psbuffer);
1248     return !ferror(output->fh);
1249 }
1250
1251 static gboolean
1252 print_bookmark_ps(print_stream_t *self, const gchar *name, const gchar *title)
1253 {
1254     output_ps *output = (output_ps *)self->data;
1255     char       psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1256
1257     /*
1258      * See the Adobe "pdfmark reference":
1259      *
1260      *  http://partners.adobe.com/asn/acrobat/docs/pdfmark.pdf
1261      *
1262      * The pdfmark stuff tells code that turns PostScript into PDF
1263      * things that it should do.
1264      *
1265      * The /OUT stuff creates a bookmark that goes to the
1266      * destination with "name" as the name and "title" as the title.
1267      *
1268      * The "/DEST" creates the destination.
1269      */
1270     ps_clean_string(psbuffer, title, MAX_PS_LINE_LENGTH);
1271     fprintf(output->fh, "[/Dest /%s /Title (%s)   /OUT pdfmark\n", name,
1272           psbuffer);
1273     fputs("[/View [/XYZ -4 currentpoint matrix currentmatrix matrix defaultmatrix\n",
1274           output->fh);
1275     fputs("matrix invertmatrix matrix concatmatrix transform exch pop 20 add null]\n",
1276           output->fh);
1277     fprintf(output->fh, "/Dest /%s /DEST pdfmark\n", name);
1278     return !ferror(output->fh);
1279 }
1280
1281 static gboolean
1282 new_page_ps(print_stream_t *self)
1283 {
1284     output_ps *output = (output_ps *)self->data;
1285
1286     fputs("formfeed\n", output->fh);
1287     return !ferror(output->fh);
1288 }
1289
1290 static gboolean
1291 print_finale_ps(print_stream_t *self)
1292 {
1293     output_ps *output = (output_ps *)self->data;
1294
1295     print_ps_finale(output->fh);
1296     return !ferror(output->fh);
1297 }
1298
1299 static gboolean
1300 destroy_ps(print_stream_t *self)
1301 {
1302     output_ps *output = (output_ps *)self->data;
1303     gboolean   ret;
1304
1305     ret = close_print_dest(output->to_file, output->fh);
1306     g_free(output);
1307     g_free(self);
1308     return ret;
1309 }
1310
1311 static const print_stream_ops_t print_ps_ops = {
1312     print_preamble_ps,
1313     print_line_ps,
1314     print_bookmark_ps,
1315     new_page_ps,
1316     print_finale_ps,
1317     destroy_ps
1318 };
1319
1320 static print_stream_t *
1321 print_stream_ps_alloc(gboolean to_file, FILE *fh)
1322 {
1323     print_stream_t *stream;
1324     output_ps      *output;
1325
1326     output          = (output_ps *)g_malloc(sizeof *output);
1327     output->to_file = to_file;
1328     output->fh      = fh;
1329     stream          = (print_stream_t *)g_malloc(sizeof (print_stream_t));
1330     stream->ops     = &print_ps_ops;
1331     stream->data    = output;
1332
1333     return stream;
1334 }
1335
1336 print_stream_t *
1337 print_stream_ps_new(gboolean to_file, const char *dest)
1338 {
1339     FILE *fh;
1340
1341     fh = open_print_dest(to_file, dest);
1342     if (fh == NULL)
1343         return NULL;
1344
1345     return print_stream_ps_alloc(to_file, fh);
1346 }
1347
1348 print_stream_t *
1349 print_stream_ps_stdio_new(FILE *fh)
1350 {
1351     return print_stream_ps_alloc(TRUE, fh);
1352 }
1353
1354 output_fields_t* output_fields_new(void)
1355 {
1356     output_fields_t* fields     = g_new(output_fields_t, 1);
1357     fields->print_header        = FALSE;
1358     fields->separator           = '\t';
1359     fields->occurrence          = 'a';
1360     fields->aggregator          = ',';
1361     fields->fields              = NULL; /*Do lazy initialisation */
1362     fields->field_indicies      = NULL;
1363     fields->field_values        = NULL;
1364     fields->quote               ='\0';
1365     fields->includes_col_fields = FALSE;
1366     return fields;
1367 }
1368
1369 gsize output_fields_num_fields(output_fields_t* fields)
1370 {
1371     g_assert(fields);
1372
1373     if (NULL == fields->fields) {
1374         return 0;
1375     } else {
1376         return fields->fields->len;
1377     }
1378 }
1379
1380 void output_fields_free(output_fields_t* fields)
1381 {
1382     g_assert(fields);
1383
1384     if (NULL != fields->fields) {
1385         gsize i;
1386
1387         if (NULL != fields->field_indicies) {
1388             /* Keys are stored in fields->fields, values are
1389              * integers.
1390              */
1391             g_hash_table_destroy(fields->field_indicies);
1392         }
1393
1394         if (NULL != fields->field_values) {
1395             g_free(fields->field_values);
1396         }
1397
1398         for(i = 0; i < fields->fields->len; ++i) {
1399             gchar* field = (gchar *)g_ptr_array_index(fields->fields,i);
1400             g_free(field);
1401         }
1402         g_ptr_array_free(fields->fields, TRUE);
1403     }
1404
1405     g_free(fields);
1406 }
1407
1408 #define COLUMN_FIELD_FILTER  "_ws.col."
1409
1410 void output_fields_add(output_fields_t *fields, const gchar *field)
1411 {
1412     gchar *field_copy;
1413
1414     g_assert(fields);
1415     g_assert(field);
1416
1417
1418     if (NULL == fields->fields) {
1419         fields->fields = g_ptr_array_new();
1420     }
1421
1422     field_copy = g_strdup(field);
1423
1424     g_ptr_array_add(fields->fields, field_copy);
1425
1426     /* See if we have a column as a field entry */
1427     if (!strncmp(field, COLUMN_FIELD_FILTER, strlen(COLUMN_FIELD_FILTER)))
1428         fields->includes_col_fields = TRUE;
1429
1430 }
1431
1432 static void
1433 output_field_check(void *data, void *user_data)
1434 {
1435     gchar *field = (gchar *)data;
1436     gboolean *all_valid = (gboolean *)user_data;
1437
1438     if (!strncmp(field, COLUMN_FIELD_FILTER, strlen(COLUMN_FIELD_FILTER)))
1439         return;
1440
1441     if (!proto_registrar_get_byname(field)) {
1442         g_warning("'%s' isn't a valid field!", field);
1443         *all_valid = FALSE;
1444     }
1445
1446 }
1447
1448 gboolean
1449 output_fields_valid(output_fields_t *fields)
1450 {
1451     gboolean all_valid = TRUE;
1452
1453     if (fields->fields == NULL) {
1454         return TRUE;
1455     }
1456
1457     g_ptr_array_foreach(fields->fields, output_field_check, &all_valid);
1458
1459     return all_valid;
1460 }
1461
1462 gboolean output_fields_set_option(output_fields_t *info, gchar *option)
1463 {
1464     const gchar *option_name;
1465     const gchar *option_value;
1466
1467     g_assert(info);
1468     g_assert(option);
1469
1470     if ('\0' == *option) {
1471         return FALSE; /* Is this guarded against by option parsing? */
1472     }
1473     option_name = strtok(option, "=");
1474     if (!option_name) {
1475         return FALSE;
1476     }
1477     option_value = option + strlen(option_name) + 1;
1478     if (0 == strcmp(option_name, "header")) {
1479         switch (NULL == option_value ? '\0' : *option_value) {
1480         case 'n':
1481             info->print_header = FALSE;
1482             break;
1483         case 'y':
1484             info->print_header = TRUE;
1485             break;
1486         default:
1487             return FALSE;
1488         }
1489         return TRUE;
1490     }
1491
1492     if (0 == strcmp(option_name, "separator")) {
1493         switch (NULL == option_value ? '\0' : *option_value) {
1494         case '\0':
1495             return FALSE;
1496         case '/':
1497             switch (*++option_value) {
1498             case 't':
1499                 info->separator = '\t';
1500                 break;
1501             case 's':
1502                 info->separator = ' ';
1503                 break;
1504             default:
1505                 info->separator = '\\';
1506             }
1507             break;
1508         default:
1509             info->separator = *option_value;
1510             break;
1511         }
1512         return TRUE;
1513     }
1514
1515     if (0 == strcmp(option_name, "occurrence")) {
1516         switch (NULL == option_value ? '\0' : *option_value) {
1517         case 'f':
1518         case 'l':
1519         case 'a':
1520             info->occurrence = *option_value;
1521             break;
1522         default:
1523             return FALSE;
1524         }
1525         return TRUE;
1526     }
1527
1528     if (0 == strcmp(option_name, "aggregator")) {
1529         switch (NULL == option_value ? '\0' : *option_value) {
1530         case '\0':
1531             return FALSE;
1532         case '/':
1533             switch (*++option_value) {
1534             case 's':
1535                 info->aggregator = ' ';
1536                 break;
1537             default:
1538                 info->aggregator = '\\';
1539             }
1540             break;
1541         default:
1542             info->aggregator = *option_value;
1543             break;
1544         }
1545         return TRUE;
1546     }
1547
1548     if (0 == strcmp(option_name, "quote")) {
1549         switch (NULL == option_value ? '\0' : *option_value) {
1550         default: /* Fall through */
1551         case '\0':
1552             info->quote = '\0';
1553             return FALSE;
1554         case 'd':
1555             info->quote = '"';
1556             break;
1557         case 's':
1558             info->quote = '\'';
1559             break;
1560         case 'n':
1561             info->quote = '\0';
1562             break;
1563         }
1564         return TRUE;
1565     }
1566
1567     return FALSE;
1568 }
1569
1570 void output_fields_list_options(FILE *fh)
1571 {
1572     fprintf(fh, "TShark: The available options for field output \"E\" are:\n");
1573     fputs("header=y|n    Print field abbreviations as first line of output (def: N: no)\n", fh);
1574     fputs("separator=/t|/s|<character>   Set the separator to use;\n     \"/t\" = tab, \"/s\" = space (def: /t: tab)\n", fh);
1575     fputs("occurrence=f|l|a  Select the occurrence of a field to use;\n     \"f\" = first, \"l\" = last, \"a\" = all (def: a: all)\n", fh);
1576     fputs("aggregator=,|/s|<character>   Set the aggregator to use;\n     \",\" = comma, \"/s\" = space (def: ,: comma)\n", fh);
1577     fputs("quote=d|s|n   Print either d: double-quotes, s: single quotes or \n     n: no quotes around field values (def: n: none)\n", fh);
1578 }
1579
1580 gboolean output_fields_has_cols(output_fields_t* fields)
1581 {
1582     g_assert(fields);
1583     return fields->includes_col_fields;
1584 }
1585
1586 void write_fields_preamble(output_fields_t* fields, FILE *fh)
1587 {
1588     gsize i;
1589
1590     g_assert(fields);
1591     g_assert(fh);
1592     g_assert(fields->fields);
1593
1594     if (!fields->print_header) {
1595         return;
1596     }
1597
1598     for(i = 0; i < fields->fields->len; ++i) {
1599         const gchar* field = (const gchar *)g_ptr_array_index(fields->fields,i);
1600         if (i != 0 ) {
1601             fputc(fields->separator, fh);
1602         }
1603         fputs(field, fh);
1604     }
1605     fputc('\n', fh);
1606 }
1607
1608 static void format_field_values(output_fields_t* fields, gpointer field_index, const gchar* value)
1609 {
1610     guint      indx;
1611     GPtrArray* fv_p;
1612
1613     if ((NULL == value) || ('\0' == *value))
1614         return;
1615
1616     /* Unwrap change made to disambiguiate zero / null */
1617     indx = GPOINTER_TO_UINT(field_index) - 1;
1618
1619     if (fields->field_values[indx] == NULL) {
1620         fields->field_values[indx] = g_ptr_array_new();
1621     }
1622
1623     /* Essentially: fieldvalues[indx] is a 'GPtrArray *' with each array entry */
1624     /*  pointing to a string which is (part of) the final output string.       */
1625
1626     fv_p = fields->field_values[indx];
1627
1628     switch (fields->occurrence) {
1629     case 'f':
1630         /* print the value of only the first occurrence of the field */
1631         if (g_ptr_array_len(fv_p) != 0)
1632             return;
1633         break;
1634     case 'l':
1635         /* print the value of only the last occurrence of the field */
1636         g_ptr_array_set_size(fv_p, 0);
1637         break;
1638     case 'a':
1639         /* print the value of all accurrences of the field */
1640         /* If not the first, add the 'aggregator' */
1641         if (g_ptr_array_len(fv_p) > 0) {
1642             g_ptr_array_add(fv_p, (gpointer)g_strdup_printf("%c", fields->aggregator));
1643         }
1644         break;
1645     default:
1646         g_assert_not_reached();
1647         break;
1648     }
1649
1650     g_ptr_array_add(fv_p, (gpointer)value);
1651 }
1652
1653 static void proto_tree_get_node_field_values(proto_node *node, gpointer data)
1654 {
1655     write_field_data_t *call_data;
1656     field_info *fi;
1657     gpointer    field_index;
1658
1659     call_data = (write_field_data_t *)data;
1660     fi = PNODE_FINFO(node);
1661
1662     /* dissection with an invisible proto tree? */
1663     g_assert(fi);
1664
1665     field_index = g_hash_table_lookup(call_data->fields->field_indicies, fi->hfinfo->abbrev);
1666     if (NULL != field_index) {
1667         format_field_values(call_data->fields, field_index,
1668                             get_node_field_value(fi, call_data->edt) /* g_ alloc'd string */
1669             );
1670     }
1671
1672     /* Recurse here. */
1673     if (node->first_child != NULL) {
1674         proto_tree_children_foreach(node, proto_tree_get_node_field_values,
1675                                     call_data);
1676     }
1677 }
1678
1679 void proto_tree_write_fields(output_fields_t *fields, epan_dissect_t *edt, column_info *cinfo, FILE *fh)
1680 {
1681     gsize     i;
1682     gint      col;
1683     gchar    *col_name;
1684     gpointer  field_index;
1685
1686     write_field_data_t data;
1687
1688     g_assert(fields);
1689     g_assert(fields->fields);
1690     g_assert(edt);
1691     g_assert(fh);
1692
1693     data.fields = fields;
1694     data.edt = edt;
1695
1696     if (NULL == fields->field_indicies) {
1697         /* Prepare a lookup table from string abbreviation for field to its index. */
1698         fields->field_indicies = g_hash_table_new(g_str_hash, g_str_equal);
1699
1700         i = 0;
1701         while (i < fields->fields->len) {
1702             gchar *field = (gchar *)g_ptr_array_index(fields->fields, i);
1703             /* Store field indicies +1 so that zero is not a valid value,
1704              * and can be distinguished from NULL as a pointer.
1705              */
1706             ++i;
1707             g_hash_table_insert(fields->field_indicies, field, GUINT_TO_POINTER(i));
1708         }
1709     }
1710
1711     /* Array buffer to store values for this packet              */
1712     /*  Allocate an array for the 'GPtrarray *' the first time   */
1713     /*   ths function is invoked for a file;                     */
1714     /*  Any and all 'GPtrArray *' are freed (after use) each     */
1715     /*   time (each packet) this function is invoked for a flle. */
1716     /* XXX: ToDo: use packet-scope'd memory & (if/when implemented) wmem ptr_array */
1717     if (NULL == fields->field_values)
1718         fields->field_values = g_new0(GPtrArray*, fields->fields->len);  /* free'd in output_fields_free() */
1719
1720     proto_tree_children_foreach(edt->tree, proto_tree_get_node_field_values,
1721                                 &data);
1722
1723     if (fields->includes_col_fields) {
1724         for (col = 0; col < cinfo->num_cols; col++) {
1725             /* Prepend COLUMN_FIELD_FILTER as the field name */
1726             col_name = ep_strdup_printf("%s%s", COLUMN_FIELD_FILTER, cinfo->col_title[col]);
1727             field_index = g_hash_table_lookup(fields->field_indicies, col_name);
1728
1729             if (NULL != field_index) {
1730                 format_field_values(fields, field_index, g_strdup(cinfo->col_data[col]));
1731             }
1732         }
1733     }
1734
1735     for(i = 0; i < fields->fields->len; ++i) {
1736         if (0 != i) {
1737             fputc(fields->separator, fh);
1738         }
1739         if (NULL != fields->field_values[i]) {
1740             GPtrArray *fv_p;
1741             gchar * str;
1742             gsize j;
1743             fv_p = fields->field_values[i];
1744             if (fields->quote != '\0') {
1745                 fputc(fields->quote, fh);
1746             }
1747
1748             /* Output the array of (partial) field values */
1749             for (j = 0; j < g_ptr_array_len(fv_p); j++ ) {
1750                 str = (gchar *)g_ptr_array_index(fv_p, j);
1751                 fputs(str, fh);
1752                 g_free(str);
1753             }
1754             if (fields->quote != '\0') {
1755                 fputc(fields->quote, fh);
1756             }
1757             g_ptr_array_free(fv_p, TRUE);  /* get ready for the next packet */
1758             fields->field_values[i] = NULL;
1759         }
1760     }
1761 }
1762
1763 void write_fields_finale(output_fields_t* fields _U_ , FILE *fh _U_)
1764 {
1765     /* Nothing to do */
1766 }
1767
1768 /* Returns an g_malloced string */
1769 gchar* get_node_field_value(field_info* fi, epan_dissect_t* edt)
1770 {
1771     if (fi->hfinfo->id == hf_text_only) {
1772         /* Text label.
1773          * Get the text */
1774         if (fi->rep) {
1775             return g_strdup(fi->rep->representation);
1776         }
1777         else {
1778             return get_field_hex_value(edt->pi.data_src, fi);
1779         }
1780     }
1781     else if (fi->hfinfo->id == proto_data) {
1782         /* Uninterpreted data, i.e., the "Data" protocol, is
1783          * printed as a field instead of a protocol. */
1784         return get_field_hex_value(edt->pi.data_src, fi);
1785     }
1786     else {
1787         /* Normal protocols and fields */
1788         gchar      *dfilter_string;
1789
1790         switch (fi->hfinfo->type)
1791         {
1792         case FT_PROTOCOL:
1793             /* Print out the full details for the protocol. */
1794             if (fi->rep) {
1795                 return g_strdup(fi->rep->representation);
1796             } else {
1797                 /* Just print out the protocol abbreviation */
1798                 return g_strdup(fi->hfinfo->abbrev);
1799             }
1800         case FT_NONE:
1801             /* Return "1" so that the presence of a field of type
1802              * FT_NONE can be checked when using -T fields */
1803             return g_strdup("1");
1804         default:
1805             dfilter_string = fvalue_to_string_repr(&fi->value, FTREPR_DISPLAY, NULL);
1806             if (dfilter_string != NULL) {
1807                 return dfilter_string;
1808             } else {
1809                 return get_field_hex_value(edt->pi.data_src, fi);
1810             }
1811         }
1812     }
1813 }
1814
1815 static gchar*
1816 get_field_hex_value(GSList *src_list, field_info *fi)
1817 {
1818     const guint8 *pd;
1819
1820     if (!fi->ds_tvb)
1821         return NULL;
1822
1823     if (fi->length > tvb_length_remaining(fi->ds_tvb, fi->start)) {
1824         return g_strdup("field length invalid!");
1825     }
1826
1827     /* Find the data for this field. */
1828     pd = get_field_data(src_list, fi);
1829
1830     if (pd) {
1831         int        i;
1832         gchar     *buffer;
1833         gchar     *p;
1834         int        len;
1835         const int  chars_per_byte = 2;
1836
1837         len    = chars_per_byte * fi->length;
1838         buffer = (gchar *)g_malloc(sizeof(gchar)*(len + 1));
1839         buffer[len] = '\0'; /* Ensure NULL termination in bad cases */
1840         p = buffer;
1841         /* Print a simple hex dump */
1842         for (i = 0 ; i < fi->length; i++) {
1843             g_snprintf(p, chars_per_byte+1, "%02x", pd[i]);
1844             p += chars_per_byte;
1845         }
1846         return buffer;
1847     } else {
1848         return NULL;
1849     }
1850 }
1851