Add support for DUA dissection. Now all SIGTRAN protocols are supported...
[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 void
517 write_csv_preamble(FILE *fh _U_)
518 {
519
520 }
521
522 void
523 proto_tree_write_csv(epan_dissect_t *edt, FILE *fh)
524 {
525         gint    i;
526
527         /* if this is the first packet, we have to write the CSV header */
528         if(edt->pi.fd->num == 1) {
529             for(i=0; i < edt->pi.cinfo->num_cols - 1; i++)
530                 fprintf(fh, "\"%s\", ", edt->pi.cinfo->col_title[i]);
531
532             fprintf(fh, "\"%s\"\n", edt->pi.cinfo->col_title[i]);
533         }
534
535         for(i=0; i < edt->pi.cinfo->num_cols - 1; i++)
536             fprintf(fh, "\"%s\", ", edt->pi.cinfo->col_data[i]);
537
538         fprintf(fh, "\"%s\"\n", edt->pi.cinfo->col_data[i]);
539 }
540
541 void
542 write_csv_finale(FILE *fh _U_)
543 {
544
545 }
546
547 /*
548  * Find the data source for a specified field, and return a pointer
549  * to the data in it. Returns NULL if the data is out of bounds.
550  */
551 static const guint8 *
552 get_field_data(GSList *src_list, field_info *fi)
553 {
554         GSList *src_le;
555         data_source *src;
556         tvbuff_t *src_tvb;
557         gint length, tvbuff_length;
558
559         for (src_le = src_list; src_le != NULL; src_le = src_le->next) {
560                 src = src_le->data;
561                 src_tvb = src->tvb;
562                 if (fi->ds_tvb == src_tvb) {
563                         /*
564                          * Found it.
565                          *
566                          * XXX - a field can have a length that runs past
567                          * the end of the tvbuff.  Ideally, that should
568                          * be fixed when adding an item to the protocol
569                          * tree, but checking the length when doing
570                          * that could be expensive.  Until we fix that,
571                          * we'll do the check here.
572                          */
573                         tvbuff_length = tvb_length_remaining(src_tvb,
574                             fi->start);
575                         if (tvbuff_length < 0) {
576                                 return NULL;
577                         }
578                         length = fi->length;
579                         if (length > tvbuff_length)
580                                 length = tvbuff_length;
581                         return tvb_get_ptr(src_tvb, fi->start, length);
582                 }
583         }
584         g_assert_not_reached();
585         return NULL;    /* not found */
586 }
587
588 /* Print a string, escaping out certain characters that need to
589  * escaped out for XML. */
590 static void
591 print_escaped_xml(FILE *fh, const char *unescaped_string)
592 {
593         const unsigned char *p;
594
595         for (p = unescaped_string; *p != '\0'; p++) {
596                 switch (*p) {
597                         case '&':
598                                 fputs("&amp;", fh);
599                                 break;
600                         case '<':
601                                 fputs("&lt;", fh);
602                                 break;
603                         case '>':
604                                 fputs("&gt;", fh);
605                                 break;
606                         case '"':
607                                 fputs("&quot;", fh);
608                                 break;
609                         case '\'':
610                                 fputs("&apos;", fh);
611                                 break;
612                         default:
613                                 fputc(*p, fh);
614                 }
615         }
616 }
617
618 static void
619 write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi)
620 {
621         int i;
622         const guint8 *pd;
623
624         if (fi->length > tvb_length_remaining(fi->ds_tvb, fi->start)) {
625                 fprintf(pdata->fh, "field length invalid!");
626                 return;
627         }
628
629         /* Find the data for this field. */
630         pd = get_field_data(pdata->src_list, fi);
631
632         if (pd) {
633                 /* Print a simple hex dump */
634                 for (i = 0 ; i < fi->length; i++) {
635                         fprintf(pdata->fh, "%02x", pd[i]);
636                 }
637         }
638 }
639
640 gboolean
641 print_hex_data(print_stream_t *stream, epan_dissect_t *edt)
642 {
643         gboolean multiple_sources;
644         GSList *src_le;
645         data_source *src;
646         tvbuff_t *tvb;
647         char *name;
648         char *line;
649         const guchar *cp;
650         guint length;
651
652         /*
653          * Set "multiple_sources" iff this frame has more than one
654          * data source; if it does, we need to print the name of
655          * the data source before printing the data from the
656          * data source.
657          */
658         multiple_sources = (edt->pi.data_src->next != NULL);
659
660         for (src_le = edt->pi.data_src; src_le != NULL;
661             src_le = src_le->next) {
662                 src = src_le->data;
663                 tvb = src->tvb;
664                 if (multiple_sources) {
665                         name = src->name;
666                         print_line(stream, 0, "");
667                         line = g_malloc(strlen(name) + 2);      /* <name>:\0 */
668                         strcpy(line, name);
669                         strcat(line, ":");
670                         print_line(stream, 0, line);
671                         g_free(line);
672                 }
673                 length = tvb_length(tvb);
674                 cp = tvb_get_ptr(tvb, 0, length);
675                 if (!print_hex_data_buffer(stream, cp, length,
676                     edt->pi.fd->flags.encoding))
677                         return FALSE;
678         }
679         return TRUE;
680 }
681
682 /*
683  * This routine is based on a routine created by Dan Lasley
684  * <DLASLEY@PROMUS.com>.
685  *
686  * It was modified for Ethereal by Gilbert Ramirez and others.
687  */
688
689 #define MAX_OFFSET_LEN  8       /* max length of hex offset of bytes */
690 #define BYTES_PER_LINE  16      /* max byte values printed on a line */
691 #define HEX_DUMP_LEN    (BYTES_PER_LINE*3)
692                                 /* max number of characters hex dump takes -
693                                    2 digits plus trailing blank */
694 #define DATA_DUMP_LEN   (HEX_DUMP_LEN + 2 + BYTES_PER_LINE)
695                                 /* number of characters those bytes take;
696                                    3 characters per byte of hex dump,
697                                    2 blanks separating hex from ASCII,
698                                    1 character per byte of ASCII dump */
699 #define MAX_LINE_LEN    (MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN)
700                                 /* number of characters per line;
701                                    offset, 2 blanks separating offset
702                                    from data dump, data dump */
703
704 static gboolean
705 print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
706     guint length, char_enc encoding)
707 {
708         register unsigned int ad, i, j, k, l;
709         guchar c;
710         guchar line[MAX_LINE_LEN + 1];
711         unsigned int use_digits;
712         static guchar binhex[16] = {
713                 '0', '1', '2', '3', '4', '5', '6', '7',
714                 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
715
716         if (!print_line(stream, 0, ""))
717                 return FALSE;
718
719         /*
720          * How many of the leading digits of the offset will we supply?
721          * We always supply at least 4 digits, but if the maximum offset
722          * won't fit in 4 digits, we use as many digits as will be needed.
723          */
724         if (((length - 1) & 0xF0000000) != 0)
725                 use_digits = 8; /* need all 8 digits */
726         else if (((length - 1) & 0x0F000000) != 0)
727                 use_digits = 7; /* need 7 digits */
728         else if (((length - 1) & 0x00F00000) != 0)
729                 use_digits = 6; /* need 6 digits */
730         else if (((length - 1) & 0x000F0000) != 0)
731                 use_digits = 5; /* need 5 digits */
732         else
733                 use_digits = 4; /* we'll supply 4 digits */
734
735         ad = 0;
736         i = 0;
737         j = 0;
738         k = 0;
739         while (i < length) {
740                 if ((i & 15) == 0) {
741                         /*
742                          * Start of a new line.
743                          */
744                         j = 0;
745                         k = 0;
746                         l = use_digits;
747                         do {
748                                 l--;
749                                 c = (ad >> (l*4)) & 0xF;
750                                 line[j++] = binhex[c];
751                         } while (l != 0);
752                         line[j++] = ' ';
753                         line[j++] = ' ';
754                         memset(line+j, ' ', DATA_DUMP_LEN);
755
756                         /*
757                          * Offset in line of ASCII dump.
758                          */
759                         k = j + HEX_DUMP_LEN + 2;
760                 }
761                 c = *cp++;
762                 line[j++] = binhex[c>>4];
763                 line[j++] = binhex[c&0xf];
764                 j++;
765                 if (encoding == CHAR_EBCDIC) {
766                         c = EBCDIC_to_ASCII1(c);
767                 }
768                 line[k++] = c >= ' ' && c < 0x7f ? c : '.';
769                 i++;
770                 if ((i & 15) == 0 || i == length) {
771                         /*
772                          * We'll be starting a new line, or
773                          * we're finished printing this buffer;
774                          * dump out the line we've constructed,
775                          * and advance the offset.
776                          */
777                         line[k] = '\0';
778                         if (!print_line(stream, 0, line))
779                                 return FALSE;
780                         ad += 16;
781                 }
782         }
783         return TRUE;
784 }
785
786 static
787 void ps_clean_string(unsigned char *out, const unsigned char *in,
788                         int outbuf_size)
789 {
790         int rd, wr;
791         char c;
792
793         for (rd = 0, wr = 0 ; wr < outbuf_size; rd++, wr++ ) {
794                 c = in[rd];
795                 switch (c) {
796                         case '(':
797                         case ')':
798                         case '\\':
799                                 out[wr] = '\\';
800                                 out[++wr] = c;
801                                 break;
802
803                         default:
804                                 out[wr] = c;
805                                 break;
806                 }
807
808                 if (c == 0) {
809                         break;
810                 }
811         }
812 }
813
814 /* Some formats need stuff at the beginning of the output */
815 gboolean
816 print_preamble(print_stream_t *self, gchar *filename)
817 {
818         return (self->ops->print_preamble)(self, filename);
819 }
820
821 gboolean
822 print_line(print_stream_t *self, int indent, const char *line)
823 {
824         return (self->ops->print_line)(self, indent, line);
825 }
826
827 /* Insert bookmark */
828 gboolean
829 print_bookmark(print_stream_t *self, const gchar *name, const gchar *title)
830 {
831         return (self->ops->print_bookmark)(self, name, title);
832 }
833
834 gboolean
835 new_page(print_stream_t *self)
836 {
837         return (self->ops->new_page)(self);
838 }
839
840 /* Some formats need stuff at the end of the output */
841 gboolean
842 print_finale(print_stream_t *self)
843 {
844         return (self->ops->print_finale)(self);
845 }
846
847 gboolean
848 destroy_print_stream(print_stream_t *self)
849 {
850         return (self->ops->destroy)(self);
851 }
852
853 typedef struct {
854         int to_file;
855         FILE *fh;
856 } output_text;
857
858 static gboolean
859 print_preamble_text(print_stream_t *self _U_, gchar *filename _U_)
860 {
861         /* do nothing */
862         return TRUE;    /* always succeeds */
863 }
864
865 static gboolean
866 print_line_text(print_stream_t *self, int indent, const char *line)
867 {
868         output_text *output = self->data;
869         char space[MAX_INDENT+1];
870         int i;
871         int num_spaces;
872
873         /* Prepare the tabs for printing, depending on tree level */
874         num_spaces = indent * 4;
875         if (num_spaces > MAX_INDENT) {
876                 num_spaces = MAX_INDENT;
877         }
878         for (i = 0; i < num_spaces; i++) {
879                 space[i] = ' ';
880         }
881         /* The string is NUL-terminated */
882         space[num_spaces] = '\0';
883
884         fputs(space, output->fh);
885         fputs(line, output->fh);
886         putc('\n', output->fh);
887         return !ferror(output->fh);
888 }
889
890 static gboolean
891 print_bookmark_text(print_stream_t *self _U_, const gchar *name _U_,
892     const gchar *title _U_)
893 {
894         /* do nothing */
895         return TRUE;
896 }
897
898 static gboolean
899 new_page_text(print_stream_t *self)
900 {
901         output_text *output = self->data;
902
903         fputs("\f", output->fh);
904         return !ferror(output->fh);
905 }
906
907 static gboolean
908 print_finale_text(print_stream_t *self _U_)
909 {
910         /* do nothing */
911         return TRUE;    /* always succeeds */
912 }
913
914 static gboolean
915 destroy_text(print_stream_t *self)
916 {
917         output_text *output = self->data;
918         gboolean ret;
919
920         ret = close_print_dest(output->to_file, output->fh);
921         g_free(output);
922         g_free(self);
923         return ret;
924 }
925
926 static const print_stream_ops_t print_text_ops = {
927         print_preamble_text,
928         print_line_text,
929         print_bookmark_text,
930         new_page_text,
931         print_finale_text,
932         destroy_text
933 };
934
935 print_stream_t *
936 print_stream_text_new(int to_file, const char *dest)
937 {
938         FILE *fh;
939         print_stream_t *stream;
940         output_text *output;
941
942         fh = open_print_dest(to_file, dest);
943         if (fh == NULL)
944                 return NULL;
945
946         output = g_malloc(sizeof *output);
947         output->to_file = to_file;
948         output->fh = fh;
949         stream = g_malloc(sizeof (print_stream_t));
950         stream->ops = &print_text_ops;
951         stream->data = output;
952
953         return stream;
954 }
955
956 print_stream_t *
957 print_stream_text_stdio_new(FILE *fh)
958 {
959         print_stream_t *stream;
960         output_text *output;
961
962         output = g_malloc(sizeof *output);
963         output->to_file = TRUE;
964         output->fh = fh;
965         stream = g_malloc(sizeof (print_stream_t));
966         stream->ops = &print_text_ops;
967         stream->data = output;
968
969         return stream;
970 }
971
972 typedef struct {
973         int to_file;
974         FILE *fh;
975 } output_ps;
976
977 static gboolean
978 print_preamble_ps(print_stream_t *self, gchar *filename)
979 {
980         output_ps *output = self->data;
981         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
982
983         print_ps_preamble(output->fh);
984
985         fputs("%% Set the font to 10 point\n", output->fh);
986         fputs("/Courier findfont 10 scalefont setfont\n", output->fh);
987         fputs("\n", output->fh);
988         fputs("%% the page title\n", output->fh);
989         ps_clean_string(psbuffer, filename, MAX_PS_LINE_LENGTH);
990         fprintf(output->fh, "/eth_pagetitle (%s - Ethereal) def\n", psbuffer);
991         fputs("\n", output->fh);
992         return !ferror(output->fh);
993 }
994
995 static gboolean
996 print_line_ps(print_stream_t *self, int indent, const char *line)
997 {
998         output_ps *output = self->data;
999         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1000
1001         ps_clean_string(psbuffer, line, MAX_PS_LINE_LENGTH);
1002         fprintf(output->fh, "%d (%s) putline\n", indent, psbuffer);
1003         return !ferror(output->fh);
1004 }
1005
1006 static gboolean
1007 print_bookmark_ps(print_stream_t *self, const gchar *name, const gchar *title)
1008 {
1009         output_ps *output = self->data;
1010         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
1011
1012         /*
1013          * See the Adobe "pdfmark reference":
1014          *
1015          *      http://partners.adobe.com/asn/acrobat/docs/pdfmark.pdf
1016          *
1017          * The pdfmark stuff tells code that turns PostScript into PDF
1018          * things that it should do.
1019          *
1020          * The /OUT stuff creates a bookmark that goes to the
1021          * destination with "name" as the name and "title" as the title.
1022          *
1023          * The "/DEST" creates the destination.
1024          */
1025         ps_clean_string(psbuffer, title, MAX_PS_LINE_LENGTH);
1026         fprintf(output->fh, "[/Dest /%s /Title (%s)   /OUT pdfmark\n", name,
1027             psbuffer);
1028         fputs("[/View [/XYZ -4 currentpoint matrix currentmatrix matrix defaultmatrix\n",
1029             output->fh);
1030         fputs("matrix invertmatrix matrix concatmatrix transform exch pop 20 add null]\n",
1031             output->fh);
1032         fprintf(output->fh, "/Dest /%s /DEST pdfmark\n", name);
1033         return !ferror(output->fh);
1034 }
1035
1036 static gboolean
1037 new_page_ps(print_stream_t *self)
1038 {
1039         output_ps *output = self->data;
1040
1041         fputs("formfeed\n", output->fh);
1042         return !ferror(output->fh);
1043 }
1044
1045 static gboolean
1046 print_finale_ps(print_stream_t *self)
1047 {
1048         output_ps *output = self->data;
1049
1050         print_ps_finale(output->fh);
1051         return !ferror(output->fh);
1052 }
1053
1054 static gboolean
1055 destroy_ps(print_stream_t *self)
1056 {
1057         output_ps *output = self->data;
1058         gboolean ret;
1059
1060         ret = close_print_dest(output->to_file, output->fh);
1061         g_free(output);
1062         g_free(self);
1063         return ret;
1064 }
1065
1066 static const print_stream_ops_t print_ps_ops = {
1067         print_preamble_ps,
1068         print_line_ps,
1069         print_bookmark_ps,
1070         new_page_ps,
1071         print_finale_ps,
1072         destroy_ps
1073 };
1074
1075 print_stream_t *
1076 print_stream_ps_new(int to_file, const char *dest)
1077 {
1078         FILE *fh;
1079         print_stream_t *stream;
1080         output_ps *output;
1081
1082         fh = open_print_dest(to_file, dest);
1083         if (fh == NULL)
1084                 return NULL;
1085
1086         output = g_malloc(sizeof *output);
1087         output->to_file = to_file;
1088         output->fh = fh;
1089         stream = g_malloc(sizeof (print_stream_t));
1090         stream->ops = &print_ps_ops;
1091         stream->data = output;
1092
1093         return stream;
1094 }
1095
1096 print_stream_t *
1097 print_stream_ps_stdio_new(FILE *fh)
1098 {
1099         print_stream_t *stream;
1100         output_ps *output;
1101
1102         output = g_malloc(sizeof *output);
1103         output->to_file = TRUE;
1104         output->fh = fh;
1105         stream = g_malloc(sizeof (print_stream_t));
1106         stream->ops = &print_ps_ops;
1107         stream->data = output;
1108
1109         return stream;
1110 }