aboutsummaryrefslogtreecommitdiffstats
path: root/print.c
blob: b4bb51a6db1eeb3beefcaf07313eca64aaef4a8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
/* print.c
 * Routines for printing packet analysis trees.
 *
 * $Id$
 *
 * Gilbert Ramirez <gram@alumni.rice.edu>
 *
 * Wireshark - Network traffic analyzer
 * By Gerald Combs <gerald@wireshark.org>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>
#include <string.h>

#include <glib.h>

#include <epan/epan.h>
#include <epan/epan_dissect.h>
#include <epan/tvbuff.h>
#include <epan/packet.h>
#include <epan/emem.h>
#include <epan/expert.h>

#include "packet-range.h"
#include "print.h"
#include "isprint.h"
#include "ps.h"
#include "version_info.h"
#include <wsutil/file_util.h>
#include <epan/charsets.h>
#include <epan/dissectors/packet-data.h>
#include <epan/dissectors/packet-frame.h>
#include <epan/filesystem.h>

#define PDML_VERSION "0"
#define PSML_VERSION "0"

typedef struct {
	int			level;
	print_stream_t		*stream;
	gboolean		success;
	GSList		 	*src_list;
	print_dissections_e	print_dissections;
	gboolean		print_hex_for_data;
	packet_char_enc		encoding;
	epan_dissect_t		*edt;
} print_data;

typedef struct {
	int			level;
	FILE			*fh;
	GSList		 	*src_list;
	epan_dissect_t		*edt;
} write_pdml_data;

typedef struct {
    output_fields_t* fields;
	epan_dissect_t		*edt;
} write_field_data_t;

struct _output_fields {
    gboolean print_header;
    gchar separator;
    gchar occurrence;
    gchar aggregator;
    GPtrArray* fields;
    GHashTable* field_indicies;
    emem_strbuf_t** field_values;
    gchar quote;
};

GHashTable *output_only_tables = NULL;

static gboolean write_headers = FALSE;

static const gchar* get_field_hex_value(GSList* src_list, field_info *fi);
static void proto_tree_print_node(proto_node *node, gpointer data);
static void proto_tree_write_node_pdml(proto_node *node, gpointer data);
static const guint8 *get_field_data(GSList *src_list, field_info *fi);
static void write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi);
static gboolean print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
    guint length, packet_char_enc encoding);
static void ps_clean_string(unsigned char *out, const unsigned char *in,
			int outbuf_size);
static void print_escaped_xml(FILE *fh, const char *unescaped_string);

static void print_pdml_geninfo(proto_tree *tree, FILE *fh);

static void proto_tree_get_node_field_values(proto_node *node, gpointer data);

static FILE *
open_print_dest(int to_file, const char *dest)
{
	FILE	*fh;

	/* Open the file or command for output */
	if (to_file)
		fh = ws_fopen(dest, "w");
	else
		fh = popen(dest, "w");

	return fh;
}

static gboolean
close_print_dest(int to_file, FILE *fh)
{
	/* Close the file or command */
	if (to_file)
		return (fclose(fh) == 0);
	else
		return (pclose(fh) == 0);
}

#define MAX_PS_LINE_LENGTH 256

gboolean
proto_tree_print(print_args_t *print_args, epan_dissect_t *edt,
    print_stream_t *stream)
{
	print_data data;

	/* Create the output */
	data.level = 0;
	data.stream = stream;
	data.success = TRUE;
	data.src_list = edt->pi.data_src;
	data.encoding = edt->pi.fd->flags.encoding;
	data.print_dissections = print_args->print_dissections;
	/* If we're printing the entire packet in hex, don't
	   print uninterpreted data fields in hex as well. */
	data.print_hex_for_data = !print_args->print_hex;
	data.edt = edt;

	proto_tree_children_foreach(edt->tree, proto_tree_print_node, &data);
	return data.success;
}

#define MAX_INDENT	160

/* Print a tree's data, and any child nodes. */
static
void proto_tree_print_node(proto_node *node, gpointer data)
{
	field_info	*fi = PNODE_FINFO(node);
	print_data	*pdata = (print_data*) data;
	const guint8	*pd;
	gchar		label_str[ITEM_LABEL_LENGTH];
	gchar		*label_ptr;

	g_assert(fi && "dissection with an invisible proto tree?");

	/* Don't print invisible entries. */
	if (PROTO_ITEM_IS_HIDDEN(node))
		return;

	/* Give up if we've already gotten an error. */
	if (!pdata->success)
		return;

	/* was a free format label produced? */
	if (fi->rep) {
		label_ptr = fi->rep->representation;
	}
	else { /* no, make a generic label */
		label_ptr = label_str;
		proto_item_fill_label(fi, label_str);
	}

	if (PROTO_ITEM_IS_GENERATED(node)) {
		label_ptr = g_strdup_printf("[%s]", label_ptr);
	}

	if (!print_line(pdata->stream, pdata->level, label_ptr)) {
		pdata->success = FALSE;
		return;
	}

	/*
	 * If -O is specified, only display the protocols which are in the
	 * lookup table.  Only check on the first level: once we start printing
	 * a tree, print the rest of the subtree.  Otherwise we won't print
	 * subitems whose abbreviation doesn't match the protocol--for example
	 * text items (whose abbreviation is simply "text").
	 */
	if (output_only_tables != NULL && pdata->level == 0
	 && g_hash_table_lookup(output_only_tables, fi->hfinfo->abbrev) == NULL) {
	  pdata->success = TRUE;
	  return;
	}

	if (PROTO_ITEM_IS_GENERATED(node)) {
		g_free(label_ptr);
	}

	/* If it's uninterpreted data, dump it (unless our caller will
	   be printing the entire packet in hex). */
	if (fi->hfinfo->id == proto_data && pdata->print_hex_for_data) {
		/*
		 * Find the data for this field.
		 */
		pd = get_field_data(pdata->src_list, fi);
		if (pd) {
			if (!print_hex_data_buffer(pdata->stream, pd,
			    fi->length, pdata->encoding)) {
				pdata->success = FALSE;
				return;
			}
		}
	}

	/* If we're printing all levels, or if this node is one with a
	   subtree and its subtree is expanded, recurse into the subtree,
	   if it exists. */
	g_assert(fi->tree_type >= -1 && fi->tree_type < num_tree_types);
	if (pdata->print_dissections == print_dissections_expanded ||
	    (pdata->print_dissections == print_dissections_as_displayed &&
		fi->tree_type >= 0 && tree_is_expanded[fi->tree_type])) {
		if (node->first_child != NULL) {
			pdata->level++;
			proto_tree_children_foreach(node,
				proto_tree_print_node, pdata);
			pdata->level--;
			if (!pdata->success)
				return;
		}
	}
}

#define PDML2HTML_XSL "pdml2html.xsl"
void
write_pdml_preamble(FILE *fh, const gchar* filename)
{
	time_t t=time(NULL);
	char *ts=asctime(localtime(&t));
	ts[strlen(ts)-1]=0; /* overwrite \n */

	fputs("<?xml version=\"1.0\"?>\n", fh);
	fputs("<?xml-stylesheet type=\"text/xsl\" href=\"" PDML2HTML_XSL "\"?>\n", fh);
	fprintf(fh, "<!-- You can find " PDML2HTML_XSL " in %s or at http://anonsvn.wireshark.org/trunk/wireshark/" PDML2HTML_XSL ". -->\n", get_datafile_dir());
	fputs("<pdml version=\"" PDML_VERSION "\" ", fh);
	fprintf(fh, "creator=\"%s/%s\" time=\"%s\" capture_file=\"%s\">\n", PACKAGE, VERSION, ts, filename ? filename : "");
}

void
proto_tree_write_pdml(epan_dissect_t *edt, FILE *fh)
{
	write_pdml_data data;

	/* Create the output */
	data.level = 0;
	data.fh = fh;
	data.src_list = edt->pi.data_src;
	data.edt = edt;

	fprintf(fh, "<packet>\n");

	/* Print a "geninfo" protocol as required by PDML */
	print_pdml_geninfo(edt->tree, fh);

	proto_tree_children_foreach(edt->tree, proto_tree_write_node_pdml,
	    &data);

	fprintf(fh, "</packet>\n\n");
}

/* Write out a tree's data, and any child nodes, as PDML */
static void
proto_tree_write_node_pdml(proto_node *node, gpointer data)
{
	field_info	*fi = PNODE_FINFO(node);
	write_pdml_data	*pdata = (write_pdml_data*) data;
	const gchar	*label_ptr;
	gchar		label_str[ITEM_LABEL_LENGTH];
	char		*dfilter_string;
	size_t		chop_len;
	int		i;
	gboolean wrap_in_fake_protocol;

	g_assert(fi && "dissection with an invisible proto tree?");

	/* Will wrap up top-level field items inside a fake protocol wrapper to
	   preserve the PDML schema */
	wrap_in_fake_protocol =
	    (((fi->hfinfo->type != FT_PROTOCOL) ||
	     (fi->hfinfo->id == proto_data)) &&
	    (pdata->level == 0));

	/* Indent to the correct level */
	for (i = -1; i < pdata->level; i++) {
		fputs("  ", pdata->fh);
	}

	if (wrap_in_fake_protocol) {
		/* Open fake protocol wrapper */
		fputs("<proto name=\"fake-field-wrapper\">\n", pdata->fh);

		/* Indent to increased level before writing out field */
		pdata->level++;
		for (i = -1; i < pdata->level; i++) {
			fputs("  ", pdata->fh);
		}
	}

	/* Text label. It's printed as a field with no name. */
	if (fi->hfinfo->id == hf_text_only) {
		/* Get the text */
		if (fi->rep) {
			label_ptr = fi->rep->representation;
		}
		else {
			label_ptr = "";
		}

		/* Show empty name since it is a required field */
		fputs("<field name=\"", pdata->fh);
		fputs("\" show=\"", pdata->fh);
		print_escaped_xml(pdata->fh, label_ptr);

		fprintf(pdata->fh, "\" size=\"%d", fi->length);
		if (node->parent && node->parent->finfo && (fi->start < node->parent->finfo->start)) {
			fprintf(pdata->fh, "\" pos=\"%d", node->parent->finfo->start + fi->start);
		} else {
			fprintf(pdata->fh, "\" pos=\"%d", fi->start);
		}

		fputs("\" value=\"", pdata->fh);
		write_pdml_field_hex_value(pdata, fi);

		if (node->first_child != NULL) {
			fputs("\">\n", pdata->fh);
		}
		else {
			fputs("\"/>\n", pdata->fh);
		}
	}

	/* Uninterpreted data, i.e., the "Data" protocol, is
	 * printed as a field instead of a protocol. */
	else if (fi->hfinfo->id == proto_data) {

		/* Write out field with data */
		fputs("<field name=\"data\" value=\"", pdata->fh);
		write_pdml_field_hex_value(pdata, fi);
		fputs("\">\n", pdata->fh);
	}
	/* Normal protocols and fields */
	else {
		if (fi->hfinfo->type == FT_PROTOCOL && fi->hfinfo->id != proto_expert) {
			fputs("<proto name=\"", pdata->fh);
		}
		else {
			fputs("<field name=\"", pdata->fh);
		}
		print_escaped_xml(pdata->fh, fi->hfinfo->abbrev);

#if 0
	/* PDML spec, see:
	 * http://www.nbee.org/doku.php?id=netpdl:pdml_specification
	 *
	 * the show fields contains things in 'human readable' format
	 * showname: contains only the name of the field
	 * show: contains only the data of the field
	 * showdtl: contains additional details of the field data
	 * showmap: contains mappings of the field data (e.g. the hostname to an IP address)
	 *
	 * XXX - the showname shouldn't contain the field data itself
	 * (like it's contained in the fi->rep->representation).
	 * Unfortunately, we don't have the field data representation for
	 * all fields, so this isn't currently possible */
		fputs("\" showname=\"", pdata->fh);
		print_escaped_xml(pdata->fh, fi->hfinfo->name);
#endif

		if (fi->rep) {
			fputs("\" showname=\"", pdata->fh);
			print_escaped_xml(pdata->fh, fi->rep->representation);
		}
		else {
			label_ptr = label_str;
			proto_item_fill_label(fi, label_str);
			fputs("\" showname=\"", pdata->fh);
			print_escaped_xml(pdata->fh, label_ptr);
		}

		if (PROTO_ITEM_IS_HIDDEN(node))
			fprintf(pdata->fh, "\" hide=\"yes");

		fprintf(pdata->fh, "\" size=\"%d", fi->length);
		if (node->parent && node->parent->finfo && (fi->start < node->parent->finfo->start)) {
			fprintf(pdata->fh, "\" pos=\"%d", node->parent->finfo->start + fi->start);
		} else {
			fprintf(pdata->fh, "\" pos=\"%d", fi->start);
		}
/*		fprintf(pdata->fh, "\" id=\"%d", fi->hfinfo->id);*/

		/* show, value, and unmaskedvalue attributes */
		switch (fi->hfinfo->type)
		{
		case FT_PROTOCOL:
			break;
		case FT_NONE:
			fputs("\" show=\"\" value=\"",  pdata->fh);
			break;
		default:
			/* XXX - this is a hack until we can just call
			 * fvalue_to_string_repr() for *all* FT_* types. */
			dfilter_string = proto_construct_match_selected_string(fi,
			    pdata->edt);
			if (dfilter_string != NULL) {
				chop_len = strlen(fi->hfinfo->abbrev) + 4; /* for " == " */

				/* XXX - Remove double-quotes. Again, once we
				 * can call fvalue_to_string_repr(), we can
				 * ask it not to produce the version for
				 * display-filters, and thus, no
				 * double-quotes. */
				if (dfilter_string[strlen(dfilter_string)-1] == '"') {
					dfilter_string[strlen(dfilter_string)-1] = '\0';
					chop_len++;
				}

				fputs("\" show=\"", pdata->fh);
				print_escaped_xml(pdata->fh, &dfilter_string[chop_len]);
			}

			/*
			 * XXX - should we omit "value" for any fields?
			 * What should we do for fields whose length is 0?
			 * They might come from a pseudo-header or from
			 * the capture header (e.g., time stamps), or
			 * they might be generated fields.
			 */
			if (fi->length > 0) {
				fputs("\" value=\"", pdata->fh);

				if (fi->hfinfo->bitmask!=0) {
					fprintf(pdata->fh, "%X", fvalue_get_uinteger(&fi->value));
					fputs("\" unmaskedvalue=\"", pdata->fh);
					write_pdml_field_hex_value(pdata, fi);
				}
				else {
					write_pdml_field_hex_value(pdata, fi);
				}
			}
		}

		if (node->first_child != NULL) {
			fputs("\">\n", pdata->fh);
		}
		else if (fi->hfinfo->id == proto_data) {
			fputs("\">\n", pdata->fh);
		}
		else {
			fputs("\"/>\n", pdata->fh);
		}
	}

	/* We always print all levels for PDML. Recurse here. */
	if (node->first_child != NULL) {
		pdata->level++;
		proto_tree_children_foreach(node,
				proto_tree_write_node_pdml, pdata);
		pdata->level--;
	}

	/* Take back the extra level we added for fake wrapper protocol */
	if (wrap_in_fake_protocol) {
		pdata->level--;
	}

	if (node->first_child != NULL) {
		/* Indent to correct level */
		for (i = -1; i < pdata->level; i++) {
			fputs("  ", pdata->fh);
		}
		/* Close off current element */
		/* Data and expert "protocols" use simple tags */
		if (fi->hfinfo->id != proto_data && fi->hfinfo->id != proto_expert) {
			if (fi->hfinfo->type == FT_PROTOCOL) {
				fputs("</proto>\n", pdata->fh);
			}
			else {
				fputs("</field>\n", pdata->fh);
			}
		} else {
			fputs("</field>\n", pdata->fh);
		}
	}

	/* Close off fake wrapper protocol */
	if (wrap_in_fake_protocol) {
		fputs("</proto>\n", pdata->fh);
	}
}

/* Print info for a 'geninfo' pseudo-protocol. This is required by
 * the PDML spec. The information is contained in Wireshark's 'frame' protocol,
 * but we produce a 'geninfo' protocol in the PDML to conform to spec.
 * The 'frame' protocol follows the 'geninfo' protocol in the PDML. */
static void
print_pdml_geninfo(proto_tree *tree, FILE *fh)
{
	guint32 num, len, caplen;
	nstime_t *timestamp;
	GPtrArray *finfo_array;
	field_info *frame_finfo;

	/* Get frame protocol's finfo. */
	finfo_array = proto_find_finfo(tree, proto_frame);
	if (g_ptr_array_len(finfo_array) < 1) {
		return;
	}
	frame_finfo = (field_info *)finfo_array->pdata[0];
	g_ptr_array_free(finfo_array, TRUE);

	/* frame.number --> geninfo.num */
	finfo_array = proto_find_finfo(tree, hf_frame_number);
	if (g_ptr_array_len(finfo_array) < 1) {
		return;
	}
	num = fvalue_get_uinteger(&((field_info*)finfo_array->pdata[0])->value);
	g_ptr_array_free(finfo_array, TRUE);

	/* frame.frame_len --> geninfo.len */
	finfo_array = proto_find_finfo(tree, hf_frame_len);
	if (g_ptr_array_len(finfo_array) < 1) {
		return;
	}
	len = fvalue_get_uinteger(&((field_info*)finfo_array->pdata[0])->value);
	g_ptr_array_free(finfo_array, TRUE);

	/* frame.cap_len --> geninfo.caplen */
	finfo_array = proto_find_finfo(tree, hf_frame_capture_len);
	if (g_ptr_array_len(finfo_array) < 1) {
		return;
	}
	caplen = fvalue_get_uinteger(&((field_info*)finfo_array->pdata[0])->value);
	g_ptr_array_free(finfo_array, TRUE);

	/* frame.time --> geninfo.timestamp */
	finfo_array = proto_find_finfo(tree, hf_frame_arrival_time);
	if (g_ptr_array_len(finfo_array) < 1) {
		return;
	}
	timestamp = (nstime_t *)fvalue_get(&((field_info*)finfo_array->pdata[0])->value);
	g_ptr_array_free(finfo_array, TRUE);

	/* Print geninfo start */
	fprintf(fh,
"  <proto name=\"geninfo\" pos=\"0\" showname=\"General information\" size=\"%u\">\n",
		frame_finfo->length);

	/* Print geninfo.num */
	fprintf(fh,
"    <field name=\"num\" pos=\"0\" show=\"%u\" showname=\"Number\" value=\"%x\" size=\"%u\"/>\n",
		num, num, frame_finfo->length);

	/* Print geninfo.len */
	fprintf(fh,
"    <field name=\"len\" pos=\"0\" show=\"%u\" showname=\"Frame Length\" value=\"%x\" size=\"%u\"/>\n",
		len, len, frame_finfo->length);

	/* Print geninfo.caplen */
	fprintf(fh,
"    <field name=\"caplen\" pos=\"0\" show=\"%u\" showname=\"Captured Length\" value=\"%x\" size=\"%u\"/>\n",
		caplen, caplen, frame_finfo->length);

	/* Print geninfo.timestamp */
	fprintf(fh,
"    <field name=\"timestamp\" pos=\"0\" show=\"%s\" showname=\"Captured Time\" value=\"%d.%09d\" size=\"%u\"/>\n",
		abs_time_to_str(timestamp, ABSOLUTE_TIME_LOCAL, TRUE), (int) timestamp->secs, timestamp->nsecs, frame_finfo->length);

	/* Print geninfo end */
	fprintf(fh,
"  </proto>\n");
}

void
write_pdml_finale(FILE *fh)
{
	fputs("</pdml>\n", fh);
}

void
write_psml_preamble(FILE *fh)
{
	fputs("<?xml version=\"1.0\"?>\n", fh);
	fputs("<psml version=\"" PSML_VERSION "\" ", fh);
	fprintf(fh, "creator=\"%s/%s\">\n", PACKAGE, VERSION);
	write_headers = TRUE;
}

void
proto_tree_write_psml(epan_dissect_t *edt, FILE *fh)
{
	gint	i;

	/* if this is the first packet, we have to create the PSML structure output */
	if(write_headers) {
	    fprintf(fh, "<structure>\n");

	    for(i=0; i < edt->pi.cinfo->num_cols; i++) {
		fprintf(fh, "<section>");
		print_escaped_xml(fh, edt->pi.cinfo->col_title[i]);
		fprintf(fh, "</section>\n");
	    }

	    fprintf(fh, "</structure>\n\n");

	    write_headers = FALSE;
	}

	fprintf(fh, "<packet>\n");

	for(i=0; i < edt->pi.cinfo->num_cols; i++) {
	    fprintf(fh, "<section>");
	    print_escaped_xml(fh, edt->pi.cinfo->col_data[i]);
	    fprintf(fh, "</section>\n");
	}

	fprintf(fh, "</packet>\n\n");
}

void
write_psml_finale(FILE *fh)
{
	fputs("</psml>\n", fh);
}

void
write_csv_preamble(FILE *fh _U_)
{
	write_headers = TRUE;
}

static gchar *csv_massage_str(const gchar *source, const gchar *exceptions)
{
    gchar *csv_str;
    gchar *tmp_str;

    csv_str = g_strescape(source, exceptions);
    tmp_str = csv_str;
    while ( (tmp_str = strstr(tmp_str, "\\\"")) != NULL )
        *tmp_str = '\"';
    return csv_str;
}

static void csv_write_str(const char *str, char sep, FILE *fh)
{
    gchar *csv_str;

    csv_str = csv_massage_str(str, NULL);
    fprintf(fh, "\"%s\"%c", csv_str, sep);
    g_free(csv_str);
}

void
proto_tree_write_csv(epan_dissect_t *edt, FILE *fh)
{
    gint i;

    /* if this is the first packet, we have to write the CSV header */
    if(write_headers) {
        for(i=0; i < edt->pi.cinfo->num_cols - 1; i++)
            csv_write_str(edt->pi.cinfo->col_title[i], ',', fh);
        csv_write_str(edt->pi.cinfo->col_title[i], '\n', fh);
        write_headers = FALSE;
    }

    for(i=0; i < edt->pi.cinfo->num_cols - 1; i++)
        csv_write_str(edt->pi.cinfo->col_data[i], ',', fh);
    csv_write_str(edt->pi.cinfo->col_data[i], '\n', fh);
}

void
write_csv_finale(FILE *fh _U_)
{

}

void
write_carrays_preamble(FILE *fh _U_)
{

}

void
proto_tree_write_carrays(guint32 num, FILE *fh, epan_dissect_t *edt)
{
	guint32 i = 0, src_num = 0;
	GSList *src_le;
	data_source *src;
	tvbuff_t *tvb;
	const char *name;
	const guchar *cp;
	guint length;
	char ascii[9];

	for (src_le = edt->pi.data_src; src_le != NULL; src_le = src_le->next) {
		memset(ascii, 0, sizeof(ascii));
		src = (data_source *)src_le->data;
		tvb = src->tvb;
		length = tvb_length(tvb);
		if (length == 0)
			continue;

		cp = tvb_get_ptr(tvb, 0, length);

		name = get_data_source_name(src);
		if (name)
			fprintf(fh, "/* %s */\n", name);
		if (src_num) {
			fprintf(fh, "static const unsigned char pkt%u_%u[%u] = {\n",
				num, src_num, length);
		} else {
			fprintf(fh, "static const unsigned char pkt%u[%u] = {\n",
				num, length);
		}
		src_num++;

		for (i = 0; i < length; i++) {
			fprintf(fh, "0x%02x", *(cp + i));
			ascii[i % 8] = isprint(*(cp + i)) ? *(cp + i) : '.';

			if (i == (length - 1)) {
				guint rem;
				rem = length % 8;
				if (rem) {
					guint j;
					for ( j = 0; j < 8 - rem; j++ )
						fprintf(fh, "      ");
				}
				fprintf(fh, "  /* %s */\n};\n\n", ascii);
				break;
			}

			if (!((i + 1) % 8)) {
				fprintf(fh, ", /* %s */\n", ascii);
				memset(ascii, 0, sizeof(ascii));
			}
			else {
				fprintf(fh, ", ");
			}
		}
	}
}

void
write_carrays_finale(FILE *fh _U_)
{

}

/*
 * Find the data source for a specified field, and return a pointer
 * to the data in it. Returns NULL if the data is out of bounds.
 */
static const guint8 *
get_field_data(GSList *src_list, field_info *fi)
{
	GSList *src_le;
	data_source *src;
	tvbuff_t *src_tvb;
	gint length, tvbuff_length;

	for (src_le = src_list; src_le != NULL; src_le = src_le->next) {
		src = (data_source *)src_le->data;
		src_tvb = src->tvb;
		if (fi->ds_tvb == src_tvb) {
			/*
			 * Found it.
			 *
			 * XXX - a field can have a length that runs past
			 * the end of the tvbuff.  Ideally, that should
			 * be fixed when adding an item to the protocol
			 * tree, but checking the length when doing
			 * that could be expensive.  Until we fix that,
			 * we'll do the check here.
			 */
			tvbuff_length = tvb_length_remaining(src_tvb,
			    fi->start);
			if (tvbuff_length < 0) {
				return NULL;
			}
			length = fi->length;
			if (length > tvbuff_length)
				length = tvbuff_length;
			return tvb_get_ptr(src_tvb, fi->start, length);
		}
	}
	g_assert_not_reached();
	return NULL;	/* not found */
}

/* Print a string, escaping out certain characters that need to
 * escaped out for XML. */
static void
print_escaped_xml(FILE *fh, const char *unescaped_string)
{
	const char *p;
	char temp_str[8];

	for (p = unescaped_string; *p != '\0'; p++) {
		switch (*p) {
			case '&':
				fputs("&amp;", fh);
				break;
			case '<':
				fputs("&lt;", fh);
				break;
			case '>':
				fputs("&gt;", fh);
				break;
			case '"':
				fputs("&quot;", fh);
				break;
			case '\'':
				fputs("&apos;", fh);
				break;
			default:
				if (g_ascii_isprint(*p))
					fputc(*p, fh);
				else {
					g_snprintf(temp_str, sizeof(temp_str), "\\x%x", (guint8)*p);
					fputs(temp_str, fh);
				}
		}
	}
}

static void
write_pdml_field_hex_value(write_pdml_data *pdata, field_info *fi)
{
	int i;
	const guint8 *pd;

	if (!fi->ds_tvb)
		return;

	if (fi->length > tvb_length_remaining(fi->ds_tvb, fi->start)) {
		fprintf(pdata->fh, "field length invalid!");
		return;
	}

	/* Find the data for this field. */
	pd = get_field_data(pdata->src_list, fi);

	if (pd) {
		/* Print a simple hex dump */
		for (i = 0 ; i < fi->length; i++) {
			fprintf(pdata->fh, "%02x", pd[i]);
		}
	}
}

gboolean
print_hex_data(print_stream_t *stream, epan_dissect_t *edt)
{
	gboolean multiple_sources;
	GSList *src_le;
	data_source *src;
	tvbuff_t *tvb;
	const char *name;
	char *line;
	const guchar *cp;
	guint length;

	/*
	 * Set "multiple_sources" iff this frame has more than one
	 * data source; if it does, we need to print the name of
	 * the data source before printing the data from the
	 * data source.
	 */
	multiple_sources = (edt->pi.data_src->next != NULL);

	for (src_le = edt->pi.data_src; src_le != NULL;
	    src_le = src_le->next) {
		src = (data_source *)src_le->data;
		tvb = src->tvb;
		if (multiple_sources) {
			name = get_data_source_name(src);
			print_line(stream, 0, "");
			line = g_strdup_printf("%s:", name);
			print_line(stream, 0, line);
			g_free(line);
		}
		length = tvb_length(tvb);
		if (length == 0)
		    return TRUE;
		cp = tvb_get_ptr(tvb, 0, length);
		if (!print_hex_data_buffer(stream, cp, length,
		    edt->pi.fd->flags.encoding))
			return FALSE;
	}
	return TRUE;
}

/*
 * This routine is based on a routine created by Dan Lasley
 * <DLASLEY@PROMUS.com>.
 *
 * It was modified for Wireshark by Gilbert Ramirez and others.
 */

#define MAX_OFFSET_LEN	8	/* max length of hex offset of bytes */
#define BYTES_PER_LINE	16	/* max byte values printed on a line */
#define HEX_DUMP_LEN	(BYTES_PER_LINE*3)
				/* max number of characters hex dump takes -
				   2 digits plus trailing blank */
#define DATA_DUMP_LEN	(HEX_DUMP_LEN + 2 + BYTES_PER_LINE)
				/* number of characters those bytes take;
				   3 characters per byte of hex dump,
				   2 blanks separating hex from ASCII,
				   1 character per byte of ASCII dump */
#define MAX_LINE_LEN	(MAX_OFFSET_LEN + 2 + DATA_DUMP_LEN)
				/* number of characters per line;
				   offset, 2 blanks separating offset
				   from data dump, data dump */

static gboolean
print_hex_data_buffer(print_stream_t *stream, const guchar *cp,
    guint length, packet_char_enc encoding)
{
	register unsigned int ad, i, j, k, l;
	guchar c;
	guchar line[MAX_LINE_LEN + 1];
	unsigned int use_digits;
	static guchar binhex[16] = {
		'0', '1', '2', '3', '4', '5', '6', '7',
		'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

	if (!print_line(stream, 0, ""))
		return FALSE;

	/*
	 * How many of the leading digits of the offset will we supply?
	 * We always supply at least 4 digits, but if the maximum offset
	 * won't fit in 4 digits, we use as many digits as will be needed.
	 */
	if (((length - 1) & 0xF0000000) != 0)
		use_digits = 8;	/* need all 8 digits */
	else if (((length - 1) & 0x0F000000) != 0)
		use_digits = 7;	/* need 7 digits */
	else if (((length - 1) & 0x00F00000) != 0)
		use_digits = 6;	/* need 6 digits */
	else if (((length - 1) & 0x000F0000) != 0)
		use_digits = 5;	/* need 5 digits */
	else
		use_digits = 4;	/* we'll supply 4 digits */

	ad = 0;
	i = 0;
	j = 0;
	k = 0;
	while (i < length) {
		if ((i & 15) == 0) {
			/*
			 * Start of a new line.
			 */
			j = 0;
			l = use_digits;
			do {
				l--;
				c = (ad >> (l*4)) & 0xF;
				line[j++] = binhex[c];
			} while (l != 0);
			line[j++] = ' ';
			line[j++] = ' ';
			memset(line+j, ' ', DATA_DUMP_LEN);

			/*
			 * Offset in line of ASCII dump.
			 */
			k = j + HEX_DUMP_LEN + 2;
		}
		c = *cp++;
		line[j++] = binhex[c>>4];
		line[j++] = binhex[c&0xf];
		j++;
		if (encoding == PACKET_CHAR_ENC_CHAR_EBCDIC) {
			c = EBCDIC_to_ASCII1(c);
		}
		line[k++] = c >= ' ' && c < 0x7f ? c : '.';
		i++;
		if ((i & 15) == 0 || i == length) {
			/*
			 * We'll be starting a new line, or
			 * we're finished printing this buffer;
			 * dump out the line we've constructed,
			 * and advance the offset.
			 */
			line[k] = '\0';
			if (!print_line(stream, 0, line))
				return FALSE;
			ad += 16;
		}
	}
	return TRUE;
}

static
void ps_clean_string(unsigned char *out, const unsigned char *in,
			int outbuf_size)
{
	int rd, wr;
	char c;

	if (in == NULL) {
		out[0] = '\0';
		return;
	}

	for (rd = 0, wr = 0 ; wr < outbuf_size; rd++, wr++ ) {
		c = in[rd];
		switch (c) {
			case '(':
			case ')':
			case '\\':
				out[wr] = '\\';
				out[++wr] = c;
				break;

			default:
				out[wr] = c;
				break;
		}

		if (c == 0) {
			break;
		}
	}
}

/* Some formats need stuff at the beginning of the output */
gboolean
print_preamble(print_stream_t *self, gchar *filename)
{
	return (self->ops->print_preamble)(self, filename);
}

gboolean
print_line(print_stream_t *self, int indent, const char *line)
{
	return (self->ops->print_line)(self, indent, line);
}

/* Insert bookmark */
gboolean
print_bookmark(print_stream_t *self, const gchar *name, const gchar *title)
{
	return (self->ops->print_bookmark)(self, name, title);
}

gboolean
new_page(print_stream_t *self)
{
	return (self->ops->new_page)(self);
}

/* Some formats need stuff at the end of the output */
gboolean
print_finale(print_stream_t *self)
{
	return (self->ops->print_finale)(self);
}

gboolean
destroy_print_stream(print_stream_t *self)
{
	return (self->ops->destroy)(self);
}

typedef struct {
	int to_file;
	FILE *fh;
} output_text;

static gboolean
print_preamble_text(print_stream_t *self _U_, gchar *filename _U_)
{
	/* do nothing */
	return TRUE;	/* always succeeds */
}

static gboolean
print_line_text(print_stream_t *self, int indent, const char *line)
{
	output_text *output = (output_text *)self->data;
	char space[MAX_INDENT+1];
	int i;
	int num_spaces;

	/* Prepare the tabs for printing, depending on tree level */
	num_spaces = indent * 4;
	if (num_spaces > MAX_INDENT) {
		num_spaces = MAX_INDENT;
	}
	for (i = 0; i < num_spaces; i++) {
		space[i] = ' ';
	}
	/* The string is NUL-terminated */
	space[num_spaces] = '\0';

	fputs(space, output->fh);
	fputs(line, output->fh);
	putc('\n', output->fh);
	return !ferror(output->fh);
}

static gboolean
print_bookmark_text(print_stream_t *self _U_, const gchar *name _U_,
    const gchar *title _U_)
{
	/* do nothing */
	return TRUE;
}

static gboolean
new_page_text(print_stream_t *self)
{
	output_text *output = (output_text *)self->data;

	fputs("\f", output->fh);
	return !ferror(output->fh);
}

static gboolean
print_finale_text(print_stream_t *self _U_)
{
	/* do nothing */
	return TRUE;	/* always succeeds */
}

static gboolean
destroy_text(print_stream_t *self)
{
	output_text *output = (output_text *)self->data;
	gboolean ret;

	ret = close_print_dest(output->to_file, output->fh);
	g_free(output);
	g_free(self);
	return ret;
}

static const print_stream_ops_t print_text_ops = {
	print_preamble_text,
	print_line_text,
	print_bookmark_text,
	new_page_text,
	print_finale_text,
	destroy_text
};

static print_stream_t *
print_stream_text_alloc(int to_file, FILE *fh)
{
	print_stream_t *stream;
	output_text *output;

	output = (output_text *)g_malloc(sizeof *output);
	output->to_file = to_file;
	output->fh = fh;
	stream = (print_stream_t *)g_malloc(sizeof (print_stream_t));
	stream->ops = &print_text_ops;
	stream->data = output;

	return stream;
}

print_stream_t *
print_stream_text_new(int to_file, const char *dest)
{
	FILE *fh;

	fh = open_print_dest(to_file, dest);
	if (fh == NULL)
		return NULL;

	return print_stream_text_alloc(to_file, fh);
}

print_stream_t *
print_stream_text_stdio_new(FILE *fh)
{
	return print_stream_text_alloc(TRUE, fh);
}

typedef struct {
	int to_file;
	FILE *fh;
} output_ps;

static gboolean
print_preamble_ps(print_stream_t *self, gchar *filename)
{
	output_ps *output = (output_ps *)self->data;
	unsigned char psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */

	print_ps_preamble(output->fh);

	fputs("%% the page title\n", output->fh);
	ps_clean_string(psbuffer, filename, MAX_PS_LINE_LENGTH);
	fprintf(output->fh, "/ws_pagetitle (%s - Wireshark " VERSION "%s) def\n", psbuffer, wireshark_svnversion);
	fputs("\n", output->fh);
	return !ferror(output->fh);
}

static gboolean
print_line_ps(print_stream_t *self, int indent, const char *line)
{
	output_ps *output = (output_ps *)self->data;
	unsigned char psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */

	ps_clean_string(psbuffer, line, MAX_PS_LINE_LENGTH);
	fprintf(output->fh, "%d (%s) putline\n", indent, psbuffer);
	return !ferror(output->fh);
}

static gboolean
print_bookmark_ps(print_stream_t *self, const gchar *name, const gchar *title)
{
	output_ps *output = (output_ps *)self->data;
	unsigned char psbuffer[MAX_PS_LINE_LENGTH]; /* static sized buffer! */

	/*
	 * See the Adobe "pdfmark reference":
	 *
	 *	http://partners.adobe.com/asn/acrobat/docs/pdfmark.pdf
	 *
	 * The pdfmark stuff tells code that turns PostScript into PDF
	 * things that it should do.
	 *
	 * The /OUT stuff creates a bookmark that goes to the
	 * destination with "name" as the name and "title" as the title.
	 *
	 * The "/DEST" creates the destination.
	 */
	ps_clean_string(psbuffer, title, MAX_PS_LINE_LENGTH);
	fprintf(output->fh, "[/Dest /%s /Title (%s)   /OUT pdfmark\n", name,
	    psbuffer);
	fputs("[/View [/XYZ -4 currentpoint matrix currentmatrix matrix defaultmatrix\n",
	    output->fh);
	fputs("matrix invertmatrix matrix concatmatrix transform exch pop 20 add null]\n",
	    output->fh);
	fprintf(output->fh, "/Dest /%s /DEST pdfmark\n", name);
	return !ferror(output->fh);
}

static gboolean
new_page_ps(print_stream_t *self)
{
	output_ps *output = (output_ps *)self->data;

	fputs("formfeed\n", output->fh);
	return !ferror(output->fh);
}

static gboolean
print_finale_ps(print_stream_t *self)
{
	output_ps *output = (output_ps *)self->data;

	print_ps_finale(output->fh);
	return !ferror(output->fh);
}

static gboolean
destroy_ps(print_stream_t *self)
{
	output_ps *output = (output_ps *)self->data;
	gboolean ret;

	ret = close_print_dest(output->to_file, output->fh);
	g_free(output);
	g_free(self);
	return ret;
}

static const print_stream_ops_t print_ps_ops = {
	print_preamble_ps,
	print_line_ps,
	print_bookmark_ps,
	new_page_ps,
	print_finale_ps,
	destroy_ps
};

static print_stream_t *
print_stream_ps_alloc(int to_file, FILE *fh)
{
	print_stream_t *stream;
	output_ps *output;

	output = (output_ps *)g_malloc(sizeof *output);
	output->to_file = to_file;
	output->fh = fh;
	stream = (print_stream_t *)g_malloc(sizeof (print_stream_t));
	stream->ops = &print_ps_ops;
	stream->data = output;

	return stream;
}

print_stream_t *
print_stream_ps_new(int to_file, const char *dest)
{
	FILE *fh;

	fh = open_print_dest(to_file, dest);
	if (fh == NULL)
		return NULL;

	return print_stream_ps_alloc(to_file, fh);
}

print_stream_t *
print_stream_ps_stdio_new(FILE *fh)
{
	return print_stream_ps_alloc(TRUE, fh);
}

output_fields_t* output_fields_new(void)
{
    output_fields_t* fields = g_new(output_fields_t, 1);
    fields->print_header = FALSE;
    fields->separator = '\t';
    fields->occurrence = 'a';
    fields->aggregator = ',';
    fields->fields = NULL; /*Do lazy initialisation */
    fields->field_indicies = NULL;
    fields->field_values = NULL;
    fields->quote='\0';
    return fields;
}

gsize output_fields_num_fields(output_fields_t* fields)
{
    g_assert(fields);

    if(NULL == fields->fields) {
        return 0;
    } else {
        return fields->fields->len;
    }
}

void output_fields_free(output_fields_t* fields)
{
    g_assert(fields);

    if(NULL != fields->field_indicies) {
        /* Keys are stored in fields->fields, values are
         * integers.
         */
        g_hash_table_destroy(fields->field_indicies);
    }
    if(NULL != fields->fields) {
        gsize i;
        for(i = 0; i < fields->fields->len; ++i) {
            gchar* field = (gchar *)g_ptr_array_index(fields->fields,i);
            g_free(field);
        }
        g_ptr_array_free(fields->fields, TRUE);
    }

    g_free(fields);
}

void output_fields_add(output_fields_t* fields, const gchar* field)
{
    gchar* field_copy;

    g_assert(fields);
    g_assert(field);


    if(NULL == fields->fields) {
        fields->fields = g_ptr_array_new();
    }

    field_copy = g_strdup(field);

    g_ptr_array_add(fields->fields, field_copy);
}

gboolean output_fields_set_option(output_fields_t* info, gchar* option)
{
    const gchar* option_name;
    const gchar* option_value;

    g_assert(info);
    g_assert(option);

    if('\0' == *option) {
        return FALSE; /* Is this guarded against by option parsing? */
    }
    option_name = strtok(option,"=");
    if (!option_name) {
        return FALSE;
    }
    option_value = option + strlen(option_name) + 1;
    if(0 == strcmp(option_name, "header")) {
        switch(NULL == option_value ? '\0' : *option_value) {
        case 'n':
            info->print_header = FALSE;
            break;
        case 'y':
            info->print_header = TRUE;
            break;
        default:
            return FALSE;
        }
        return TRUE;
    }

    if(0 == strcmp(option_name,"separator")) {
        switch(NULL == option_value ? '\0' : *option_value) {
        case '\0':
            return FALSE;
        case '/':
            switch(*++option_value) {
            case 't':
                info->separator = '\t';
                break;
            case 's':
                info->separator = ' ';
                break;
            default:
                info->separator = '\\';
            }
            break;
        default:
            info->separator = *option_value;
            break;
        }
        return TRUE;
    }

    if(0 == strcmp(option_name, "occurrence")) {
        switch(NULL == option_value ? '\0' : *option_value) {
        case 'f':
        case 'l':
        case 'a':
            info->occurrence = *option_value;
            break;
        default:
            return FALSE;
        }
        return TRUE;
    }

    if(0 == strcmp(option_name,"aggregator")) {
        switch(NULL == option_value ? '\0' : *option_value) {
        case '\0':
            return FALSE;
        case '/':
            switch(*++option_value) {
            case 's':
                info->aggregator = ' ';
                break;
            default:
                info->aggregator = '\\';
            }
            break;
        default:
            info->aggregator = *option_value;
            break;
        }
        return TRUE;
    }

    if(0 == strcmp(option_name, "quote")) {
        switch(NULL == option_value ? '\0' : *option_value) {
        default: /* Fall through */
        case '\0':
            info->quote='\0';
            return FALSE;
        case 'd':
            info->quote='"';
            break;
        case 's':
            info->quote='\'';
            break;
        case 'n':
            info->quote='\0';
            break;
        }
        return TRUE;
    }

    return FALSE;
}

void output_fields_list_options(FILE *fh)
{
    fprintf(fh, "TShark: The available options for field output \"E\" are:\n");
    fputs("header=y|n    Print field abbreviations as first line of output (def: N: no)\n", fh);
    fputs("separator=/t|/s|<character>   Set the separator to use;\n     \"/t\" = tab, \"/s\" = space (def: /t: tab)\n", fh);
    fputs("occurrence=f|l|a  Select the occurrence of a field to use;\n     \"f\" = first, \"l\" = last, \"a\" = all (def: a: all)\n", fh);
    fputs("aggregator=,|/s|<character>   Set the aggregator to use;\n     \",\" = comma, \"/s\" = space (def: ,: comma)\n", fh);
    fputs("quote=d|s|n   Print either d: double-quotes, s: single quotes or \n     n: no quotes around field values (def: n: none)\n", fh);
}


void write_fields_preamble(output_fields_t* fields, FILE *fh)
{
    gsize i;

    g_assert(fields);
    g_assert(fh);

    if(!fields->print_header) {
        return;
    }

    for(i = 0; i < fields->fields->len; ++i) {
        const gchar* field = (const gchar *)g_ptr_array_index(fields->fields,i);
        if(i != 0 ) {
            fputc(fields->separator, fh);
        }
    	fputs(field, fh);
    }
    fputc('\n', fh);
}

static void proto_tree_get_node_field_values(proto_node *node, gpointer data)
{
    write_field_data_t *call_data;
    field_info *fi;
    gpointer field_index;

    call_data = (write_field_data_t *)data;
    fi = PNODE_FINFO(node);

    g_assert(fi && "dissection with an invisible proto tree?");

    field_index = g_hash_table_lookup(call_data->fields->field_indicies, fi->hfinfo->abbrev);
    if(NULL != field_index) {
        const gchar* value;

        value = get_node_field_value(fi, call_data->edt); /* ep_alloced string */

        if(NULL != value && '\0' != *value) {
            guint actual_index;
            actual_index = GPOINTER_TO_UINT(field_index);
            /* Unwrap change made to disambiguiate zero / null */
            if ( call_data->fields->field_values[actual_index - 1] == NULL ) {
                call_data->fields->field_values[actual_index - 1] = ep_strbuf_new(value);
            } else if ( call_data->fields->occurrence == 'l' ) {
                /* print only the value of the last occurrence of the field */
                ep_strbuf_printf(call_data->fields->field_values[actual_index - 1],"%s",value);
            } else if ( call_data->fields->occurrence == 'a' ) {
                /* print the value of all accurrences of the field */
                ep_strbuf_append_printf(call_data->fields->field_values[actual_index - 1],
                    "%c%s",call_data->fields->aggregator,value);
            }
        }
    }

    /* Recurse here. */
    if (node->first_child != NULL) {
        proto_tree_children_foreach(node, proto_tree_get_node_field_values,
                                    call_data);
    }
}

void proto_tree_write_fields(output_fields_t* fields, epan_dissect_t *edt, FILE *fh)
{
    gsize i;

    write_field_data_t data;

    g_assert(fields);
    g_assert(edt);
    g_assert(fh);

    data.fields = fields;
    data.edt = edt;

    if(NULL == fields->field_indicies) {
        /* Prepare a lookup table from string abbreviation for field to its index. */
        fields->field_indicies = g_hash_table_new(g_str_hash, g_str_equal);

        i = 0;
        while( i < fields->fields->len) {
            gchar* field = (gchar *)g_ptr_array_index(fields->fields, i);
             /* Store field indicies +1 so that zero is not a valid value,
              * and can be distinguished from NULL as a pointer.
              */
            ++i;
            g_hash_table_insert(fields->field_indicies, field, GUINT_TO_POINTER(i));
        }
    }

    /* Buffer to store values for this packet */
    fields->field_values = ep_alloc_array0(emem_strbuf_t*, fields->fields->len);

    proto_tree_children_foreach(edt->tree, proto_tree_get_node_field_values,
                                &data);

    for(i = 0; i < fields->fields->len; ++i) {
        if(0 != i) {
            fputc(fields->separator, fh);
        }
        if(NULL != fields->field_values[i]) {
            if(fields->quote != '\0') {
                fputc(fields->quote, fh);
            }
            fputs(fields->field_values[i]->str, fh);
            if(fields->quote != '\0') {
                fputc(fields->quote, fh);
            }
        }
    }
}

void write_fields_finale(output_fields_t* fields _U_ , FILE *fh _U_)
{
    /* Nothing to do */
}

/* Returns an ep_alloced string or a static constant*/
const gchar* get_node_field_value(field_info* fi, epan_dissect_t* edt)
{
    if (fi->hfinfo->id == hf_text_only) {
        /* Text label.
         * Get the text */
        if (fi->rep) {
            return fi->rep->representation;
        }
        else {
            return get_field_hex_value(edt->pi.data_src, fi);
        }
    }
    else if (fi->hfinfo->id == proto_data) {
        /* Uninterpreted data, i.e., the "Data" protocol, is
         * printed as a field instead of a protocol. */
        return get_field_hex_value(edt->pi.data_src, fi);
    }
    else {
        /* Normal protocols and fields */
        gchar      *dfilter_string;
        size_t      chop_len;

        switch (fi->hfinfo->type)
        {
        case FT_PROTOCOL:
            /* Print out the full details for the protocol. */
            if (fi->rep) {
                return fi->rep->representation;
            } else {
                /* Just print out the protocol abbreviation */
                return fi->hfinfo->abbrev;
            }
        case FT_NONE:
            /* Return "1" so that the presence of a field of type
             * FT_NONE can be checked when using -T fields */
            return "1";
        default:
            /* XXX - this is a hack until we can just call
             * fvalue_to_string_repr() for *all* FT_* types. */
            dfilter_string = proto_construct_match_selected_string(fi,
                edt);
            if (dfilter_string != NULL) {
                chop_len = strlen(fi->hfinfo->abbrev) + 4; /* for " == " */

                /* XXX - Remove double-quotes. Again, once we
                 * can call fvalue_to_string_repr(), we can
                 * ask it not to produce the version for
                 * display-filters, and thus, no
                 * double-quotes. */
                if (dfilter_string[strlen(dfilter_string)-1] == '"') {
                    dfilter_string[strlen(dfilter_string)-1] = '\0';
                    chop_len++;
                }

                return &(dfilter_string[chop_len]);
            } else {
                return get_field_hex_value(edt->pi.data_src, fi);
            }
        }
    }
}

static const gchar*
get_field_hex_value(GSList* src_list, field_info *fi)
{
    const guint8 *pd;

    if (!fi->ds_tvb)
        return NULL;

    if (fi->length > tvb_length_remaining(fi->ds_tvb, fi->start)) {
        return "field length invalid!";
    }

    /* Find the data for this field. */
    pd = get_field_data(src_list, fi);

    if (pd) {
        int i;
        gchar* buffer;
        gchar* p;
        int len;
        const int chars_per_byte = 2;

        len = chars_per_byte * fi->length;
        buffer = ep_alloc_array(gchar, len + 1);
        buffer[len] = '\0'; /* Ensure NULL termination in bad cases */
        p = buffer;
        /* Print a simple hex dump */
        for (i = 0 ; i < fi->length; i++) {
            g_snprintf(p, chars_per_byte+1, "%02x", pd[i]);
            p += chars_per_byte;
        }
        return buffer;
    } else {
        return NULL;
    }
}