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