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