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