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