I have to check this in with HHC enabled, otherwise I cannot get a chm file without...
[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         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                                 write_pdml_field_hex_value(pdata, fi);
350                         }
351                 }
352
353                 if (node->first_child != NULL) {
354                         fputs("\">\n", pdata->fh);
355                 }
356                 else if (fi->hfinfo->id == proto_data) {
357                         fputs("\">\n", pdata->fh);
358                 }
359                 else {
360                         fputs("\"/>\n", pdata->fh);
361                 }
362         }
363
364         /* We always print all levels for PDML. Recurse here. */
365         if (node->first_child != NULL) {
366                 pdata->level++;
367                 proto_tree_children_foreach(node,
368                                 proto_tree_write_node_pdml, pdata);
369                 pdata->level--;
370         }
371
372         if (node->first_child != NULL) {
373                 for (i = -1; i < pdata->level; i++) {
374                         fputs("  ", pdata->fh);
375                 }
376                 if (fi->hfinfo->type == FT_PROTOCOL) {
377                         fputs("</proto>\n", pdata->fh);
378                 }
379                 else {
380                         fputs("</field>\n", pdata->fh);
381                 }
382         }
383 }
384
385 /* Print info for a 'geninfo' pseudo-protocol. This is required by
386  * the PDML spec. The information is contained in Ethereal's 'frame' protocol,
387  * but we produce a 'geninfo' protocol in the PDML to conform to spec.
388  * The 'frame' protocol follows the 'geninfo' protocol in the PDML. */
389 static void
390 print_pdml_geninfo(proto_tree *tree, FILE *fh)
391 {
392         guint32 num, len, caplen;
393         nstime_t *timestamp;
394         GPtrArray *finfo_array;
395         field_info *frame_finfo;
396
397         /* Get frame protocol's finfo. */
398         finfo_array = proto_find_finfo(tree, proto_frame);
399         if (g_ptr_array_len(finfo_array) < 1) {
400                 return;
401         }
402         frame_finfo = finfo_array->pdata[0];
403         g_ptr_array_free(finfo_array, FALSE);
404
405         /* frame.number --> geninfo.num */
406         finfo_array = proto_find_finfo(tree, hf_frame_number);
407         if (g_ptr_array_len(finfo_array) < 1) {
408                 return;
409         }
410         num = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
411         g_ptr_array_free(finfo_array, FALSE);
412
413         /* frame.pkt_len --> geninfo.len */
414         finfo_array = proto_find_finfo(tree, hf_frame_packet_len);
415         if (g_ptr_array_len(finfo_array) < 1) {
416                 return;
417         }
418         len = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
419         g_ptr_array_free(finfo_array, FALSE);
420
421         /* frame.cap_len --> geninfo.caplen */
422         finfo_array = proto_find_finfo(tree, hf_frame_capture_len);
423         if (g_ptr_array_len(finfo_array) < 1) {
424                 return;
425         }
426         caplen = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
427         g_ptr_array_free(finfo_array, FALSE);
428
429         /* frame.time --> geninfo.timestamp */
430         finfo_array = proto_find_finfo(tree, hf_frame_arrival_time);
431         if (g_ptr_array_len(finfo_array) < 1) {
432                 return;
433         }
434         timestamp = fvalue_get(&((field_info*)finfo_array->pdata[0])->value);
435         g_ptr_array_free(finfo_array, FALSE);
436
437         /* Print geninfo start */
438         fprintf(fh,
439 "  <proto name=\"geninfo\" pos=\"0\" showname=\"General information\" size=\"%u\">\n",
440                 frame_finfo->length);
441
442         /* Print geninfo.num */
443         fprintf(fh,
444 "    <field name=\"num\" pos=\"0\" show=\"%u\" showname=\"Number\" value=\"%x\" size=\"%u\"/>\n",
445                 num, num, frame_finfo->length);
446
447         /* Print geninfo.len */
448         fprintf(fh,
449 "    <field name=\"len\" pos=\"0\" show=\"%u\" showname=\"Packet Length\" value=\"%x\" size=\"%u\"/>\n",
450                 len, len, frame_finfo->length);
451
452         /* Print geninfo.caplen */
453         fprintf(fh,
454 "    <field name=\"caplen\" pos=\"0\" show=\"%u\" showname=\"Captured Length\" value=\"%x\" size=\"%u\"/>\n",
455                 caplen, caplen, frame_finfo->length);
456
457         /* Print geninfo.timestamp */
458         fprintf(fh,
459 "    <field name=\"timestamp\" pos=\"0\" show=\"%s\" showname=\"Captured Time\" value=\"%d.%09d\" size=\"%u\"/>\n",
460                 abs_time_to_str(timestamp), (int) timestamp->secs, timestamp->nsecs, frame_finfo->length);
461
462         /* Print geninfo end */
463         fprintf(fh,
464 "  </proto>\n");
465 }
466
467 void
468 write_pdml_finale(FILE *fh)
469 {
470         fputs("</pdml>\n", fh);
471 }
472
473 void
474 write_psml_preamble(FILE *fh)
475 {
476         fputs("<?xml version=\"1.0\"?>\n", fh);
477         fputs("<psml version=\"" PSML_VERSION "\" ", fh);
478         fprintf(fh, "creator=\"%s/%s\">\n", PACKAGE, VERSION);
479 }
480
481 void
482 proto_tree_write_psml(epan_dissect_t *edt, FILE *fh)
483 {
484         gint    i;
485
486         /* if this is the first packet, we have to create the PSML structure output */
487         if(edt->pi.fd->num == 1) {
488             fprintf(fh, "<structure>\n");
489
490             for(i=0; i < edt->pi.cinfo->num_cols; i++) {
491                 fprintf(fh, "<section>");
492                 print_escaped_xml(fh, edt->pi.cinfo->col_title[i]);
493                 fprintf(fh, "</section>\n");
494             }
495
496             fprintf(fh, "</structure>\n\n");
497         }
498
499         fprintf(fh, "<packet>\n");
500
501         for(i=0; i < edt->pi.cinfo->num_cols; i++) {
502             fprintf(fh, "<section>");
503             print_escaped_xml(fh, edt->pi.cinfo->col_data[i]);
504             fprintf(fh, "</section>\n");
505         }
506
507         fprintf(fh, "</packet>\n\n");
508 }
509
510 void
511 write_psml_finale(FILE *fh)
512 {
513         fputs("</psml>\n", fh);
514 }
515
516 /*
517  * Find the data source for a specified field, and return a pointer
518  * to the data in it. Returns NULL if the data is out of bounds.
519  */
520 static const guint8 *
521 get_field_data(GSList *src_list, field_info *fi)
522 {
523         GSList *src_le;
524         data_source *src;
525         tvbuff_t *src_tvb;
526         gint length, tvbuff_length;
527
528         for (src_le = src_list; src_le != NULL; src_le = src_le->next) {
529                 src = src_le->data;
530                 src_tvb = src->tvb;
531                 if (fi->ds_tvb == src_tvb) {
532                         /*
533                          * Found it.
534                          *
535                          * XXX - a field can have a length that runs past
536                          * the end of the tvbuff.  Ideally, that should
537                          * be fixed when adding an item to the protocol
538                          * tree, but checking the length when doing
539                          * that could be expensive.  Until we fix that,
540                          * we'll do the check here.
541                          */
542                         tvbuff_length = tvb_length_remaining(src_tvb,
543                             fi->start);
544                         if (tvbuff_length < 0) {
545                                 return NULL;
546                         }
547                         length = fi->length;
548                         if (length > tvbuff_length)
549                                 length = tvbuff_length;
550                         return tvb_get_ptr(src_tvb, fi->start, length);
551                 }
552         }
553         g_assert_not_reached();
554         return NULL;    /* not found */
555 }
556
557 /* Print a string, escaping out certain characters that need to
558  * escaped out for XML. */
559 static void
560 print_escaped_xml(FILE *fh, const char *unescaped_string)
561 {
562         const unsigned char *p;
563
564         for (p = unescaped_string; *p != '\0'; p++) {
565                 switch (*p) {
566                         case '&':
567                                 fputs("&amp;", fh);
568                                 break;
569                         case '<':
570                                 fputs("&lt;", fh);
571                                 break;
572                         case '>':
573                                 fputs("&gt;", fh);
574                                 break;
575                         case '"':
576                                 fputs("&quot;", fh);
577                                 break;
578                         case '\'':
579                                 fputs("&apos;", fh);
580                                 break;
581                         default:
582                                 fputc(*p, fh);
583                 }
584         }
585 }
586
587 static void
588 write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi)
589 {
590         int i;
591         const guint8 *pd;
592
593         if (fi->length > tvb_length_remaining(fi->ds_tvb, fi->start)) {
594                 fprintf(pdata->fh, "field length invalid!");
595                 return;
596         }
597
598         /* Find the data for this field. */
599         pd = get_field_data(pdata->src_list, fi);
600
601         if (pd) {
602                 /* Print a simple hex dump */
603                 for (i = 0 ; i < fi->length; i++) {
604                         fprintf(pdata->fh, "%02x", pd[i]);
605                 }
606         }
607 }
608
609 gboolean
610 print_hex_data(print_stream_t *stream, epan_dissect_t *edt)
611 {
612         gboolean multiple_sources;
613         GSList *src_le;
614         data_source *src;
615         tvbuff_t *tvb;
616         char *name;
617         char *line;
618         const guchar *cp;
619         guint length;
620
621         /*
622          * Set "multiple_sources" iff this frame has more than one
623          * data source; if it does, we need to print the name of
624          * the data source before printing the data from the
625          * data source.
626          */
627         multiple_sources = (edt->pi.data_src->next != NULL);
628
629         for (src_le = edt->pi.data_src; src_le != NULL;
630             src_le = src_le->next) {
631                 src = src_le->data;
632                 tvb = src->tvb;
633                 if (multiple_sources) {
634                         name = src->name;
635                         print_line(stream, 0, "");
636                         line = g_malloc(strlen(name) + 2);      /* <name>:\0 */
637                         strcpy(line, name);
638                         strcat(line, ":");
639                         print_line(stream, 0, line);
640                         g_free(line);
641                 }
642                 length = tvb_length(tvb);
643                 cp = tvb_get_ptr(tvb, 0, length);
644                 if (!print_hex_data_buffer(stream, cp, length,
645                     edt->pi.fd->flags.encoding))
646                         return FALSE;
647         }
648         return TRUE;
649 }
650
651 /*
652  * This routine is based on a routine created by Dan Lasley
653  * <DLASLEY@PROMUS.com>.
654  *
655  * It was modified for Ethereal by Gilbert Ramirez and others.
656  */
657
658 #define MAX_OFFSET_LEN  8       /* max length of hex offset of bytes */
659 #define BYTES_PER_LINE  16      /* max byte values printed on a line */
660 #define HEX_DUMP_LEN    (BYTES_PER_LINE*3)
661                                 /* max number of characters hex dump takes -
662                                    2 digits plus trailing blank */
663 #define DATA_DUMP_LEN   (HEX_DUMP_LEN + 2 + BYTES_PER_LINE)
664                                 /* number of characters those bytes take;
665                                    3 characters per byte of hex dump,
666                                    2 blanks separating hex from ASCII,
667                                    1 character per byte of ASCII dump */
668 #define MAX_LINE_LEN    (MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN)
669                                 /* number of characters per line;
670                                    offset, 2 blanks separating offset
671                                    from data dump, data dump */
672
673 static gboolean
674 print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
675     guint length, char_enc encoding)
676 {
677         register unsigned int ad, i, j, k, l;
678         guchar c;
679         guchar line[MAX_LINE_LEN + 1];
680         unsigned int use_digits;
681         static guchar binhex[16] = {
682                 '0', '1', '2', '3', '4', '5', '6', '7',
683                 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
684
685         if (!print_line(stream, 0, ""))
686                 return FALSE;
687
688         /*
689          * How many of the leading digits of the offset will we supply?
690          * We always supply at least 4 digits, but if the maximum offset
691          * won't fit in 4 digits, we use as many digits as will be needed.
692          */
693         if (((length - 1) & 0xF0000000) != 0)
694                 use_digits = 8; /* need all 8 digits */
695         else if (((length - 1) & 0x0F000000) != 0)
696                 use_digits = 7; /* need 7 digits */
697         else if (((length - 1) & 0x00F00000) != 0)
698                 use_digits = 6; /* need 6 digits */
699         else if (((length - 1) & 0x000F0000) != 0)
700                 use_digits = 5; /* need 5 digits */
701         else
702                 use_digits = 4; /* we'll supply 4 digits */
703
704         ad = 0;
705         i = 0;
706         j = 0;
707         k = 0;
708         while (i < length) {
709                 if ((i & 15) == 0) {
710                         /*
711                          * Start of a new line.
712                          */
713                         j = 0;
714                         k = 0;
715                         l = use_digits;
716                         do {
717                                 l--;
718                                 c = (ad >> (l*4)) & 0xF;
719                                 line[j++] = binhex[c];
720                         } while (l != 0);
721                         line[j++] = ' ';
722                         line[j++] = ' ';
723                         memset(line+j, ' ', DATA_DUMP_LEN);
724
725                         /*
726                          * Offset in line of ASCII dump.
727                          */
728                         k = j + HEX_DUMP_LEN + 2;
729                 }
730                 c = *cp++;
731                 line[j++] = binhex[c>>4];
732                 line[j++] = binhex[c&0xf];
733                 j++;
734                 if (encoding == CHAR_EBCDIC) {
735                         c = EBCDIC_to_ASCII1(c);
736                 }
737                 line[k++] = c >= ' ' && c < 0x7f ? c : '.';
738                 i++;
739                 if ((i & 15) == 0 || i == length) {
740                         /*
741                          * We'll be starting a new line, or
742                          * we're finished printing this buffer;
743                          * dump out the line we've constructed,
744                          * and advance the offset.
745                          */
746                         line[k] = '\0';
747                         if (!print_line(stream, 0, line))
748                                 return FALSE;
749                         ad += 16;
750                 }
751         }
752         return TRUE;
753 }
754
755 static
756 void ps_clean_string(unsigned char *out, const unsigned char *in,
757                         int outbuf_size)
758 {
759         int rd, wr;
760         char c;
761
762         for (rd = 0, wr = 0 ; wr < outbuf_size; rd++, wr++ ) {
763                 c = in[rd];
764                 switch (c) {
765                         case '(':
766                         case ')':
767                         case '\\':
768                                 out[wr] = '\\';
769                                 out[++wr] = c;
770                                 break;
771
772                         default:
773                                 out[wr] = c;
774                                 break;
775                 }
776
777                 if (c == 0) {
778                         break;
779                 }
780         }
781 }
782
783 /* Some formats need stuff at the beginning of the output */
784 gboolean
785 print_preamble(print_stream_t *self, gchar *filename)
786 {
787         return (self->ops->print_preamble)(self, filename);
788 }
789
790 gboolean
791 print_line(print_stream_t *self, int indent, const char *line)
792 {
793         return (self->ops->print_line)(self, indent, line);
794 }
795
796 /* Insert bookmark */
797 gboolean
798 print_bookmark(print_stream_t *self, const gchar *name, const gchar *title)
799 {
800         return (self->ops->print_bookmark)(self, name, title);
801 }
802
803 gboolean
804 new_page(print_stream_t *self)
805 {
806         return (self->ops->new_page)(self);
807 }
808
809 /* Some formats need stuff at the end of the output */
810 gboolean
811 print_finale(print_stream_t *self)
812 {
813         return (self->ops->print_finale)(self);
814 }
815
816 gboolean
817 destroy_print_stream(print_stream_t *self)
818 {
819         return (self->ops->destroy)(self);
820 }
821
822 typedef struct {
823         int to_file;
824         FILE *fh;
825 } output_text;
826
827 static gboolean
828 print_preamble_text(print_stream_t *self _U_, gchar *filename _U_)
829 {
830         /* do nothing */
831         return TRUE;    /* always succeeds */
832 }
833
834 static gboolean
835 print_line_text(print_stream_t *self, int indent, const char *line)
836 {
837         output_text *output = self->data;
838         char space[MAX_INDENT+1];
839         int i;
840         int num_spaces;
841
842         /* Prepare the tabs for printing, depending on tree level */
843         num_spaces = indent * 4;
844         if (num_spaces > MAX_INDENT) {
845                 num_spaces = MAX_INDENT;
846         }
847         for (i = 0; i < num_spaces; i++) {
848                 space[i] = ' ';
849         }
850         /* The string is NUL-terminated */
851         space[num_spaces] = '\0';
852
853         fputs(space, output->fh);
854         fputs(line, output->fh);
855         putc('\n', output->fh);
856         return !ferror(output->fh);
857 }
858
859 static gboolean
860 print_bookmark_text(print_stream_t *self _U_, const gchar *name _U_,
861     const gchar *title _U_)
862 {
863         /* do nothing */
864         return TRUE;
865 }
866
867 static gboolean
868 new_page_text(print_stream_t *self)
869 {
870         output_text *output = self->data;
871
872         fputs("\f", output->fh);
873         return !ferror(output->fh);
874 }
875
876 static gboolean
877 print_finale_text(print_stream_t *self _U_)
878 {
879         /* do nothing */
880         return TRUE;    /* always succeeds */
881 }
882
883 static gboolean
884 destroy_text(print_stream_t *self)
885 {
886         output_text *output = self->data;
887         gboolean ret;
888
889         ret = close_print_dest(output->to_file, output->fh);
890         g_free(output);
891         g_free(self);
892         return ret;
893 }
894
895 static const print_stream_ops_t print_text_ops = {
896         print_preamble_text,
897         print_line_text,
898         print_bookmark_text,
899         new_page_text,
900         print_finale_text,
901         destroy_text
902 };
903
904 print_stream_t *
905 print_stream_text_new(int to_file, const char *dest)
906 {
907         FILE *fh;
908         print_stream_t *stream;
909         output_text *output;
910
911         fh = open_print_dest(to_file, dest);
912         if (fh == NULL)
913                 return NULL;
914
915         output = g_malloc(sizeof *output);
916         output->to_file = to_file;
917         output->fh = fh;
918         stream = g_malloc(sizeof (print_stream_t));
919         stream->ops = &print_text_ops;
920         stream->data = output;
921
922         return stream;
923 }
924
925 print_stream_t *
926 print_stream_text_stdio_new(FILE *fh)
927 {
928         print_stream_t *stream;
929         output_text *output;
930
931         output = g_malloc(sizeof *output);
932         output->to_file = TRUE;
933         output->fh = fh;
934         stream = g_malloc(sizeof (print_stream_t));
935         stream->ops = &print_text_ops;
936         stream->data = output;
937
938         return stream;
939 }
940
941 typedef struct {
942         int to_file;
943         FILE *fh;
944 } output_ps;
945
946 static gboolean
947 print_preamble_ps(print_stream_t *self, gchar *filename)
948 {
949         output_ps *output = self->data;
950         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
951
952         print_ps_preamble(output->fh);
953
954         fputs("%% Set the font to 10 point\n", output->fh);
955         fputs("/Courier findfont 10 scalefont setfont\n", output->fh);
956         fputs("\n", output->fh);
957         fputs("%% the page title\n", output->fh);
958         ps_clean_string(psbuffer, filename, MAX_PS_LINE_LENGTH);
959         fprintf(output->fh, "/eth_pagetitle (%s - Ethereal) def\n", psbuffer);
960         fputs("\n", output->fh);
961         return !ferror(output->fh);
962 }
963
964 static gboolean
965 print_line_ps(print_stream_t *self, int indent, const char *line)
966 {
967         output_ps *output = self->data;
968         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
969
970         ps_clean_string(psbuffer, line, MAX_PS_LINE_LENGTH);
971         fprintf(output->fh, "%d (%s) putline\n", indent, psbuffer);
972         return !ferror(output->fh);
973 }
974
975 static gboolean
976 print_bookmark_ps(print_stream_t *self, const gchar *name, const gchar *title)
977 {
978         output_ps *output = self->data;
979         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
980
981         /*
982          * See the Adobe "pdfmark reference":
983          *
984          *      http://partners.adobe.com/asn/acrobat/docs/pdfmark.pdf
985          *
986          * The pdfmark stuff tells code that turns PostScript into PDF
987          * things that it should do.
988          *
989          * The /OUT stuff creates a bookmark that goes to the
990          * destination with "name" as the name and "title" as the title.
991          *
992          * The "/DEST" creates the destination.
993          */
994         ps_clean_string(psbuffer, title, MAX_PS_LINE_LENGTH);
995         fprintf(output->fh, "[/Dest /%s /Title (%s)   /OUT pdfmark\n", name,
996             psbuffer);
997         fputs("[/View [/XYZ -4 currentpoint matrix currentmatrix matrix defaultmatrix\n",
998             output->fh);
999         fputs("matrix invertmatrix matrix concatmatrix transform exch pop 20 add null]\n",
1000             output->fh);
1001         fprintf(output->fh, "/Dest /%s /DEST pdfmark\n", name);
1002         return !ferror(output->fh);
1003 }
1004
1005 static gboolean
1006 new_page_ps(print_stream_t *self)
1007 {
1008         output_ps *output = self->data;
1009
1010         fputs("formfeed\n", output->fh);
1011         return !ferror(output->fh);
1012 }
1013
1014 static gboolean
1015 print_finale_ps(print_stream_t *self)
1016 {
1017         output_ps *output = self->data;
1018
1019         print_ps_finale(output->fh);
1020         return !ferror(output->fh);
1021 }
1022
1023 static gboolean
1024 destroy_ps(print_stream_t *self)
1025 {
1026         output_ps *output = self->data;
1027         gboolean ret;
1028
1029         ret = close_print_dest(output->to_file, output->fh);
1030         g_free(output);
1031         g_free(self);
1032         return ret;
1033 }
1034
1035 static const print_stream_ops_t print_ps_ops = {
1036         print_preamble_ps,
1037         print_line_ps,
1038         print_bookmark_ps,
1039         new_page_ps,
1040         print_finale_ps,
1041         destroy_ps
1042 };
1043
1044 print_stream_t *
1045 print_stream_ps_new(int to_file, const char *dest)
1046 {
1047         FILE *fh;
1048         print_stream_t *stream;
1049         output_ps *output;
1050
1051         fh = open_print_dest(to_file, dest);
1052         if (fh == NULL)
1053                 return NULL;
1054
1055         output = g_malloc(sizeof *output);
1056         output->to_file = to_file;
1057         output->fh = fh;
1058         stream = g_malloc(sizeof (print_stream_t));
1059         stream->ops = &print_ps_ops;
1060         stream->data = output;
1061
1062         return stream;
1063 }
1064
1065 print_stream_t *
1066 print_stream_ps_stdio_new(FILE *fh)
1067 {
1068         print_stream_t *stream;
1069         output_ps *output;
1070
1071         output = g_malloc(sizeof *output);
1072         output->to_file = TRUE;
1073         output->fh = fh;
1074         stream = g_malloc(sizeof (print_stream_t));
1075         stream->ops = &print_ps_ops;
1076         stream->data = output;
1077
1078         return stream;
1079 }