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