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