Update the ptvcursors chapter.
[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
39 #include "packet-range.h"
40 #include "print.h"
41 #include "ps.h"
42 #include "file_util.h"
43 #include <epan/charsets.h>
44 #include <epan/dissectors/packet-data.h>
45 #include <epan/dissectors/packet-frame.h>
46
47 #define PDML_VERSION "0"
48 #define PSML_VERSION "0"
49
50 typedef struct {
51         int                     level;
52         print_stream_t          *stream;
53         gboolean                success;
54         GSList                  *src_list;
55         print_dissections_e     print_dissections;
56         gboolean                print_hex_for_data;
57         char_enc                encoding;
58         epan_dissect_t          *edt;
59 } print_data;
60
61 typedef struct {
62         int                     level;
63         FILE                    *fh;
64         GSList                  *src_list;
65         epan_dissect_t          *edt;
66 } write_pdml_data;
67
68 static void proto_tree_print_node(proto_node *node, gpointer data);
69 static void proto_tree_write_node_pdml(proto_node *node, gpointer data);
70 static const guint8 *get_field_data(GSList *src_list, field_info *fi);
71 static void write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi);
72 static gboolean print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
73     guint length, char_enc encoding);
74 static void ps_clean_string(unsigned char *out, const unsigned char *in,
75                         int outbuf_size);
76 static void print_escaped_xml(FILE *fh, const char *unescaped_string);
77
78 static void print_pdml_geninfo(proto_tree *tree, FILE *fh);
79
80 static FILE *
81 open_print_dest(int to_file, const char *dest)
82 {
83         FILE    *fh;
84
85         /* Open the file or command for output */
86         if (to_file)
87                 fh = eth_fopen(dest, "w");
88         else
89                 fh = popen(dest, "w");
90
91         return fh;
92 }
93
94 static gboolean
95 close_print_dest(int to_file, FILE *fh)
96 {
97         /* Close the file or command */
98         if (to_file)
99                 return (fclose(fh) == 0);
100         else
101                 return (pclose(fh) == 0);
102 }
103
104 #define MAX_PS_LINE_LENGTH 256
105
106 gboolean
107 proto_tree_print(print_args_t *print_args, epan_dissect_t *edt,
108     print_stream_t *stream)
109 {
110         print_data data;
111
112         /* Create the output */
113         data.level = 0;
114         data.stream = stream;
115         data.success = TRUE;
116         data.src_list = edt->pi.data_src;
117         data.encoding = edt->pi.fd->flags.encoding;
118         data.print_dissections = print_args->print_dissections;
119         /* If we're printing the entire packet in hex, don't
120            print uninterpreted data fields in hex as well. */
121         data.print_hex_for_data = !print_args->print_hex;
122         data.edt = edt;
123
124         proto_tree_children_foreach(edt->tree, proto_tree_print_node, &data);
125         return data.success;
126 }
127
128 #define MAX_INDENT      160
129
130 /* Print a tree's data, and any child nodes. */
131 static
132 void proto_tree_print_node(proto_node *node, gpointer data)
133 {
134         field_info      *fi = PITEM_FINFO(node);
135         print_data      *pdata = (print_data*) data;
136         const guint8    *pd;
137         gchar           label_str[ITEM_LABEL_LENGTH];
138         gchar           *label_ptr;
139
140         /* Don't print invisible entries. */
141         if (PROTO_ITEM_IS_HIDDEN(node))
142                 return;
143
144         /* Give up if we've already gotten an error. */
145         if (!pdata->success)
146                 return;
147
148         /* was a free format label produced? */
149         if (fi->rep) {
150                 label_ptr = fi->rep->representation;
151         }
152         else { /* no, make a generic label */
153                 label_ptr = label_str;
154                 proto_item_fill_label(fi, label_str);
155         }
156
157         if (!print_line(pdata->stream, pdata->level, label_ptr)) {
158                 pdata->success = FALSE;
159                 return;
160         }
161
162         /* If it's uninterpreted data, dump it (unless our caller will
163            be printing the entire packet in hex). */
164         if (fi->hfinfo->id == proto_data && pdata->print_hex_for_data) {
165                 /*
166                  * Find the data for this field.
167                  */
168                 pd = get_field_data(pdata->src_list, fi);
169                 if (pd) {
170                         if (!print_hex_data_buffer(pdata->stream, pd,
171                             fi->length, pdata->encoding)) {
172                                 pdata->success = FALSE;
173                                 return;
174                         }
175                 }
176         }
177
178         /* If we're printing all levels, or if this node is one with a
179            subtree and its subtree is expanded, recurse into the subtree,
180            if it exists. */
181         g_assert(fi->tree_type >= -1 && fi->tree_type < num_tree_types);
182         if (pdata->print_dissections == print_dissections_expanded ||
183             (pdata->print_dissections == print_dissections_as_displayed &&
184                 fi->tree_type >= 0 && tree_is_expanded[fi->tree_type])) {
185                 if (node->first_child != NULL) {
186                         pdata->level++;
187                         proto_tree_children_foreach(node,
188                                 proto_tree_print_node, pdata);
189                         pdata->level--;
190                         if (!pdata->success)
191                                 return;
192                 }
193         }
194 }
195
196 void
197 write_pdml_preamble(FILE *fh)
198 {
199         fputs("<?xml version=\"1.0\"?>\n", fh);
200         fputs("<pdml version=\"" PDML_VERSION "\" ", fh);
201         fprintf(fh, "creator=\"%s/%s\">\n", PACKAGE, VERSION);
202 }
203
204 void
205 proto_tree_write_pdml(epan_dissect_t *edt, FILE *fh)
206 {
207         write_pdml_data data;
208
209         /* Create the output */
210         data.level = 0;
211         data.fh = fh;
212         data.src_list = edt->pi.data_src;
213         data.edt = edt;
214
215         fprintf(fh, "<packet>\n");
216
217         /* Print a "geninfo" protocol as required by PDML */
218         print_pdml_geninfo(edt->tree, fh);
219
220         proto_tree_children_foreach(edt->tree, proto_tree_write_node_pdml,
221             &data);
222
223         fprintf(fh, "</packet>\n\n");
224 }
225
226 /* Write out a tree's data, and any child nodes, as PDML */
227 static void
228 proto_tree_write_node_pdml(proto_node *node, gpointer data)
229 {
230         field_info      *fi = PITEM_FINFO(node);
231         write_pdml_data *pdata = (write_pdml_data*) data;
232         const gchar     *label_ptr;
233         gchar           label_str[ITEM_LABEL_LENGTH];
234         char            *dfilter_string;
235         int             chop_len;
236         int             i;
237
238         for (i = -1; i < pdata->level; i++) {
239                 fputs("  ", pdata->fh);
240         }
241
242         /* Text label. It's printed as a field with no name. */
243         if (fi->hfinfo->id == hf_text_only) {
244                 /* Get the text */
245                 if (fi->rep) {
246                         label_ptr = fi->rep->representation;
247                 }
248                 else {
249                         label_ptr = "";
250                 }
251
252                 fputs("<field show=\"", pdata->fh);
253                 print_escaped_xml(pdata->fh, label_ptr);
254
255                 fprintf(pdata->fh, "\" size=\"%d", fi->length);
256                 fprintf(pdata->fh, "\" pos=\"%d", fi->start);
257
258                 fputs("\" value=\"", pdata->fh);
259                 write_pdml_field_hex_value(pdata, fi);
260
261                 if (node->first_child != NULL) {
262                         fputs("\">\n", pdata->fh);
263                 }
264                 else {
265                         fputs("\"/>\n", pdata->fh);
266                 }
267         }
268         /* Uninterpreted data, i.e., the "Data" protocol, is
269          * printed as a field instead of a protocol. */
270         else if (fi->hfinfo->id == proto_data) {
271
272                 fputs("<field name=\"data\" value=\"", pdata->fh);
273
274                 write_pdml_field_hex_value(pdata, fi);
275
276                 fputs("\"/>\n", pdata->fh);
277
278         }
279         /* Normal protocols and fields */
280         else {
281                 if (fi->hfinfo->type == FT_PROTOCOL) {
282                         fputs("<proto name=\"", pdata->fh);
283                 }
284                 else {
285                         fputs("<field name=\"", pdata->fh);
286                 }
287                 print_escaped_xml(pdata->fh, fi->hfinfo->abbrev);
288
289 #if 0
290         /* PDML spec, see: 
291          * http://analyzer.polito.it/30alpha/docs/dissectors/PDMLSpec.htm
292          *
293          * the show fields contains things in 'human readable' format
294          * showname: contains only the name of the field
295          * show: contains only the data of the field
296          * showdtl: contains additional details of the field data
297          * showmap: contains mappings of the field data (e.g. the hostname to an IP address)
298          *
299          * XXX - the showname shouldn't contain the field data itself 
300          * (like it's contained in the fi->rep->representation). 
301          * Unfortunately, we don't have the field data representation for 
302          * all fields, so this isn't currently possible */
303                 fputs("\" showname=\"", pdata->fh);
304                 print_escaped_xml(pdata->fh, fi->hfinfo->name);
305 #endif
306
307                 if (fi->rep) {
308                         fputs("\" showname=\"", pdata->fh);
309                         print_escaped_xml(pdata->fh, fi->rep->representation);
310                 }
311                 else {
312                         label_ptr = label_str;
313                         proto_item_fill_label(fi, label_str);
314                         fputs("\" showname=\"", pdata->fh);
315                         print_escaped_xml(pdata->fh, label_ptr);
316                 }
317
318                 if (PROTO_ITEM_IS_HIDDEN(node))
319                         fprintf(pdata->fh, "\" hide=\"yes");
320
321                 fprintf(pdata->fh, "\" size=\"%d", fi->length);
322                 fprintf(pdata->fh, "\" pos=\"%d", fi->start);
323 /*              fprintf(pdata->fh, "\" id=\"%d", fi->hfinfo->id);*/
324
325                 if (fi->hfinfo->type != FT_PROTOCOL) {
326                         /* Field */
327
328                         /* XXX - this is a hack until we can just call
329                          * fvalue_to_string_repr() for *all* FT_* types. */
330                         dfilter_string = proto_construct_dfilter_string(fi,
331                                         pdata->edt);
332                         if (dfilter_string != NULL) {
333                                 chop_len = strlen(fi->hfinfo->abbrev) + 4; /* for " == " */
334
335                                 /* XXX - Remove double-quotes. Again, once we
336                                  * can call fvalue_to_string_repr(), we can
337                                  * ask it not to produce the version for
338                                  * display-filters, and thus, no
339                                  * double-quotes. */
340                                 if (dfilter_string[strlen(dfilter_string)-1] == '"') {
341                                         dfilter_string[strlen(dfilter_string)-1] = '\0';
342                                         chop_len++;
343                                 }
344
345                                 fputs("\" show=\"", pdata->fh);
346                                 print_escaped_xml(pdata->fh, &dfilter_string[chop_len]);
347                         }
348                         if (fi->length > 0) {
349                                 fputs("\" value=\"", pdata->fh);
350
351                                 if (fi->hfinfo->bitmask!=0) {
352                                         fprintf(pdata->fh, "%X", fvalue_get_integer(&fi->value));
353                                         fputs("\" unmaskedvalue=\"", pdata->fh);
354                                         write_pdml_field_hex_value(pdata, fi);
355                                 }
356                                 else {
357                     write_pdml_field_hex_value(pdata, fi);
358                 }
359                         }
360                 }
361
362                 if (node->first_child != NULL) {
363                         fputs("\">\n", pdata->fh);
364                 }
365                 else if (fi->hfinfo->id == proto_data) {
366                         fputs("\">\n", pdata->fh);
367                 }
368                 else {
369                         fputs("\"/>\n", pdata->fh);
370                 }
371         }
372
373         /* We always print all levels for PDML. Recurse here. */
374         if (node->first_child != NULL) {
375                 pdata->level++;
376                 proto_tree_children_foreach(node,
377                                 proto_tree_write_node_pdml, pdata);
378                 pdata->level--;
379         }
380
381         if (node->first_child != NULL) {
382                 for (i = -1; i < pdata->level; i++) {
383                         fputs("  ", pdata->fh);
384                 }
385                 if (fi->hfinfo->type == FT_PROTOCOL) {
386                         fputs("</proto>\n", pdata->fh);
387                 }
388                 else {
389                         fputs("</field>\n", pdata->fh);
390                 }
391         }
392 }
393
394 /* Print info for a 'geninfo' pseudo-protocol. This is required by
395  * the PDML spec. The information is contained in Wireshark's 'frame' protocol,
396  * but we produce a 'geninfo' protocol in the PDML to conform to spec.
397  * The 'frame' protocol follows the 'geninfo' protocol in the PDML. */
398 static void
399 print_pdml_geninfo(proto_tree *tree, FILE *fh)
400 {
401         guint32 num, len, caplen;
402         nstime_t *timestamp;
403         GPtrArray *finfo_array;
404         field_info *frame_finfo;
405
406         /* Get frame protocol's finfo. */
407         finfo_array = proto_find_finfo(tree, proto_frame);
408         if (g_ptr_array_len(finfo_array) < 1) {
409                 return;
410         }
411         frame_finfo = finfo_array->pdata[0];
412         g_ptr_array_free(finfo_array, FALSE);
413
414         /* frame.number --> geninfo.num */
415         finfo_array = proto_find_finfo(tree, hf_frame_number);
416         if (g_ptr_array_len(finfo_array) < 1) {
417                 return;
418         }
419         num = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
420         g_ptr_array_free(finfo_array, FALSE);
421
422         /* frame.pkt_len --> geninfo.len */
423         finfo_array = proto_find_finfo(tree, hf_frame_packet_len);
424         if (g_ptr_array_len(finfo_array) < 1) {
425                 return;
426         }
427         len = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
428         g_ptr_array_free(finfo_array, FALSE);
429
430         /* frame.cap_len --> geninfo.caplen */
431         finfo_array = proto_find_finfo(tree, hf_frame_capture_len);
432         if (g_ptr_array_len(finfo_array) < 1) {
433                 return;
434         }
435         caplen = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
436         g_ptr_array_free(finfo_array, FALSE);
437
438         /* frame.time --> geninfo.timestamp */
439         finfo_array = proto_find_finfo(tree, hf_frame_arrival_time);
440         if (g_ptr_array_len(finfo_array) < 1) {
441                 return;
442         }
443         timestamp = fvalue_get(&((field_info*)finfo_array->pdata[0])->value);
444         g_ptr_array_free(finfo_array, FALSE);
445
446         /* Print geninfo start */
447         fprintf(fh,
448 "  <proto name=\"geninfo\" pos=\"0\" showname=\"General information\" size=\"%u\">\n",
449                 frame_finfo->length);
450
451         /* Print geninfo.num */
452         fprintf(fh,
453 "    <field name=\"num\" pos=\"0\" show=\"%u\" showname=\"Number\" value=\"%x\" size=\"%u\"/>\n",
454                 num, num, frame_finfo->length);
455
456         /* Print geninfo.len */
457         fprintf(fh,
458 "    <field name=\"len\" pos=\"0\" show=\"%u\" showname=\"Packet Length\" value=\"%x\" size=\"%u\"/>\n",
459                 len, len, frame_finfo->length);
460
461         /* Print geninfo.caplen */
462         fprintf(fh,
463 "    <field name=\"caplen\" pos=\"0\" show=\"%u\" showname=\"Captured Length\" value=\"%x\" size=\"%u\"/>\n",
464                 caplen, caplen, frame_finfo->length);
465
466         /* Print geninfo.timestamp */
467         fprintf(fh,
468 "    <field name=\"timestamp\" pos=\"0\" show=\"%s\" showname=\"Captured Time\" value=\"%d.%09d\" size=\"%u\"/>\n",
469                 abs_time_to_str(timestamp), (int) timestamp->secs, timestamp->nsecs, frame_finfo->length);
470
471         /* Print geninfo end */
472         fprintf(fh,
473 "  </proto>\n");
474 }
475
476 void
477 write_pdml_finale(FILE *fh)
478 {
479         fputs("</pdml>\n", fh);
480 }
481
482 void
483 write_psml_preamble(FILE *fh)
484 {
485         fputs("<?xml version=\"1.0\"?>\n", fh);
486         fputs("<psml version=\"" PSML_VERSION "\" ", fh);
487         fprintf(fh, "creator=\"%s/%s\">\n", PACKAGE, VERSION);
488 }
489
490 void
491 proto_tree_write_psml(epan_dissect_t *edt, FILE *fh)
492 {
493         gint    i;
494
495         /* if this is the first packet, we have to create the PSML structure output */
496         if(edt->pi.fd->num == 1) {
497             fprintf(fh, "<structure>\n");
498
499             for(i=0; i < edt->pi.cinfo->num_cols; i++) {
500                 fprintf(fh, "<section>");
501                 print_escaped_xml(fh, edt->pi.cinfo->col_title[i]);
502                 fprintf(fh, "</section>\n");
503             }
504
505             fprintf(fh, "</structure>\n\n");
506         }
507
508         fprintf(fh, "<packet>\n");
509
510         for(i=0; i < edt->pi.cinfo->num_cols; i++) {
511             fprintf(fh, "<section>");
512             print_escaped_xml(fh, edt->pi.cinfo->col_data[i]);
513             fprintf(fh, "</section>\n");
514         }
515
516         fprintf(fh, "</packet>\n\n");
517 }
518
519 void
520 write_psml_finale(FILE *fh)
521 {
522         fputs("</psml>\n", fh);
523 }
524
525 void
526 write_csv_preamble(FILE *fh _U_)
527 {
528
529 }
530
531 void
532 proto_tree_write_csv(epan_dissect_t *edt, FILE *fh)
533 {
534         gint    i;
535
536         /* if this is the first packet, we have to write the CSV header */
537         if(edt->pi.fd->num == 1) {
538             for(i=0; i < edt->pi.cinfo->num_cols - 1; i++)
539                 fprintf(fh, "\"%s\", ", edt->pi.cinfo->col_title[i]);
540
541             fprintf(fh, "\"%s\"\n", edt->pi.cinfo->col_title[i]);
542         }
543
544         for(i=0; i < edt->pi.cinfo->num_cols - 1; i++)
545             fprintf(fh, "\"%s\", ", edt->pi.cinfo->col_data[i]);
546
547         fprintf(fh, "\"%s\"\n", edt->pi.cinfo->col_data[i]);
548 }
549
550 void
551 write_csv_finale(FILE *fh _U_)
552 {
553
554 }
555
556 /*
557  * Find the data source for a specified field, and return a pointer
558  * to the data in it. Returns NULL if the data is out of bounds.
559  */
560 static const guint8 *
561 get_field_data(GSList *src_list, field_info *fi)
562 {
563         GSList *src_le;
564         data_source *src;
565         tvbuff_t *src_tvb;
566         gint length, tvbuff_length;
567
568         for (src_le = src_list; src_le != NULL; src_le = src_le->next) {
569                 src = src_le->data;
570                 src_tvb = src->tvb;
571                 if (fi->ds_tvb == src_tvb) {
572                         /*
573                          * Found it.
574                          *
575                          * XXX - a field can have a length that runs past
576                          * the end of the tvbuff.  Ideally, that should
577                          * be fixed when adding an item to the protocol
578                          * tree, but checking the length when doing
579                          * that could be expensive.  Until we fix that,
580                          * we'll do the check here.
581                          */
582                         tvbuff_length = tvb_length_remaining(src_tvb,
583                             fi->start);
584                         if (tvbuff_length < 0) {
585                                 return NULL;
586                         }
587                         length = fi->length;
588                         if (length > tvbuff_length)
589                                 length = tvbuff_length;
590                         return tvb_get_ptr(src_tvb, fi->start, length);
591                 }
592         }
593         g_assert_not_reached();
594         return NULL;    /* not found */
595 }
596
597 /* Print a string, escaping out certain characters that need to
598  * escaped out for XML. */
599 static void
600 print_escaped_xml(FILE *fh, const char *unescaped_string)
601 {
602         const unsigned char *p;
603
604         for (p = unescaped_string; *p != '\0'; p++) {
605                 switch (*p) {
606                         case '&':
607                                 fputs("&amp;", fh);
608                                 break;
609                         case '<':
610                                 fputs("&lt;", fh);
611                                 break;
612                         case '>':
613                                 fputs("&gt;", fh);
614                                 break;
615                         case '"':
616                                 fputs("&quot;", fh);
617                                 break;
618                         case '\'':
619                                 fputs("&apos;", fh);
620                                 break;
621                         default:
622                                 fputc(*p, fh);
623                 }
624         }
625 }
626
627 static void
628 write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi)
629 {
630         int i;
631         const guint8 *pd;
632
633         if (fi->length > tvb_length_remaining(fi->ds_tvb, fi->start)) {
634                 fprintf(pdata->fh, "field length invalid!");
635                 return;
636         }
637
638         /* Find the data for this field. */
639         pd = get_field_data(pdata->src_list, fi);
640
641         if (pd) {
642                 /* Print a simple hex dump */
643                 for (i = 0 ; i < fi->length; i++) {
644                         fprintf(pdata->fh, "%02x", pd[i]);
645                 }
646         }
647 }
648
649 gboolean
650 print_hex_data(print_stream_t *stream, epan_dissect_t *edt)
651 {
652         gboolean multiple_sources;
653         GSList *src_le;
654         data_source *src;
655         tvbuff_t *tvb;
656         char *name;
657         char *line;
658         const guchar *cp;
659         guint length;
660
661         /*
662          * Set "multiple_sources" iff this frame has more than one
663          * data source; if it does, we need to print the name of
664          * the data source before printing the data from the
665          * data source.
666          */
667         multiple_sources = (edt->pi.data_src->next != NULL);
668
669         for (src_le = edt->pi.data_src; src_le != NULL;
670             src_le = src_le->next) {
671                 src = src_le->data;
672                 tvb = src->tvb;
673                 if (multiple_sources) {
674                         name = src->name;
675                         print_line(stream, 0, "");
676                         line = g_malloc(strlen(name) + 2);      /* <name>:\0 */
677                         strcpy(line, name);
678                         strcat(line, ":");
679                         print_line(stream, 0, line);
680                         g_free(line);
681                 }
682                 length = tvb_length(tvb);
683                 if (length == 0)
684                     return TRUE;
685                 cp = tvb_get_ptr(tvb, 0, length);
686                 if (!print_hex_data_buffer(stream, cp, length,
687                     edt->pi.fd->flags.encoding))
688                         return FALSE;
689         }
690         return TRUE;
691 }
692
693 /*
694  * This routine is based on a routine created by Dan Lasley
695  * <DLASLEY@PROMUS.com>.
696  *
697  * It was modified for Wireshark by Gilbert Ramirez and others.
698  */
699
700 #define MAX_OFFSET_LEN  8       /* max length of hex offset of bytes */
701 #define BYTES_PER_LINE  16      /* max byte values printed on a line */
702 #define HEX_DUMP_LEN    (BYTES_PER_LINE*3)
703                                 /* max number of characters hex dump takes -
704                                    2 digits plus trailing blank */
705 #define DATA_DUMP_LEN   (HEX_DUMP_LEN + 2 + BYTES_PER_LINE)
706                                 /* number of characters those bytes take;
707                                    3 characters per byte of hex dump,
708                                    2 blanks separating hex from ASCII,
709                                    1 character per byte of ASCII dump */
710 #define MAX_LINE_LEN    (MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN)
711                                 /* number of characters per line;
712                                    offset, 2 blanks separating offset
713                                    from data dump, data dump */
714
715 static gboolean
716 print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
717     guint length, char_enc encoding)
718 {
719         register unsigned int ad, i, j, k, l;
720         guchar c;
721         guchar line[MAX_LINE_LEN + 1];
722         unsigned int use_digits;
723         static guchar binhex[16] = {
724                 '0', '1', '2', '3', '4', '5', '6', '7',
725                 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
726
727         if (!print_line(stream, 0, ""))
728                 return FALSE;
729
730         /*
731          * How many of the leading digits of the offset will we supply?
732          * We always supply at least 4 digits, but if the maximum offset
733          * won't fit in 4 digits, we use as many digits as will be needed.
734          */
735         if (((length - 1) & 0xF0000000) != 0)
736                 use_digits = 8; /* need all 8 digits */
737         else if (((length - 1) & 0x0F000000) != 0)
738                 use_digits = 7; /* need 7 digits */
739         else if (((length - 1) & 0x00F00000) != 0)
740                 use_digits = 6; /* need 6 digits */
741         else if (((length - 1) & 0x000F0000) != 0)
742                 use_digits = 5; /* need 5 digits */
743         else
744                 use_digits = 4; /* we'll supply 4 digits */
745
746         ad = 0;
747         i = 0;
748         j = 0;
749         k = 0;
750         while (i < length) {
751                 if ((i & 15) == 0) {
752                         /*
753                          * Start of a new line.
754                          */
755                         j = 0;
756                         k = 0;
757                         l = use_digits;
758                         do {
759                                 l--;
760                                 c = (ad >> (l*4)) & 0xF;
761                                 line[j++] = binhex[c];
762                         } while (l != 0);
763                         line[j++] = ' ';
764                         line[j++] = ' ';
765                         memset(line+j, ' ', DATA_DUMP_LEN);
766
767                         /*
768                          * Offset in line of ASCII dump.
769                          */
770                         k = j + HEX_DUMP_LEN + 2;
771                 }
772                 c = *cp++;
773                 line[j++] = binhex[c>>4];
774                 line[j++] = binhex[c&0xf];
775                 j++;
776                 if (encoding == CHAR_EBCDIC) {
777                         c = EBCDIC_to_ASCII1(c);
778                 }
779                 line[k++] = c >= ' ' && c < 0x7f ? c : '.';
780                 i++;
781                 if ((i & 15) == 0 || i == length) {
782                         /*
783                          * We'll be starting a new line, or
784                          * we're finished printing this buffer;
785                          * dump out the line we've constructed,
786                          * and advance the offset.
787                          */
788                         line[k] = '\0';
789                         if (!print_line(stream, 0, line))
790                                 return FALSE;
791                         ad += 16;
792                 }
793         }
794         return TRUE;
795 }
796
797 static
798 void ps_clean_string(unsigned char *out, const unsigned char *in,
799                         int outbuf_size)
800 {
801         int rd, wr;
802         char c;
803
804         for (rd = 0, wr = 0 ; wr < outbuf_size; rd++, wr++ ) {
805                 c = in[rd];
806                 switch (c) {
807                         case '(':
808                         case ')':
809                         case '\\':
810                                 out[wr] = '\\';
811                                 out[++wr] = c;
812                                 break;
813
814                         default:
815                                 out[wr] = c;
816                                 break;
817                 }
818
819                 if (c == 0) {
820                         break;
821                 }
822         }
823 }
824
825 /* Some formats need stuff at the beginning of the output */
826 gboolean
827 print_preamble(print_stream_t *self, gchar *filename)
828 {
829         return (self->ops->print_preamble)(self, filename);
830 }
831
832 gboolean
833 print_line(print_stream_t *self, int indent, const char *line)
834 {
835         return (self->ops->print_line)(self, indent, line);
836 }
837
838 /* Insert bookmark */
839 gboolean
840 print_bookmark(print_stream_t *self, const gchar *name, const gchar *title)
841 {
842         return (self->ops->print_bookmark)(self, name, title);
843 }
844
845 gboolean
846 new_page(print_stream_t *self)
847 {
848         return (self->ops->new_page)(self);
849 }
850
851 /* Some formats need stuff at the end of the output */
852 gboolean
853 print_finale(print_stream_t *self)
854 {
855         return (self->ops->print_finale)(self);
856 }
857
858 gboolean
859 destroy_print_stream(print_stream_t *self)
860 {
861         return (self->ops->destroy)(self);
862 }
863
864 typedef struct {
865         int to_file;
866         FILE *fh;
867 } output_text;
868
869 static gboolean
870 print_preamble_text(print_stream_t *self _U_, gchar *filename _U_)
871 {
872         /* do nothing */
873         return TRUE;    /* always succeeds */
874 }
875
876 static gboolean
877 print_line_text(print_stream_t *self, int indent, const char *line)
878 {
879         output_text *output = self->data;
880         char space[MAX_INDENT+1];
881         int i;
882         int num_spaces;
883
884         /* Prepare the tabs for printing, depending on tree level */
885         num_spaces = indent * 4;
886         if (num_spaces > MAX_INDENT) {
887                 num_spaces = MAX_INDENT;
888         }
889         for (i = 0; i < num_spaces; i++) {
890                 space[i] = ' ';
891         }
892         /* The string is NUL-terminated */
893         space[num_spaces] = '\0';
894
895         fputs(space, output->fh);
896         fputs(line, output->fh);
897         putc('\n', output->fh);
898         return !ferror(output->fh);
899 }
900
901 static gboolean
902 print_bookmark_text(print_stream_t *self _U_, const gchar *name _U_,
903     const gchar *title _U_)
904 {
905         /* do nothing */
906         return TRUE;
907 }
908
909 static gboolean
910 new_page_text(print_stream_t *self)
911 {
912         output_text *output = self->data;
913
914         fputs("\f", output->fh);
915         return !ferror(output->fh);
916 }
917
918 static gboolean
919 print_finale_text(print_stream_t *self _U_)
920 {
921         /* do nothing */
922         return TRUE;    /* always succeeds */
923 }
924
925 static gboolean
926 destroy_text(print_stream_t *self)
927 {
928         output_text *output = self->data;
929         gboolean ret;
930
931         ret = close_print_dest(output->to_file, output->fh);
932         g_free(output);
933         g_free(self);
934         return ret;
935 }
936
937 static const print_stream_ops_t print_text_ops = {
938         print_preamble_text,
939         print_line_text,
940         print_bookmark_text,
941         new_page_text,
942         print_finale_text,
943         destroy_text
944 };
945
946 print_stream_t *
947 print_stream_text_new(int to_file, const char *dest)
948 {
949         FILE *fh;
950         print_stream_t *stream;
951         output_text *output;
952
953         fh = open_print_dest(to_file, dest);
954         if (fh == NULL)
955                 return NULL;
956
957         output = g_malloc(sizeof *output);
958         output->to_file = to_file;
959         output->fh = fh;
960         stream = g_malloc(sizeof (print_stream_t));
961         stream->ops = &print_text_ops;
962         stream->data = output;
963
964         return stream;
965 }
966
967 print_stream_t *
968 print_stream_text_stdio_new(FILE *fh)
969 {
970         print_stream_t *stream;
971         output_text *output;
972
973         output = g_malloc(sizeof *output);
974         output->to_file = TRUE;
975         output->fh = fh;
976         stream = g_malloc(sizeof (print_stream_t));
977         stream->ops = &print_text_ops;
978         stream->data = output;
979
980         return stream;
981 }
982
983 typedef struct {
984         int to_file;
985         FILE *fh;
986 } output_ps;
987
988 static gboolean
989 print_preamble_ps(print_stream_t *self, gchar *filename)
990 {
991         output_ps *output = self->data;
992         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
993
994         print_ps_preamble(output->fh);
995
996         fputs("%% Set the font to 10 point\n", output->fh);
997         fputs("/Courier findfont 10 scalefont setfont\n", output->fh);
998         fputs("\n", output->fh);
999         fputs("%% the page title\n", output->fh);
1000         ps_clean_string(psbuffer, filename, MAX_PS_LINE_LENGTH);
1001         fprintf(output->fh, "/eth_pagetitle (%s - Wireshark) def\n", psbuffer);
1002         fputs("\n", output->fh);
1003         return !ferror(output->fh);
1004 }
1005
1006 static gboolean
1007 print_line_ps(print_stream_t *self, int indent, const char *line)
1008 {
1009         output_ps *output = self->data;
1010         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1011
1012         ps_clean_string(psbuffer, line, MAX_PS_LINE_LENGTH);
1013         fprintf(output->fh, "%d (%s) putline\n", indent, psbuffer);
1014         return !ferror(output->fh);
1015 }
1016
1017 static gboolean
1018 print_bookmark_ps(print_stream_t *self, const gchar *name, const gchar *title)
1019 {
1020         output_ps *output = self->data;
1021         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1022
1023         /*
1024          * See the Adobe "pdfmark reference":
1025          *
1026          *      http://partners.adobe.com/asn/acrobat/docs/pdfmark.pdf
1027          *
1028          * The pdfmark stuff tells code that turns PostScript into PDF
1029          * things that it should do.
1030          *
1031          * The /OUT stuff creates a bookmark that goes to the
1032          * destination with "name" as the name and "title" as the title.
1033          *
1034          * The "/DEST" creates the destination.
1035          */
1036         ps_clean_string(psbuffer, title, MAX_PS_LINE_LENGTH);
1037         fprintf(output->fh, "[/Dest /%s /Title (%s)   /OUT pdfmark\n", name,
1038             psbuffer);
1039         fputs("[/View [/XYZ -4 currentpoint matrix currentmatrix matrix defaultmatrix\n",
1040             output->fh);
1041         fputs("matrix invertmatrix matrix concatmatrix transform exch pop 20 add null]\n",
1042             output->fh);
1043         fprintf(output->fh, "/Dest /%s /DEST pdfmark\n", name);
1044         return !ferror(output->fh);
1045 }
1046
1047 static gboolean
1048 new_page_ps(print_stream_t *self)
1049 {
1050         output_ps *output = self->data;
1051
1052         fputs("formfeed\n", output->fh);
1053         return !ferror(output->fh);
1054 }
1055
1056 static gboolean
1057 print_finale_ps(print_stream_t *self)
1058 {
1059         output_ps *output = self->data;
1060
1061         print_ps_finale(output->fh);
1062         return !ferror(output->fh);
1063 }
1064
1065 static gboolean
1066 destroy_ps(print_stream_t *self)
1067 {
1068         output_ps *output = self->data;
1069         gboolean ret;
1070
1071         ret = close_print_dest(output->to_file, output->fh);
1072         g_free(output);
1073         g_free(self);
1074         return ret;
1075 }
1076
1077 static const print_stream_ops_t print_ps_ops = {
1078         print_preamble_ps,
1079         print_line_ps,
1080         print_bookmark_ps,
1081         new_page_ps,
1082         print_finale_ps,
1083         destroy_ps
1084 };
1085
1086 print_stream_t *
1087 print_stream_ps_new(int to_file, const char *dest)
1088 {
1089         FILE *fh;
1090         print_stream_t *stream;
1091         output_ps *output;
1092
1093         fh = open_print_dest(to_file, dest);
1094         if (fh == NULL)
1095                 return NULL;
1096
1097         output = g_malloc(sizeof *output);
1098         output->to_file = to_file;
1099         output->fh = fh;
1100         stream = g_malloc(sizeof (print_stream_t));
1101         stream->ops = &print_ps_ops;
1102         stream->data = output;
1103
1104         return stream;
1105 }
1106
1107 print_stream_t *
1108 print_stream_ps_stdio_new(FILE *fh)
1109 {
1110         print_stream_t *stream;
1111         output_ps *output;
1112
1113         output = g_malloc(sizeof *output);
1114         output->to_file = TRUE;
1115         output->fh = fh;
1116         stream = g_malloc(sizeof (print_stream_t));
1117         stream->ops = &print_ps_ops;
1118         stream->data = output;
1119
1120         return stream;
1121 }