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