More warining fixes: char -> const char
[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
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                 cp = tvb_get_ptr(tvb, 0, length);
683                 if (!print_hex_data_buffer(stream, cp, length,
684                     edt->pi.fd->flags.encoding))
685                         return FALSE;
686         }
687         return TRUE;
688 }
689
690 /*
691  * This routine is based on a routine created by Dan Lasley
692  * <DLASLEY@PROMUS.com>.
693  *
694  * It was modified for Ethereal by Gilbert Ramirez and others.
695  */
696
697 #define MAX_OFFSET_LEN  8       /* max length of hex offset of bytes */
698 #define BYTES_PER_LINE  16      /* max byte values printed on a line */
699 #define HEX_DUMP_LEN    (BYTES_PER_LINE*3)
700                                 /* max number of characters hex dump takes -
701                                    2 digits plus trailing blank */
702 #define DATA_DUMP_LEN   (HEX_DUMP_LEN + 2 + BYTES_PER_LINE)
703                                 /* number of characters those bytes take;
704                                    3 characters per byte of hex dump,
705                                    2 blanks separating hex from ASCII,
706                                    1 character per byte of ASCII dump */
707 #define MAX_LINE_LEN    (MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN)
708                                 /* number of characters per line;
709                                    offset, 2 blanks separating offset
710                                    from data dump, data dump */
711
712 static gboolean
713 print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
714     guint length, char_enc encoding)
715 {
716         register unsigned int ad, i, j, k, l;
717         guchar c;
718         guchar line[MAX_LINE_LEN + 1];
719         unsigned int use_digits;
720         static guchar binhex[16] = {
721                 '0', '1', '2', '3', '4', '5', '6', '7',
722                 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
723
724         if (!print_line(stream, 0, ""))
725                 return FALSE;
726
727         /*
728          * How many of the leading digits of the offset will we supply?
729          * We always supply at least 4 digits, but if the maximum offset
730          * won't fit in 4 digits, we use as many digits as will be needed.
731          */
732         if (((length - 1) & 0xF0000000) != 0)
733                 use_digits = 8; /* need all 8 digits */
734         else if (((length - 1) & 0x0F000000) != 0)
735                 use_digits = 7; /* need 7 digits */
736         else if (((length - 1) & 0x00F00000) != 0)
737                 use_digits = 6; /* need 6 digits */
738         else if (((length - 1) & 0x000F0000) != 0)
739                 use_digits = 5; /* need 5 digits */
740         else
741                 use_digits = 4; /* we'll supply 4 digits */
742
743         ad = 0;
744         i = 0;
745         j = 0;
746         k = 0;
747         while (i < length) {
748                 if ((i & 15) == 0) {
749                         /*
750                          * Start of a new line.
751                          */
752                         j = 0;
753                         k = 0;
754                         l = use_digits;
755                         do {
756                                 l--;
757                                 c = (ad >> (l*4)) & 0xF;
758                                 line[j++] = binhex[c];
759                         } while (l != 0);
760                         line[j++] = ' ';
761                         line[j++] = ' ';
762                         memset(line+j, ' ', DATA_DUMP_LEN);
763
764                         /*
765                          * Offset in line of ASCII dump.
766                          */
767                         k = j + HEX_DUMP_LEN + 2;
768                 }
769                 c = *cp++;
770                 line[j++] = binhex[c>>4];
771                 line[j++] = binhex[c&0xf];
772                 j++;
773                 if (encoding == CHAR_EBCDIC) {
774                         c = EBCDIC_to_ASCII1(c);
775                 }
776                 line[k++] = c >= ' ' && c < 0x7f ? c : '.';
777                 i++;
778                 if ((i & 15) == 0 || i == length) {
779                         /*
780                          * We'll be starting a new line, or
781                          * we're finished printing this buffer;
782                          * dump out the line we've constructed,
783                          * and advance the offset.
784                          */
785                         line[k] = '\0';
786                         if (!print_line(stream, 0, line))
787                                 return FALSE;
788                         ad += 16;
789                 }
790         }
791         return TRUE;
792 }
793
794 static
795 void ps_clean_string(unsigned char *out, const unsigned char *in,
796                         int outbuf_size)
797 {
798         int rd, wr;
799         char c;
800
801         for (rd = 0, wr = 0 ; wr < outbuf_size; rd++, wr++ ) {
802                 c = in[rd];
803                 switch (c) {
804                         case '(':
805                         case ')':
806                         case '\\':
807                                 out[wr] = '\\';
808                                 out[++wr] = c;
809                                 break;
810
811                         default:
812                                 out[wr] = c;
813                                 break;
814                 }
815
816                 if (c == 0) {
817                         break;
818                 }
819         }
820 }
821
822 /* Some formats need stuff at the beginning of the output */
823 gboolean
824 print_preamble(print_stream_t *self, gchar *filename)
825 {
826         return (self->ops->print_preamble)(self, filename);
827 }
828
829 gboolean
830 print_line(print_stream_t *self, int indent, const char *line)
831 {
832         return (self->ops->print_line)(self, indent, line);
833 }
834
835 /* Insert bookmark */
836 gboolean
837 print_bookmark(print_stream_t *self, const gchar *name, const gchar *title)
838 {
839         return (self->ops->print_bookmark)(self, name, title);
840 }
841
842 gboolean
843 new_page(print_stream_t *self)
844 {
845         return (self->ops->new_page)(self);
846 }
847
848 /* Some formats need stuff at the end of the output */
849 gboolean
850 print_finale(print_stream_t *self)
851 {
852         return (self->ops->print_finale)(self);
853 }
854
855 gboolean
856 destroy_print_stream(print_stream_t *self)
857 {
858         return (self->ops->destroy)(self);
859 }
860
861 typedef struct {
862         int to_file;
863         FILE *fh;
864 } output_text;
865
866 static gboolean
867 print_preamble_text(print_stream_t *self _U_, gchar *filename _U_)
868 {
869         /* do nothing */
870         return TRUE;    /* always succeeds */
871 }
872
873 static gboolean
874 print_line_text(print_stream_t *self, int indent, const char *line)
875 {
876         output_text *output = self->data;
877         char space[MAX_INDENT+1];
878         int i;
879         int num_spaces;
880
881         /* Prepare the tabs for printing, depending on tree level */
882         num_spaces = indent * 4;
883         if (num_spaces > MAX_INDENT) {
884                 num_spaces = MAX_INDENT;
885         }
886         for (i = 0; i < num_spaces; i++) {
887                 space[i] = ' ';
888         }
889         /* The string is NUL-terminated */
890         space[num_spaces] = '\0';
891
892         fputs(space, output->fh);
893         fputs(line, output->fh);
894         putc('\n', output->fh);
895         return !ferror(output->fh);
896 }
897
898 static gboolean
899 print_bookmark_text(print_stream_t *self _U_, const gchar *name _U_,
900     const gchar *title _U_)
901 {
902         /* do nothing */
903         return TRUE;
904 }
905
906 static gboolean
907 new_page_text(print_stream_t *self)
908 {
909         output_text *output = self->data;
910
911         fputs("\f", output->fh);
912         return !ferror(output->fh);
913 }
914
915 static gboolean
916 print_finale_text(print_stream_t *self _U_)
917 {
918         /* do nothing */
919         return TRUE;    /* always succeeds */
920 }
921
922 static gboolean
923 destroy_text(print_stream_t *self)
924 {
925         output_text *output = self->data;
926         gboolean ret;
927
928         ret = close_print_dest(output->to_file, output->fh);
929         g_free(output);
930         g_free(self);
931         return ret;
932 }
933
934 static const print_stream_ops_t print_text_ops = {
935         print_preamble_text,
936         print_line_text,
937         print_bookmark_text,
938         new_page_text,
939         print_finale_text,
940         destroy_text
941 };
942
943 print_stream_t *
944 print_stream_text_new(int to_file, const char *dest)
945 {
946         FILE *fh;
947         print_stream_t *stream;
948         output_text *output;
949
950         fh = open_print_dest(to_file, dest);
951         if (fh == NULL)
952                 return NULL;
953
954         output = g_malloc(sizeof *output);
955         output->to_file = to_file;
956         output->fh = fh;
957         stream = g_malloc(sizeof (print_stream_t));
958         stream->ops = &print_text_ops;
959         stream->data = output;
960
961         return stream;
962 }
963
964 print_stream_t *
965 print_stream_text_stdio_new(FILE *fh)
966 {
967         print_stream_t *stream;
968         output_text *output;
969
970         output = g_malloc(sizeof *output);
971         output->to_file = TRUE;
972         output->fh = fh;
973         stream = g_malloc(sizeof (print_stream_t));
974         stream->ops = &print_text_ops;
975         stream->data = output;
976
977         return stream;
978 }
979
980 typedef struct {
981         int to_file;
982         FILE *fh;
983 } output_ps;
984
985 static gboolean
986 print_preamble_ps(print_stream_t *self, gchar *filename)
987 {
988         output_ps *output = self->data;
989         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
990
991         print_ps_preamble(output->fh);
992
993         fputs("%% Set the font to 10 point\n", output->fh);
994         fputs("/Courier findfont 10 scalefont setfont\n", output->fh);
995         fputs("\n", output->fh);
996         fputs("%% the page title\n", output->fh);
997         ps_clean_string(psbuffer, filename, MAX_PS_LINE_LENGTH);
998         fprintf(output->fh, "/eth_pagetitle (%s - Ethereal) def\n", psbuffer);
999         fputs("\n", output->fh);
1000         return !ferror(output->fh);
1001 }
1002
1003 static gboolean
1004 print_line_ps(print_stream_t *self, int indent, const char *line)
1005 {
1006         output_ps *output = self->data;
1007         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1008
1009         ps_clean_string(psbuffer, line, MAX_PS_LINE_LENGTH);
1010         fprintf(output->fh, "%d (%s) putline\n", indent, psbuffer);
1011         return !ferror(output->fh);
1012 }
1013
1014 static gboolean
1015 print_bookmark_ps(print_stream_t *self, const gchar *name, const gchar *title)
1016 {
1017         output_ps *output = self->data;
1018         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1019
1020         /*
1021          * See the Adobe "pdfmark reference":
1022          *
1023          *      http://partners.adobe.com/asn/acrobat/docs/pdfmark.pdf
1024          *
1025          * The pdfmark stuff tells code that turns PostScript into PDF
1026          * things that it should do.
1027          *
1028          * The /OUT stuff creates a bookmark that goes to the
1029          * destination with "name" as the name and "title" as the title.
1030          *
1031          * The "/DEST" creates the destination.
1032          */
1033         ps_clean_string(psbuffer, title, MAX_PS_LINE_LENGTH);
1034         fprintf(output->fh, "[/Dest /%s /Title (%s)   /OUT pdfmark\n", name,
1035             psbuffer);
1036         fputs("[/View [/XYZ -4 currentpoint matrix currentmatrix matrix defaultmatrix\n",
1037             output->fh);
1038         fputs("matrix invertmatrix matrix concatmatrix transform exch pop 20 add null]\n",
1039             output->fh);
1040         fprintf(output->fh, "/Dest /%s /DEST pdfmark\n", name);
1041         return !ferror(output->fh);
1042 }
1043
1044 static gboolean
1045 new_page_ps(print_stream_t *self)
1046 {
1047         output_ps *output = self->data;
1048
1049         fputs("formfeed\n", output->fh);
1050         return !ferror(output->fh);
1051 }
1052
1053 static gboolean
1054 print_finale_ps(print_stream_t *self)
1055 {
1056         output_ps *output = self->data;
1057
1058         print_ps_finale(output->fh);
1059         return !ferror(output->fh);
1060 }
1061
1062 static gboolean
1063 destroy_ps(print_stream_t *self)
1064 {
1065         output_ps *output = self->data;
1066         gboolean ret;
1067
1068         ret = close_print_dest(output->to_file, output->fh);
1069         g_free(output);
1070         g_free(self);
1071         return ret;
1072 }
1073
1074 static const print_stream_ops_t print_ps_ops = {
1075         print_preamble_ps,
1076         print_line_ps,
1077         print_bookmark_ps,
1078         new_page_ps,
1079         print_finale_ps,
1080         destroy_ps
1081 };
1082
1083 print_stream_t *
1084 print_stream_ps_new(int to_file, const char *dest)
1085 {
1086         FILE *fh;
1087         print_stream_t *stream;
1088         output_ps *output;
1089
1090         fh = open_print_dest(to_file, dest);
1091         if (fh == NULL)
1092                 return NULL;
1093
1094         output = g_malloc(sizeof *output);
1095         output->to_file = to_file;
1096         output->fh = fh;
1097         stream = g_malloc(sizeof (print_stream_t));
1098         stream->ops = &print_ps_ops;
1099         stream->data = output;
1100
1101         return stream;
1102 }
1103
1104 print_stream_t *
1105 print_stream_ps_stdio_new(FILE *fh)
1106 {
1107         print_stream_t *stream;
1108         output_ps *output;
1109
1110         output = g_malloc(sizeof *output);
1111         output->to_file = TRUE;
1112         output->fh = fh;
1113         stream = g_malloc(sizeof (print_stream_t));
1114         stream->ops = &print_ps_ops;
1115         stream->data = output;
1116
1117         return stream;
1118 }