f2641c4a10dfa0521092c3fb5c3040d9b1640511
[obnox/wireshark/wip.git] / print.c
1 /* print.c
2  * Routines for printing packet analysis trees.
3  *
4  * $Id: print.c,v 1.68 2003/12/30 23:13:32 guy Exp $
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 "print.h"
40 #include "ps.h"
41 #include "util.h"
42 #include "packet-data.h"
43 #include "packet-frame.h"
44
45 #define PDML_VERSION "0"
46
47 static void proto_tree_print_node(proto_node *node, gpointer data);
48 static void proto_tree_print_node_pdml(proto_node *node, gpointer data);
49 static void print_hex_data_buffer(FILE *fh, register const guchar *cp,
50     register guint length, char_enc encoding, gint format);
51 static void ps_clean_string(unsigned char *out, const unsigned char *in,
52                         int outbuf_size);
53
54 typedef struct {
55         int                         level;
56         FILE                    *fh;
57         GSList                  *src_list;
58         print_dissections_e print_dissections;
59         gboolean                print_hex_for_data;
60         char_enc                encoding;
61         gint                    format;
62         epan_dissect_t      *edt;
63 } print_data;
64
65 static void print_pdml_geninfo(proto_tree *tree, print_data *pdata);
66
67 FILE *open_print_dest(int to_file, const char *dest)
68 {
69         FILE    *fh;
70
71         /* Open the file or command for output */
72         if (to_file)
73                 fh = fopen(dest, "w");
74         else
75                 fh = popen(dest, "w");
76
77         return fh;
78 }
79
80 void close_print_dest(int to_file, FILE *fh)
81 {
82         /* Close the file or command */
83         if (to_file)
84                 fclose(fh);
85         else
86                 pclose(fh);
87 }
88
89
90 void
91 proto_tree_print(print_args_t *print_args, epan_dissect_t *edt,
92     FILE *fh)
93 {
94         print_data data;
95
96         /* Create the output */
97         data.level = 0;
98         data.fh = fh;
99         data.src_list = edt->pi.data_src;
100         data.encoding = edt->pi.fd->flags.encoding;
101         data.print_dissections = print_args->print_dissections;
102         data.print_hex_for_data = !print_args->print_hex;
103             /* If we're printing the entire packet in hex, don't
104                print uninterpreted data fields in hex as well. */
105         data.format = print_args->format;
106         data.edt = edt;
107
108         if (data.format == PR_FMT_PDML) {
109
110                 fprintf(fh, "<packet>\n");
111
112                 /* Print a "geninfo" protocol as required by PDML */
113                 print_pdml_geninfo(edt->tree, &data);
114
115                 proto_tree_children_foreach(edt->tree, proto_tree_print_node_pdml, &data);
116
117                 fprintf(fh, "</packet>\n\n");
118         }
119         else {
120                 proto_tree_children_foreach(edt->tree, proto_tree_print_node, &data);
121         }
122 }
123
124 /*
125  * Find the data source for a specified field, and return a pointer
126  * to the data in it.
127  */
128 static const guint8 *
129 get_field_data(GSList *src_list, field_info *fi)
130 {
131         GSList *src_le;
132         data_source *src;
133         tvbuff_t *src_tvb;
134         gint length, tvbuff_length;
135
136         for (src_le = src_list; src_le != NULL; src_le = src_le->next) {
137                 src = src_le->data;
138                 src_tvb = src->tvb;
139                 if (fi->ds_tvb == src_tvb) {
140                         /*
141                          * Found it.
142                          *
143                          * XXX - a field can have a length that runs past
144                          * the end of the tvbuff.  Ideally, that should
145                          * be fixed when adding an item to the protocol
146                          * tree, but checking the length when doing
147                          * that could be expensive.  Until we fix that,
148                          * we'll do the check here.
149                          */
150                         length = fi->length;
151                         tvbuff_length = tvb_length_remaining(src_tvb,
152                             fi->start);
153                         if (length > tvbuff_length)
154                                 length = tvbuff_length;
155                         return tvb_get_ptr(src_tvb, fi->start, length);
156                 }
157         }
158         g_assert_not_reached();
159         return NULL;    /* not found */
160 }
161
162 #define MAX_INDENT      160
163
164 #define MAX_PS_LINE_LENGTH 256
165
166 /* Print a tree's data, and any child nodes. */
167 static
168 void proto_tree_print_node(proto_node *node, gpointer data)
169 {
170         field_info      *fi = PITEM_FINFO(node);
171         print_data      *pdata = (print_data*) data;
172         const guint8    *pd;
173         gchar           label_str[ITEM_LABEL_LENGTH];
174         gchar           *label_ptr;
175
176         /* Don't print invisible entries. */
177         if (!fi->visible)
178                 return;
179
180         /* was a free format label produced? */
181         if (fi->rep) {
182                 label_ptr = fi->rep->representation;
183         }
184         else { /* no, make a generic label */
185                 label_ptr = label_str;
186                 proto_item_fill_label(fi, label_str);
187         }
188
189         print_line(pdata->fh, pdata->level, pdata->format, label_ptr);
190
191         /* If it's uninterpreted data, dump it (unless our caller will
192            be printing the entire packet in hex). */
193         if (fi->hfinfo->id == proto_data && pdata->print_hex_for_data) {
194                 /*
195                  * Find the data for this field.
196                  */
197                 pd = get_field_data(pdata->src_list, fi);
198                 print_hex_data_buffer(pdata->fh, pd, fi->length,
199                     pdata->encoding, pdata->format);
200         }
201
202         /* If we're printing all levels, or if this node is one with a
203            subtree and its subtree is expanded, recurse into the subtree,
204            if it exists. */
205         g_assert(fi->tree_type >= -1 && fi->tree_type < num_tree_types);
206         if (pdata->print_dissections == print_dissections_expanded ||
207             (pdata->print_dissections == print_dissections_as_displayed &&
208         fi->tree_type >= 0 && tree_is_expanded[fi->tree_type])) {
209                 if (node->first_child != NULL) {
210                         pdata->level++;
211                         proto_tree_children_foreach(node,
212                                 proto_tree_print_node, pdata);
213                         pdata->level--;
214                 }
215         }
216 }
217
218 /* Print a string, escaping out certain characters that need to
219  * escaped out for XML. */
220 static void
221 print_escaped_xml(FILE *fh, char *unescaped_string)
222 {
223         unsigned char *p;
224
225         for (p = unescaped_string; *p != '\0'; p++) {
226                 switch (*p) {
227                         case '&':
228                                 fputs("&amp;", fh);
229                                 break;
230                         case '<':
231                                 fputs("&lt;", fh);
232                                 break;
233                         case '>':
234                                 fputs("&gt;", fh);
235                                 break;
236                         case '"':
237                                 fputs("&quot;", fh);
238                                 break;
239                         default:
240                                 fputc(*p, fh);
241                 }
242         }
243 }
244
245 static void
246 print_field_hex_value(print_data *pdata, field_info *fi)
247 {
248         int i;
249         const guint8 *pd;
250
251         /* Find the data for this field. */
252         pd = get_field_data(pdata->src_list, fi);
253
254         /* Print a simple hex dump */
255         for (i = 0 ; i < fi->length; i++) {
256                 fprintf(pdata->fh, "%02x", pd[i]);
257         }
258 }
259
260
261 /* Print a tree's data, and any child nodes, as PDML */
262 static void
263 proto_tree_print_node_pdml(proto_node *node, gpointer data)
264 {
265         field_info      *fi = PITEM_FINFO(node);
266         print_data      *pdata = (print_data*) data;
267         gchar           *label_ptr;
268         gchar           label_str[ITEM_LABEL_LENGTH];
269         char            *dfilter_string;
270         int             chop_len;
271         int             i;
272
273         for (i = -1; i < pdata->level; i++) {
274                 fputs("  ", pdata->fh);
275         }
276
277         /* Text label. It's printed as a field with no name. */
278         if (fi->hfinfo->id == hf_text_only) {
279                 /* Get the text */
280                 if (fi->rep) {
281                         label_ptr = fi->rep->representation;
282                 }
283                 else {
284                         label_ptr = "";
285                 }
286
287                 fputs("<field show=\"", pdata->fh);
288                 print_escaped_xml(pdata->fh, label_ptr);
289
290                 fprintf(pdata->fh, "\" size=\"%d", fi->length);
291                 fprintf(pdata->fh, "\" pos=\"%d", fi->start);
292
293                 fputs("\" value=\"", pdata->fh);
294                 print_field_hex_value(pdata, fi);
295
296                 if (node->first_child != NULL) {
297                         fputs("\">\n", pdata->fh);
298                 }
299                 else {
300                         fputs("\"/>\n", pdata->fh);
301                 }
302         }
303         /* Uninterpreted data, i.e., the "Data" protocol, is
304          * printed as a field instead of a protocol. */
305         else if (fi->hfinfo->id == proto_data) {
306
307                 fputs("<field name=\"data\" value=\"", pdata->fh);
308
309                 print_field_hex_value(pdata, fi);
310
311                 fputs("\"/>\n", pdata->fh);
312
313         }
314         /* Normal protocols and fields */
315         else {
316                 if (fi->hfinfo->type == FT_PROTOCOL) {
317                         fputs("<proto name=\"", pdata->fh);
318                 }
319                 else {
320                         fputs("<field name=\"", pdata->fh);
321                 }
322                 print_escaped_xml(pdata->fh, fi->hfinfo->abbrev);
323
324                 if (fi->rep) {
325                         fputs("\" showname=\"", pdata->fh);
326                         print_escaped_xml(pdata->fh, fi->rep->representation);
327                 }
328                 else {
329                         label_ptr = label_str;
330                         proto_item_fill_label(fi, label_str);
331                         fputs("\" showname=\"", pdata->fh);
332                         print_escaped_xml(pdata->fh, label_ptr);
333                 }
334
335                 fprintf(pdata->fh, "\" size=\"%d", fi->length);
336                 fprintf(pdata->fh, "\" pos=\"%d", fi->start);
337 /*              fprintf(pdata->fh, "\" id=\"%d", fi->hfinfo->id);*/
338
339                 if (fi->hfinfo->type != FT_PROTOCOL) {
340                         /* Field */
341
342                         /* XXX - this is a hack until we can juse 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                                 print_field_hex_value(pdata, fi);
365                         }
366                 }
367
368                 if (node->first_child != NULL) {
369                         fputs("\">\n", pdata->fh);
370                 }
371                 else if (fi->hfinfo->id == proto_data) {
372                         fputs("\">\n", pdata->fh);
373                 }
374                 else {
375                         fputs("\"/>\n", pdata->fh);
376                 }
377         }
378
379         /* We always pring all levels for PDML. Recurse here. */
380         if (node->first_child != NULL) {
381                 pdata->level++;
382                 proto_tree_children_foreach(node,
383                                 proto_tree_print_node_pdml, pdata);
384                 pdata->level--;
385         }
386
387         if (node->first_child != NULL) {
388                 for (i = -1; i < pdata->level; i++) {
389                         fputs("  ", pdata->fh);
390                 }
391                 if (fi->hfinfo->type == FT_PROTOCOL) {
392                         fputs("</proto>\n", pdata->fh);
393                 }
394                 else {
395                         fputs("</field>\n", pdata->fh);
396                 }
397         }
398 }
399
400 /* Print info for a 'geninfo' pseudo-protocol. This is required by
401  * the PDML spec. The information is contained in Ethereal's 'frame' protocol,
402  * but we produce a 'geninfo' protocol in the PDML to conform to spec.
403  * The 'frame' protocol follows the 'geninfo' protocol in the PDML. */
404 static void
405 print_pdml_geninfo(proto_tree *tree, print_data *pdata)
406 {
407         guint32 num, len, caplen;
408         nstime_t *timestamp;
409         GPtrArray *finfo_array;
410         field_info *frame_finfo;
411
412         /* Get frame protocol's finfo. */
413         finfo_array = proto_find_finfo(tree, proto_frame);
414         if (g_ptr_array_len(finfo_array) < 1) {
415                 return;
416         }
417         frame_finfo = finfo_array->pdata[0];
418         g_ptr_array_free(finfo_array, FALSE);
419
420         /* frame.number --> geninfo.num */
421         finfo_array = proto_find_finfo(tree, hf_frame_number);
422         if (g_ptr_array_len(finfo_array) < 1) {
423                 return;
424         }
425         num = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
426         g_ptr_array_free(finfo_array, FALSE);
427
428         /* frame.pkt_len --> geninfo.len */
429         finfo_array = proto_find_finfo(tree, hf_frame_packet_len);
430         if (g_ptr_array_len(finfo_array) < 1) {
431                 return;
432         }
433         len = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
434         g_ptr_array_free(finfo_array, FALSE);
435
436         /* frame.cap_len --> geninfo.caplen */
437         finfo_array = proto_find_finfo(tree, hf_frame_capture_len);
438         if (g_ptr_array_len(finfo_array) < 1) {
439                 return;
440         }
441         caplen = fvalue_get_integer(&((field_info*)finfo_array->pdata[0])->value);
442         g_ptr_array_free(finfo_array, FALSE);
443
444         /* frame.time --> geninfo.timestamp */
445         finfo_array = proto_find_finfo(tree, hf_frame_arrival_time);
446         if (g_ptr_array_len(finfo_array) < 1) {
447                 return;
448         }
449         timestamp = fvalue_get(&((field_info*)finfo_array->pdata[0])->value);
450         g_ptr_array_free(finfo_array, FALSE);
451
452         /* Print geninfo start */
453         fprintf(pdata->fh,
454 "  <proto name=\"geninfo\" pos=\"0\" showname=\"General information\" size=\"%u\">\n",
455                 frame_finfo->length);
456
457         /* Print geninfo.num */
458         fprintf(pdata->fh,
459 "    <field name=\"num\" pos=\"0\" show=\"%u\" showname=\"Number\" value=\"%x\" size=\"%u\"/>\n",
460                 num, num, frame_finfo->length);
461
462         /* Print geninfo.len */
463         fprintf(pdata->fh,
464 "    <field name=\"len\" pos=\"0\" show=\"%u\" showname=\"Packet Length\" value=\"%x\" size=\"%u\"/>\n",
465                 len, len, frame_finfo->length);
466
467         /* Print geninfo.caplen */
468         fprintf(pdata->fh,
469 "    <field name=\"caplen\" pos=\"0\" show=\"%u\" showname=\"Captured Length\" value=\"%x\" size=\"%u\"/>\n",
470                 caplen, caplen, frame_finfo->length);
471
472         /* Print geninfo.timestamp */
473         fprintf(pdata->fh,
474 "    <field name=\"timestamp\" pos=\"0\" show=\"%s\" showname=\"Captured Time\" value=\"%d.%09d\" size=\"%u\"/>\n",
475                 abs_time_to_str(timestamp), (int) timestamp->secs, timestamp->nsecs, frame_finfo->length);
476
477         /* Print geninfo end */
478         fprintf(pdata->fh,
479 "  </proto>\n");
480 }
481
482
483 void print_hex_data(FILE *fh, gint format, epan_dissect_t *edt)
484 {
485         gboolean multiple_sources;
486         GSList *src_le;
487         data_source *src;
488         tvbuff_t *tvb;
489         char *name;
490         char *line;
491         const guchar *cp;
492         guint length;
493
494         /*
495          * Set "multiple_sources" iff this frame has more than one
496          * data source; if it does, we need to print the name of
497          * the data source before printing the data from the
498          * data source.
499          */
500         multiple_sources = (edt->pi.data_src->next != NULL);
501
502         for (src_le = edt->pi.data_src; src_le != NULL;
503             src_le = src_le->next) {
504                 src = src_le->data;
505                 tvb = src->tvb;
506                 if (multiple_sources) {
507                         name = src->name;
508                         print_line(fh, 0, format, "");
509                         line = g_malloc(strlen(name) + 2);      /* <name>:\0 */
510                         strcpy(line, name);
511                         strcat(line, ":");
512                         print_line(fh, 0, format, line);
513                         g_free(line);
514                 }
515                 length = tvb_length(tvb);
516                 cp = tvb_get_ptr(tvb, 0, length);
517                 print_hex_data_buffer(fh, cp, length,
518                     edt->pi.fd->flags.encoding, format);
519         }
520 }
521
522 /*
523  * This routine is based on a routine created by Dan Lasley
524  * <DLASLEY@PROMUS.com>.
525  *
526  * It was modified for Ethereal by Gilbert Ramirez and others.
527  */
528
529 #define MAX_OFFSET_LEN  8       /* max length of hex offset of bytes */
530 #define BYTES_PER_LINE  16      /* max byte values printed on a line */
531 #define HEX_DUMP_LEN    (BYTES_PER_LINE*3)
532                                 /* max number of characters hex dump takes -
533                                    2 digits plus trailing blank */
534 #define DATA_DUMP_LEN   (HEX_DUMP_LEN + 2 + BYTES_PER_LINE)
535                                 /* number of characters those bytes take;
536                                    3 characters per byte of hex dump,
537                                    2 blanks separating hex from ASCII,
538                                    1 character per byte of ASCII dump */
539 #define MAX_LINE_LEN    (MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN)
540                                 /* number of characters per line;
541                                    offset, 2 blanks separating offset
542                                    from data dump, data dump */
543
544 static void
545 print_hex_data_buffer(FILE *fh, register const guchar *cp,
546     register guint length, char_enc encoding, gint format)
547 {
548         register unsigned int ad, i, j, k, l;
549         guchar c;
550         guchar line[MAX_LINE_LEN + 1];
551         unsigned int use_digits;
552         static guchar binhex[16] = {
553                 '0', '1', '2', '3', '4', '5', '6', '7',
554                 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
555
556         print_line(fh, 0, format, "");
557
558         /*
559          * How many of the leading digits of the offset will we supply?
560          * We always supply at least 4 digits, but if the maximum offset
561          * won't fit in 4 digits, we use as many digits as will be needed.
562          */
563         if (((length - 1) & 0xF0000000) != 0)
564                 use_digits = 8; /* need all 8 digits */
565         else if (((length - 1) & 0x0F000000) != 0)
566                 use_digits = 7; /* need 7 digits */
567         else if (((length - 1) & 0x00F00000) != 0)
568                 use_digits = 6; /* need 6 digits */
569         else if (((length - 1) & 0x000F0000) != 0)
570                 use_digits = 5; /* need 5 digits */
571         else
572                 use_digits = 4; /* we'll supply 4 digits */
573
574         ad = 0;
575         i = 0;
576         j = 0;
577         k = 0;
578         while (i < length) {
579                 if ((i & 15) == 0) {
580                         /*
581                          * Start of a new line.
582                          */
583                         j = 0;
584                         k = 0;
585                         l = use_digits;
586                         do {
587                                 l--;
588                                 c = (ad >> (l*4)) & 0xF;
589                                 line[j++] = binhex[c];
590                         } while (l != 0);
591                         line[j++] = ' ';
592                         line[j++] = ' ';
593                         memset(line+j, ' ', DATA_DUMP_LEN);
594
595                         /*
596                          * Offset in line of ASCII dump.
597                          */
598                         k = j + HEX_DUMP_LEN + 2;
599                 }
600                 c = *cp++;
601                 line[j++] = binhex[c>>4];
602                 line[j++] = binhex[c&0xf];
603                 j++;
604                 if (encoding == CHAR_EBCDIC) {
605                         c = EBCDIC_to_ASCII1(c);
606                 }
607                 line[k++] = c >= ' ' && c < 0x7f ? c : '.';
608                 i++;
609                 if ((i & 15) == 0 || i == length) {
610                         /*
611                          * We'll be starting a new line, or
612                          * we're finished printing this buffer;
613                          * dump out the line we've constructed,
614                          * and advance the offset.
615                          */
616                         line[k] = '\0';
617                         print_line(fh, 0, format, line);
618                         ad += 16;
619                 }
620         }
621 }
622
623 static
624 void ps_clean_string(unsigned char *out, const unsigned char *in,
625                         int outbuf_size)
626 {
627         int rd, wr;
628         char c;
629
630         for (rd = 0, wr = 0 ; wr < outbuf_size; rd++, wr++ ) {
631                 c = in[rd];
632                 switch (c) {
633                         case '(':
634                         case ')':
635                         case '\\':
636                                 out[wr] = '\\';
637                                 out[++wr] = c;
638                                 break;
639
640                         default:
641                                 out[wr] = c;
642                                 break;
643                 }
644
645                 if (c == 0) {
646                         break;
647                 }
648         }
649 }
650
651 /* Some formats need stuff at the beginning of the output */
652 void
653 print_preamble(FILE *fh, gint format)
654 {
655         if (format == PR_FMT_PS)
656                 print_ps_preamble(fh);
657         else if (format == PR_FMT_PDML) {
658                 fputs("<?xml version=\"1.0\"?>\n", fh);
659                 fputs("<pdml version=\"" PDML_VERSION "\" ", fh);
660                 fprintf(fh, "creator=\"%s/%s\">\n", PACKAGE, VERSION);
661         }
662 }
663
664 /* Some formats need stuff at the end of the output */
665 void
666 print_finale(FILE *fh, gint format)
667 {
668         if (format == PR_FMT_PS)
669                 print_ps_finale(fh);
670         else if (format == PR_FMT_PDML) {
671                 fputs("</pdml>\n", fh);
672         }
673 }
674
675 void
676 print_line(FILE *fh, int indent, gint format, char *line)
677 {
678         char            space[MAX_INDENT+1];
679         int             i;
680         int             num_spaces;
681         char            psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */
682
683         if (format == PR_FMT_PS) {
684                 ps_clean_string(psbuffer, line, MAX_PS_LINE_LENGTH);
685                 fprintf(fh, "%d (%s) putline\n", indent, psbuffer);
686         }
687         else if (format == PR_FMT_TEXT) {
688                 /* Prepare the tabs for printing, depending on tree level */
689                 num_spaces = indent * 4;
690                 if (num_spaces > MAX_INDENT) {
691                         num_spaces = MAX_INDENT;
692                 }
693                 for (i = 0; i < num_spaces; i++) {
694                         space[i] = ' ';
695                 }
696                 /* The string is NUL-terminated */
697                 space[num_spaces] = '\0';
698
699                 fputs(space, fh);
700                 fputs(line, fh);
701                 putc('\n', fh);
702         }
703         else {
704                 g_assert_not_reached();
705         }
706 }