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