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