summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/common/zip/xarvfs.cpp
blob: 571a51c7164dc88b38c2109d237e838cdf442b1d (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
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
/* $Id: xarvfs.cpp $ */
/** @file
 * IPRT - XAR Virtual Filesystem.
 */

/*
 * Copyright (C) 2010-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * 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, in version 3 of the
 * License.
 *
 * 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, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include "internal/iprt.h"
#include <iprt/zip.h>

#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/ctype.h>
#include <iprt/err.h>
#include <iprt/md5.h>
#include <iprt/poll.h>
#include <iprt/file.h>
#include <iprt/sha.h>
#include <iprt/string.h>
#include <iprt/vfs.h>
#include <iprt/vfslowlevel.h>
#include <iprt/formats/xar.h>
#include <iprt/cpp/xml.h>


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** @name Hash state
 * @{ */
#define RTZIPXAR_HASH_PENDING           0
#define RTZIPXAR_HASH_OK                1
#define RTZIPXAR_HASH_FAILED_ARCHIVED   2
#define RTZIPXAR_HASH_FAILED_EXTRACTED  3
/** @} */


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Hash digest value union for the supported XAR hash functions.
 * @todo This could be generalized in iprt/checksum.h or somewhere.
 */
typedef union RTZIPXARHASHDIGEST
{
    uint8_t abMd5[RTMD5_HASH_SIZE];
    uint8_t abSha1[RTSHA1_HASH_SIZE];
} RTZIPXARHASHDIGEST;
/** Pointer to a XAR hash digest union. */
typedef RTZIPXARHASHDIGEST *PRTZIPXARHASHDIGEST;
/** Pointer to a const XAR hash digest union. */
typedef RTZIPXARHASHDIGEST *PCRTZIPXARHASHDIGEST;

/**
 * Hash context union.
 */
typedef union RTZIPXARHASHCTX
{
    RTMD5CONTEXT    Md5;
    RTSHA1CONTEXT   Sha1;
} RTZIPXARHASHCTX;
/** Pointer to a hash context union. */
typedef RTZIPXARHASHCTX *PRTZIPXARHASHCTX;

/**
 * XAR reader instance data.
 */
typedef struct RTZIPXARREADER
{
    /** The TOC XML element. */
    xml::ElementNode const *pToc;
    /** The TOC XML document. */
    xml::Document          *pDoc;

    /** The current file. */
    xml::ElementNode const *pCurFile;
    /** The depth of the current file, with 0 being the root level. */
    uint32_t                cCurDepth;
} RTZIPXARREADER;
/** Pointer to the XAR reader instance data. */
typedef RTZIPXARREADER *PRTZIPXARREADER;

/**
 * Xar directory, character device, block device, fifo socket or symbolic link.
 */
typedef struct RTZIPXARBASEOBJ
{
    /** The file TOC element. */
    xml::ElementNode const *pFileElem;
    /** RTFS_TYPE_XXX value for the object. */
    RTFMODE                 fModeType;
} RTZIPXARBASEOBJ;
/** Pointer to a XAR filesystem stream base object. */
typedef RTZIPXARBASEOBJ *PRTZIPXARBASEOBJ;


/**
 * XAR data encoding.
 */
typedef enum RTZIPXARENCODING
{
    RTZIPXARENCODING_INVALID = 0,
    RTZIPXARENCODING_STORE,
    RTZIPXARENCODING_GZIP,
    RTZIPXARENCODING_UNSUPPORTED,
    RTZIPXARENCODING_END
} RTZIPXARENCODING;


/**
 * Data stream attributes.
 */
typedef struct RTZIPXARDATASTREAM
{
    /** Offset of the data in the stream.
     * @remarks The I/O stream and file constructor will adjust this so that it
     *          relative to the start of the input stream, instead of the first byte
     *          after the TOC. */
    RTFOFF                  offData;
    /** The size of the archived data. */
    RTFOFF                  cbDataArchived;
    /** The size of the extracted data. */
    RTFOFF                  cbDataExtracted;
    /** The encoding of the archived ata. */
    RTZIPXARENCODING        enmEncoding;
    /** The hash function used for the archived data. */
    uint8_t                 uHashFunArchived;
    /** The hash function used for the extracted data. */
    uint8_t                 uHashFunExtracted;
    /** The digest of the archived data. */
    RTZIPXARHASHDIGEST      DigestArchived;
    /** The digest of the extracted data. */
    RTZIPXARHASHDIGEST      DigestExtracted;
} RTZIPXARDATASTREAM;
/** Pointer to XAR data stream attributes. */
typedef RTZIPXARDATASTREAM *PRTZIPXARDATASTREAM;


/**
 * Xar file represented as a VFS I/O stream.
 */
typedef struct RTZIPXARIOSTREAM
{
    /** The basic XAR object data. */
    RTZIPXARBASEOBJ         BaseObj;
    /** The attributes of the primary data stream. */
    RTZIPXARDATASTREAM      DataAttr;
    /** The current file position in the archived file. */
    RTFOFF                  offCurPos;
    /** The input I/O stream. */
    RTVFSIOSTREAM           hVfsIos;
    /** Set if we've reached the end of the file or if the next object in the
     * file system stream has been requested. */
    bool                    fEndOfStream;
    /** Whether the stream is seekable. */
    bool                    fSeekable;
    /** Hash state. */
    uint8_t                 uHashState;
    /** The size of the file that we've currently hashed.
     * We use this to check whether the user skips part of the file while reading
     * and when to compare the digests. */
    RTFOFF                  cbDigested;
    /** The digest of the archived data. */
    RTZIPXARHASHCTX         CtxArchived;
    /** The digest of the extracted data. */
    RTZIPXARHASHCTX         CtxExtracted;
} RTZIPXARIOSTREAM;
/** Pointer to a the private data of a XAR file I/O stream. */
typedef RTZIPXARIOSTREAM *PRTZIPXARIOSTREAM;


/**
 * Xar file represented as a VFS file.
 */
typedef struct RTZIPXARFILE
{
    /** The XAR I/O stream data. */
    RTZIPXARIOSTREAM        Ios;
    /** The input file. */
    RTVFSFILE               hVfsFile;
} RTZIPXARFILE;
/** Pointer to the private data of a XAR file. */
typedef RTZIPXARFILE *PRTZIPXARFILE;


/**
 * Decompressed I/O stream instance.
 *
 * This is just a front that checks digests and other sanity stuff.
 */
typedef struct RTZIPXARDECOMPIOS
{
    /** The decompressor I/O stream. */
    RTVFSIOSTREAM           hVfsIosDecompressor;
    /** The raw XAR I/O stream. */
    RTVFSIOSTREAM           hVfsIosRaw;
    /** Pointer to the raw XAR I/O stream instance data. */
    PRTZIPXARIOSTREAM       pIosRaw;
    /** The current file position in the archived file. */
    RTFOFF                  offCurPos;
    /** The hash function to use on the extracted data. */
    uint8_t                 uHashFunExtracted;
    /** Hash state on the extracted data. */
    uint8_t                 uHashState;
    /** The digest of the extracted data. */
    RTZIPXARHASHCTX         CtxExtracted;
    /** The expected digest of the extracted data. */
    RTZIPXARHASHDIGEST      DigestExtracted;
} RTZIPXARDECOMPIOS;
/** Pointer to the private data of a XAR decompressed I/O stream. */
typedef RTZIPXARDECOMPIOS *PRTZIPXARDECOMPIOS;


/**
 * Xar filesystem stream private data.
 */
typedef struct RTZIPXARFSSTREAM
{
    /** The input I/O stream. */
    RTVFSIOSTREAM           hVfsIos;
    /** The input file, if the stream is actually a file. */
    RTVFSFILE               hVfsFile;

    /** The start offset in the input I/O stream. */
    RTFOFF                  offStart;
    /** The zero offset in the file which all others are relative to. */
    RTFOFF                  offZero;

    /** The hash function we're using (XAR_HASH_XXX). */
    uint8_t                 uHashFunction;
    /** The size of the digest produced by the hash function we're using. */
    uint8_t                 cbHashDigest;

    /** Set if we've reached the end of the stream. */
    bool                    fEndOfStream;
    /** Set if we've encountered a fatal error. */
    int                     rcFatal;


    /** The XAR reader instance data. */
    RTZIPXARREADER          XarReader;
} RTZIPXARFSSTREAM;
/** Pointer to a the private data of a XAR filesystem stream. */
typedef RTZIPXARFSSTREAM *PRTZIPXARFSSTREAM;


/**
 * Hashes a block of data.
 *
 * @param   uHashFunction   The hash function to use.
 * @param   pvSrc           The data to hash.
 * @param   cbSrc           The size of the data to hash.
 * @param   pHashDigest     Where to return the message digest.
 */
static void rtZipXarCalcHash(uint32_t uHashFunction, void const *pvSrc, size_t cbSrc, PRTZIPXARHASHDIGEST pHashDigest)
{
    switch (uHashFunction)
    {
        case XAR_HASH_SHA1:
            RTSha1(pvSrc, cbSrc, pHashDigest->abSha1);
            break;
        case XAR_HASH_MD5:
            RTMd5(pvSrc, cbSrc, pHashDigest->abMd5);
            break;
        default:
            RT_ZERO(*pHashDigest);
            break;
    }
}


/**
 * Initializes a hash context.
 *
 * @param   pCtx            Pointer to the context union.
 * @param   uHashFunction   The hash function to use.
 */
static void rtZipXarHashInit(PRTZIPXARHASHCTX pCtx, uint32_t uHashFunction)
{
    switch (uHashFunction)
    {
        case XAR_HASH_SHA1:
            RTSha1Init(&pCtx->Sha1);
            break;
        case XAR_HASH_MD5:
            RTMd5Init(&pCtx->Md5);;
            break;
        default:
            RT_ZERO(*pCtx);
            break;
    }
}


/**
 * Adds a block to the hash calculation.
 *
 * @param   pCtx            Pointer to the context union.
 * @param   uHashFunction   The hash function to use.
 * @param   pvSrc           The data to add to the hash.
 * @param   cbSrc           The size of the data.
 */
static void rtZipXarHashUpdate(PRTZIPXARHASHCTX pCtx, uint32_t uHashFunction, void const *pvSrc, size_t cbSrc)
{
    switch (uHashFunction)
    {
        case XAR_HASH_SHA1:
            RTSha1Update(&pCtx->Sha1, pvSrc, cbSrc);
            break;
        case XAR_HASH_MD5:
            RTMd5Update(&pCtx->Md5, pvSrc, cbSrc);
            break;
    }
}


/**
 * Finalizes the hash, producing the message digest.
 *
 * @param   pCtx            Pointer to the context union.
 * @param   uHashFunction   The hash function to use.
 * @param   pHashDigest     Where to return the message digest.
 */
static void rtZipXarHashFinal(PRTZIPXARHASHCTX pCtx, uint32_t uHashFunction, PRTZIPXARHASHDIGEST pHashDigest)
{
    switch (uHashFunction)
    {
        case XAR_HASH_SHA1:
            RTSha1Final(&pCtx->Sha1, pHashDigest->abSha1);
            break;
        case XAR_HASH_MD5:
            RTMd5Final(pHashDigest->abMd5, &pCtx->Md5);
            break;
        default:
            RT_ZERO(*pHashDigest);
            break;
    }
}


/**
 * Compares two hash digests.
 *
 * @returns true if equal, false if not.
 * @param   uHashFunction   The hash function to use.
 * @param   pHashDigest1    The first hash digest.
 * @param   pHashDigest2    The second hash digest.
 */
static bool rtZipXarHashIsEqual(uint32_t uHashFunction, PRTZIPXARHASHDIGEST pHashDigest1, PRTZIPXARHASHDIGEST pHashDigest2)
{
    switch (uHashFunction)
    {
        case XAR_HASH_SHA1:
            return memcmp(pHashDigest1->abSha1, pHashDigest2->abSha1, sizeof(pHashDigest1->abSha1)) == 0;
        case XAR_HASH_MD5:
            return memcmp(pHashDigest1->abMd5, pHashDigest2->abMd5, sizeof(pHashDigest1->abMd5)) == 0;
        default:
            return true;
    }
}


/**
 * Gets the 'offset', 'size' and optionally 'length' sub elements.
 *
 * @returns IPRT status code.
 * @param   pElement            The parent element.
 * @param   poff                Where to return the offset value.
 * @param   pcbSize             Where to return the size value.
 * @param   pcbLength           Where to return the length value, optional.
 */
static int rtZipXarGetOffsetSizeLengthFromElem(xml::ElementNode const *pElement,
                                               PRTFOFF poff, PRTFOFF pcbSize, PRTFOFF pcbLength)
{
    /*
     * The offset.
     */
    xml::ElementNode const *pElem = pElement->findChildElement("offset");
    if (!pElem)
        return VERR_XAR_MISSING_OFFSET_ELEMENT;
    const char *pszValue = pElem->getValue();
    if (!pszValue)
        return VERR_XAR_BAD_OFFSET_ELEMENT;

    int rc = RTStrToInt64Full(pszValue, 0, poff);
    if (   RT_FAILURE(rc)
        || rc == VWRN_NUMBER_TOO_BIG
        || *poff > RTFOFF_MAX / 2 /* make sure to not overflow calculating offsets. */
        || *poff < 0)
        return VERR_XAR_BAD_OFFSET_ELEMENT;

    /*
     * The 'size' stored in the archive.
     */
    pElem = pElement->findChildElement("size");
    if (!pElem)
        return VERR_XAR_MISSING_SIZE_ELEMENT;

    pszValue = pElem->getValue();
    if (!pszValue)
        return VERR_XAR_BAD_SIZE_ELEMENT;

    rc = RTStrToInt64Full(pszValue, 0, pcbSize);
    if (   RT_FAILURE(rc)
        || rc == VWRN_NUMBER_TOO_BIG
        || *pcbSize >= RTFOFF_MAX - _1M
        || *pcbSize < 0)
        return VERR_XAR_BAD_SIZE_ELEMENT;
    AssertCompile(RTFOFF_MAX == UINT64_MAX / 2);

    /*
     * The 'length' of the uncompressed data.  Not present for checksums, so
     * the caller might not want it.
     */
    if (pcbLength)
    {
        pElem = pElement->findChildElement("length");
        if (!pElem)
            return VERR_XAR_MISSING_LENGTH_ELEMENT;

        pszValue = pElem->getValue();
        if (!pszValue)
            return VERR_XAR_BAD_LENGTH_ELEMENT;

        rc = RTStrToInt64Full(pszValue, 0, pcbLength);
        if (   RT_FAILURE(rc)
            || rc == VWRN_NUMBER_TOO_BIG
            || *pcbLength >= RTFOFF_MAX - _1M
            || *pcbLength < 0)
            return VERR_XAR_BAD_LENGTH_ELEMENT;
        AssertCompile(RTFOFF_MAX == UINT64_MAX / 2);
    }

    return VINF_SUCCESS;
}


/**
 * Convers a checksum style value into a XAR hash function number.
 *
 * @returns IPRT status code.
 * @param   pszStyle        The XAR checksum style.
 * @param   puHashFunction  Where to return the hash function number on success.
 */
static int rtZipXarParseChecksumStyle(const char *pszStyle, uint8_t *puHashFunction)
{
    size_t cchStyle = strlen(pszStyle);
    if (   cchStyle == 4
        && (pszStyle[0] == 's' || pszStyle[0] == 'S')
        && (pszStyle[1] == 'h' || pszStyle[1] == 'H')
        && (pszStyle[2] == 'a' || pszStyle[2] == 'A')
        &&  pszStyle[3] == '1' )
        *puHashFunction = XAR_HASH_SHA1;
    else if (   cchStyle == 3
             && (pszStyle[0] == 'm' || pszStyle[0] == 'M')
             && (pszStyle[1] == 'd' || pszStyle[1] == 'D')
             &&  pszStyle[2] == '5' )
        *puHashFunction = XAR_HASH_MD5;
    else if (   cchStyle == 4
             && (pszStyle[0] == 'n' || pszStyle[0] == 'N')
             && (pszStyle[1] == 'o' || pszStyle[1] == 'O')
             && (pszStyle[2] == 'n' || pszStyle[2] == 'N')
             && (pszStyle[3] == 'e' || pszStyle[3] == 'E') )
        *puHashFunction = XAR_HASH_NONE;
    else
    {
        *puHashFunction = UINT8_MAX;
        return VERR_XAR_BAD_CHECKSUM_ELEMENT;
    }
    return VINF_SUCCESS;
}


/**
 * Parses a checksum element typically found under 'data'.
 *
 * @returns IPRT status code.
 * @param   pParentElem     The parent element ('data').
 * @param   pszName         The name of the element, like 'checksum-archived' or
 *                          'checksum-extracted'.
 * @param   puHashFunction  Where to return the XAR hash function number.
 * @param   pDigest         Where to return the expected message digest.
 */
static int rtZipXarParseChecksumElem(xml::ElementNode const *pParentElem, const char *pszName,
                                     uint8_t *puHashFunction, PRTZIPXARHASHDIGEST pDigest)
{
    /* Default is no checksum. */
    *puHashFunction = XAR_HASH_NONE;
    RT_ZERO(*pDigest);

    xml::ElementNode const *pChecksumElem = pParentElem->findChildElement(pszName);
    if (!pChecksumElem)
        return VINF_SUCCESS;

    /* The style. */
    const char *pszStyle = pChecksumElem->findAttributeValue("style");
    if (!pszStyle)
        return VERR_XAR_BAD_CHECKSUM_ELEMENT;
    int rc = rtZipXarParseChecksumStyle(pszStyle, puHashFunction);
    if (RT_FAILURE(rc))
        return rc;

    if (*puHashFunction == XAR_HASH_NONE)
        return VINF_SUCCESS;

    /* The digest. */
    const char *pszDigest = pChecksumElem->getValue();
    if (!pszDigest)
        return VERR_XAR_BAD_CHECKSUM_ELEMENT;

    switch (*puHashFunction)
    {
        case XAR_HASH_SHA1:
            rc = RTSha1FromString(pszDigest, pDigest->abSha1);
            break;
        case XAR_HASH_MD5:
            rc = RTMd5FromString(pszDigest, pDigest->abMd5);
            break;
        default:
            rc = VERR_INTERNAL_ERROR_2;
    }
    return rc;
}


/**
 * Gets all the attributes of the primary data stream.
 *
 * @returns IPRT status code.
 * @param   pFileElem           The file element, we'll be parsing the 'data'
 *                              sub element of this.
 * @param   pDataAttr           Where to return the attributes.
 */
static int rtZipXarGetDataStreamAttributes(xml::ElementNode const *pFileElem, PRTZIPXARDATASTREAM pDataAttr)
{
    /*
     * Get the data element.
     */
    xml::ElementNode const *pDataElem = pFileElem->findChildElement("data");
    if (!pDataElem)
        return VERR_XAR_MISSING_DATA_ELEMENT;

    /*
     * Checksums.
     */
    int rc = rtZipXarParseChecksumElem(pDataElem, "extracted-checksum",
                                       &pDataAttr->uHashFunExtracted, &pDataAttr->DigestExtracted);
    if (RT_FAILURE(rc))
        return rc;
    rc = rtZipXarParseChecksumElem(pDataElem, "archived-checksum",
                                   &pDataAttr->uHashFunArchived, &pDataAttr->DigestArchived);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * The encoding.
     */
    const char *pszEncoding = pDataElem->findChildElementAttributeValueP("encoding", "style");
    if (!pszEncoding)
        return VERR_XAR_NO_ENCODING;
    if (!strcmp(pszEncoding, "application/octet-stream"))
        pDataAttr->enmEncoding = RTZIPXARENCODING_STORE;
    else if (!strcmp(pszEncoding, "application/x-gzip"))
        pDataAttr->enmEncoding = RTZIPXARENCODING_GZIP;
    else
        pDataAttr->enmEncoding = RTZIPXARENCODING_UNSUPPORTED;

    /*
     * The data offset and the compressed and uncompressed sizes.
     */
    rc = rtZipXarGetOffsetSizeLengthFromElem(pDataElem, &pDataAttr->offData,
                                             &pDataAttr->cbDataExtracted, &pDataAttr->cbDataArchived);
    if (RT_FAILURE(rc))
        return rc;

    /* No zero padding or other alignment crap, please. */
    if (   pDataAttr->enmEncoding == RTZIPXARENCODING_STORE
        && pDataAttr->cbDataExtracted != pDataAttr->cbDataArchived)
        return VERR_XAR_ARCHIVED_AND_EXTRACTED_SIZES_MISMATCH;

    return VINF_SUCCESS;
}


/**
 * Parses a timestamp.
 *
 * We consider all timestamps optional, and will only fail (return @c false) on
 * parse errors.  If the specified element isn't found, we'll return epoc time.
 *
 * @returns boolean success indicator.
 * @param   pParent             The parent element (typically 'file').
 * @param   pszChild            The name of the child element.
 * @param   pTimeSpec           Where to return the timespec on success.
 */
static bool rtZipXarParseTimestamp(const xml::ElementNode *pParent, const char *pszChild, PRTTIMESPEC pTimeSpec)
{
    const char *pszValue = pParent->findChildElementValueP(pszChild);
    if (pszValue)
    {
        if (RTTimeSpecFromString(pTimeSpec, pszValue))
            return true;
        return false;
    }
    RTTimeSpecSetNano(pTimeSpec, 0);
    return true;
}


/**
 * Gets the next file element in the TOC.
 *
 * @returns Pointer to the next file, NULL if we've reached the end.
 * @param   pCurFile            The current element.
 * @param   pcCurDepth          Depth gauge we update when decending and
 *                              acending thru the tree.
 */
static xml::ElementNode const *rtZipXarGetNextFileElement(xml::ElementNode const *pCurFile, uint32_t *pcCurDepth)
{
    /*
     * Consider children first.
     */
    xml::ElementNode const *pChild = pCurFile->findChildElement("file");
    if (pChild)
    {
        *pcCurDepth += 1;
        return pChild;
    }

    /*
     * Siblings and ancestor siblings.
     */
    for (;;)
    {
        xml::ElementNode const *pSibling = pCurFile->findNextSibilingElement("file");
        if (pSibling != NULL)
            return pSibling;

        if (*pcCurDepth == 0)
            break;
        *pcCurDepth -= 1;
        pCurFile = static_cast<const xml::ElementNode *>(pCurFile->getParent());
        AssertBreak(pCurFile);
        Assert(pCurFile->nameEquals("file"));
    }

    return NULL;
}



/*
 *
 * T h e   V F S   F i l e s y s t e m   S t r e a m   B i t s.
 * T h e   V F S   F i l e s y s t e m   S t r e a m   B i t s.
 * T h e   V F S   F i l e s y s t e m   S t r e a m   B i t s.
 *
 */


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtZipXarFssBaseObj_Close(void *pvThis)
{
    PRTZIPXARBASEOBJ pThis = (PRTZIPXARBASEOBJ)pvThis;

    /* Currently there is nothing we really have to do here. */
    NOREF(pThis);

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipXarFssBaseObj_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPXARBASEOBJ pThis = (PRTZIPXARBASEOBJ)pvThis;

    /*
     * Get the common data.
     */

    /* Sizes. */
    if (pThis->fModeType == RTFS_TYPE_FILE)
    {
        PRTZIPXARIOSTREAM pThisIos = RT_FROM_MEMBER(pThis, RTZIPXARIOSTREAM, BaseObj);
        pObjInfo->cbObject    = pThisIos->DataAttr.cbDataArchived; /* Modified by decomp ios. */
        pObjInfo->cbAllocated = pThisIos->DataAttr.cbDataArchived;
    }
    else
    {
        pObjInfo->cbObject    = 0;
        pObjInfo->cbAllocated = 0;
    }

    /* The file mode. */
    if (RT_UNLIKELY(!pThis->pFileElem->getChildElementValueDefP("mode", 0755, &pObjInfo->Attr.fMode)))
        return VERR_XAR_BAD_FILE_MODE;
    if (pObjInfo->Attr.fMode & RTFS_TYPE_MASK)
        return VERR_XAR_BAD_FILE_MODE;
    pObjInfo->Attr.fMode &= RTFS_UNIX_MASK & ~RTFS_TYPE_MASK;
    pObjInfo->Attr.fMode |= pThis->fModeType;

    /* File times. */
    if (RT_UNLIKELY(!rtZipXarParseTimestamp(pThis->pFileElem, "atime", &pObjInfo->AccessTime)))
        return VERR_XAR_BAD_FILE_TIMESTAMP;
    if (RT_UNLIKELY(!rtZipXarParseTimestamp(pThis->pFileElem, "ctime", &pObjInfo->ChangeTime)))
        return VERR_XAR_BAD_FILE_TIMESTAMP;
    if (RT_UNLIKELY(!rtZipXarParseTimestamp(pThis->pFileElem, "mtime", &pObjInfo->ModificationTime)))
        return VERR_XAR_BAD_FILE_TIMESTAMP;
    pObjInfo->BirthTime = RTTimeSpecGetNano(&pObjInfo->AccessTime) <= RTTimeSpecGetNano(&pObjInfo->ChangeTime)
                        ? pObjInfo->AccessTime : pObjInfo->ChangeTime;
    if (RTTimeSpecGetNano(&pObjInfo->BirthTime) > RTTimeSpecGetNano(&pObjInfo->ModificationTime))
        pObjInfo->BirthTime = pObjInfo->ModificationTime;

    /*
     * Copy the desired data.
     */
    switch (enmAddAttr)
    {
        case RTFSOBJATTRADD_NOTHING:
        case RTFSOBJATTRADD_UNIX:
            pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX;
            if (RT_UNLIKELY(!pThis->pFileElem->getChildElementValueDefP("uid", 0, &pObjInfo->Attr.u.Unix.uid)))
                return VERR_XAR_BAD_FILE_UID;
            if (RT_UNLIKELY(!pThis->pFileElem->getChildElementValueDefP("gid", 0, &pObjInfo->Attr.u.Unix.gid)))
                return VERR_XAR_BAD_FILE_GID;
            if (RT_UNLIKELY(!pThis->pFileElem->getChildElementValueDefP("deviceno", 0, &pObjInfo->Attr.u.Unix.INodeIdDevice)))
                return VERR_XAR_BAD_FILE_DEVICE_NO;
            if (RT_UNLIKELY(!pThis->pFileElem->getChildElementValueDefP("inode", 0, &pObjInfo->Attr.u.Unix.INodeId)))
                return VERR_XAR_BAD_FILE_INODE;
            pObjInfo->Attr.u.Unix.cHardlinks    = 1;
            pObjInfo->Attr.u.Unix.fFlags        = 0;
            pObjInfo->Attr.u.Unix.GenerationId  = 0;
            pObjInfo->Attr.u.Unix.Device        = 0;
            break;

        case RTFSOBJATTRADD_UNIX_OWNER:
        {
            pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_OWNER;
            if (RT_UNLIKELY(!pThis->pFileElem->getChildElementValueDefP("uid", 0, &pObjInfo->Attr.u.Unix.uid)))
                return VERR_XAR_BAD_FILE_UID;
            const char *pszUser = pThis->pFileElem->findChildElementValueP("user");
            if (pszUser)
                RTStrCopy(pObjInfo->Attr.u.UnixOwner.szName, sizeof(pObjInfo->Attr.u.UnixOwner.szName), pszUser);
            else
                pObjInfo->Attr.u.UnixOwner.szName[0] = '\0';
            break;
        }

        case RTFSOBJATTRADD_UNIX_GROUP:
        {
            pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_UNIX_GROUP;
            if (RT_UNLIKELY(!pThis->pFileElem->getChildElementValueDefP("gid", 0, &pObjInfo->Attr.u.Unix.gid)))
                return VERR_XAR_BAD_FILE_GID;
            const char *pszGroup = pThis->pFileElem->findChildElementValueP("group");
            if (pszGroup)
                RTStrCopy(pObjInfo->Attr.u.UnixGroup.szName, sizeof(pObjInfo->Attr.u.UnixGroup.szName), pszGroup);
            else
                pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
            break;
        }

        case RTFSOBJATTRADD_EASIZE:
            pObjInfo->Attr.enmAdditional = RTFSOBJATTRADD_EASIZE;
            RT_ZERO(pObjInfo->Attr.u);
            break;

        default:
            return VERR_NOT_SUPPORTED;
    }

    return VINF_SUCCESS;
}


/**
 * Xar filesystem base object operations.
 */
static const RTVFSOBJOPS g_rtZipXarFssBaseObjOps =
{
    RTVFSOBJOPS_VERSION,
    RTVFSOBJTYPE_BASE,
    "XarFsStream::Obj",
    rtZipXarFssBaseObj_Close,
    rtZipXarFssBaseObj_QueryInfo,
    NULL,
    RTVFSOBJOPS_VERSION
};


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtZipXarFssIos_Close(void *pvThis)
{
    PRTZIPXARIOSTREAM pThis = (PRTZIPXARIOSTREAM)pvThis;

    RTVfsIoStrmRelease(pThis->hVfsIos);
    pThis->hVfsIos = NIL_RTVFSIOSTREAM;

    return rtZipXarFssBaseObj_Close(&pThis->BaseObj);
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipXarFssIos_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPXARIOSTREAM pThis = (PRTZIPXARIOSTREAM)pvThis;
    return rtZipXarFssBaseObj_QueryInfo(&pThis->BaseObj, pObjInfo, enmAddAttr);
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnRead}
 */
static DECLCALLBACK(int) rtZipXarFssIos_Read(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbRead)
{
    PRTZIPXARIOSTREAM pThis = (PRTZIPXARIOSTREAM)pvThis;
    AssertReturn(off >= -1, VERR_INVALID_PARAMETER);
    AssertReturn(pSgBuf->cSegs == 1, VERR_INVALID_PARAMETER);

    /*
     * Fend of reads beyond the end of the stream here.  If
     */
    if (off == -1)
        off = pThis->offCurPos;
    if (off < 0 || off > pThis->DataAttr.cbDataArchived)
        return VERR_EOF;
    if (pThis->fEndOfStream)
    {
        if (off >= pThis->DataAttr.cbDataArchived)
            return pcbRead ? VINF_EOF : VERR_EOF;
        if (!pThis->fSeekable)
            return VERR_SEEK_ON_DEVICE;
        pThis->fEndOfStream = false;
    }

    size_t cbToRead = pSgBuf->paSegs[0].cbSeg;
    uint64_t cbLeft = pThis->DataAttr.cbDataArchived - off;
    if (cbToRead > cbLeft)
    {
        if (!pcbRead)
            return VERR_EOF;
        cbToRead = (size_t)cbLeft;
    }

    /*
     * Do the reading.
     */
    size_t cbReadStack = 0;
    if (!pcbRead)
        pcbRead = &cbReadStack;
    int rc = RTVfsIoStrmReadAt(pThis->hVfsIos, off + pThis->DataAttr.offData, pSgBuf->paSegs[0].pvSeg,
                               cbToRead, fBlocking, pcbRead);

    /* Feed the hashes. */
    size_t cbActuallyRead = *pcbRead;
    if (pThis->uHashState == RTZIPXAR_HASH_PENDING)
    {
        if (pThis->offCurPos == pThis->cbDigested)
        {
            rtZipXarHashUpdate(&pThis->CtxArchived,  pThis->DataAttr.uHashFunArchived,  pSgBuf->paSegs[0].pvSeg, cbActuallyRead);
            rtZipXarHashUpdate(&pThis->CtxExtracted, pThis->DataAttr.uHashFunExtracted, pSgBuf->paSegs[0].pvSeg, cbActuallyRead);
            pThis->cbDigested += cbActuallyRead;
        }
        else if (   pThis->cbDigested > pThis->offCurPos
                 && pThis->cbDigested < (RTFOFF)(pThis->offCurPos + cbActuallyRead))
        {
            size_t      offHash = pThis->cbDigested - pThis->offCurPos;
            void const *pvHash  = (uint8_t const *)pSgBuf->paSegs[0].pvSeg + offHash;
            size_t      cbHash  = cbActuallyRead - offHash;
            rtZipXarHashUpdate(&pThis->CtxArchived,  pThis->DataAttr.uHashFunArchived,  pvHash, cbHash);
            rtZipXarHashUpdate(&pThis->CtxExtracted, pThis->DataAttr.uHashFunExtracted, pvHash, cbHash);
            pThis->cbDigested += cbHash;
        }
    }

    /* Update the file position. */
    pThis->offCurPos += cbActuallyRead;

    /*
     * Check for end of stream, also check the hash.
     */
    if (pThis->offCurPos >= pThis->DataAttr.cbDataArchived)
    {
        Assert(pThis->offCurPos == pThis->DataAttr.cbDataArchived);
        pThis->fEndOfStream = true;

        /* Check hash. */
        if (   pThis->uHashState == RTZIPXAR_HASH_PENDING
            && pThis->cbDigested == pThis->DataAttr.cbDataArchived)
        {
            RTZIPXARHASHDIGEST Digest;
            rtZipXarHashFinal(&pThis->CtxArchived, pThis->DataAttr.uHashFunArchived, &Digest);
            if (rtZipXarHashIsEqual(pThis->DataAttr.uHashFunArchived, &Digest, &pThis->DataAttr.DigestArchived))
            {
                rtZipXarHashFinal(&pThis->CtxExtracted, pThis->DataAttr.uHashFunExtracted, &Digest);
                if (rtZipXarHashIsEqual(pThis->DataAttr.uHashFunExtracted, &Digest, &pThis->DataAttr.DigestExtracted))
                    pThis->uHashState = RTZIPXAR_HASH_OK;
                else
                {
                    pThis->uHashState = RTZIPXAR_HASH_FAILED_EXTRACTED;
                    rc = VERR_XAR_EXTRACTED_HASH_MISMATCH;
                }
            }
            else
            {
                pThis->uHashState = RTZIPXAR_HASH_FAILED_ARCHIVED;
                rc = VERR_XAR_ARCHIVED_HASH_MISMATCH;
            }
        }
        else if (pThis->uHashState == RTZIPXAR_HASH_FAILED_ARCHIVED)
            rc = VERR_XAR_ARCHIVED_HASH_MISMATCH;
        else if (pThis->uHashState == RTZIPXAR_HASH_FAILED_EXTRACTED)
            rc = VERR_XAR_EXTRACTED_HASH_MISMATCH;
    }

    return rc;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnWrite}
 */
static DECLCALLBACK(int) rtZipXarFssIos_Write(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbWritten)
{
    /* Cannot write to a read-only I/O stream. */
    NOREF(pvThis); NOREF(off); NOREF(pSgBuf); NOREF(fBlocking); NOREF(pcbWritten);
    return VERR_ACCESS_DENIED;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnFlush}
 */
static DECLCALLBACK(int) rtZipXarFssIos_Flush(void *pvThis)
{
    /* It's a read only stream, nothing dirty to flush. */
    NOREF(pvThis);
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnPollOne}
 */
static DECLCALLBACK(int) rtZipXarFssIos_PollOne(void *pvThis, uint32_t fEvents, RTMSINTERVAL cMillies, bool fIntr,
                                                uint32_t *pfRetEvents)
{
    PRTZIPXARIOSTREAM pThis = (PRTZIPXARIOSTREAM)pvThis;

    /* When we've reached the end, read will be set to indicate it. */
    if (   (fEvents & RTPOLL_EVT_READ)
        && pThis->fEndOfStream)
    {
        int rc = RTVfsIoStrmPoll(pThis->hVfsIos, fEvents, 0, fIntr, pfRetEvents);
        if (RT_SUCCESS(rc))
            *pfRetEvents |= RTPOLL_EVT_READ;
        else
            *pfRetEvents = RTPOLL_EVT_READ;
        return VINF_SUCCESS;
    }

    return RTVfsIoStrmPoll(pThis->hVfsIos, fEvents, cMillies, fIntr, pfRetEvents);
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnTell}
 */
static DECLCALLBACK(int) rtZipXarFssIos_Tell(void *pvThis, PRTFOFF poffActual)
{
    PRTZIPXARIOSTREAM pThis = (PRTZIPXARIOSTREAM)pvThis;
    *poffActual = pThis->offCurPos;
    return VINF_SUCCESS;
}


/**
 * Xar I/O stream operations.
 */
static const RTVFSIOSTREAMOPS g_rtZipXarFssIosOps =
{
    { /* Obj */
        RTVFSOBJOPS_VERSION,
        RTVFSOBJTYPE_IO_STREAM,
        "XarFsStream::IoStream",
        rtZipXarFssIos_Close,
        rtZipXarFssIos_QueryInfo,
        NULL,
        RTVFSOBJOPS_VERSION
    },
    RTVFSIOSTREAMOPS_VERSION,
    0,
    rtZipXarFssIos_Read,
    rtZipXarFssIos_Write,
    rtZipXarFssIos_Flush,
    rtZipXarFssIos_PollOne,
    rtZipXarFssIos_Tell,
    NULL /*Skip*/,
    NULL /*ZeroFill*/,
    RTVFSIOSTREAMOPS_VERSION
};


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtZipXarFssFile_Close(void *pvThis)
{
    PRTZIPXARFILE pThis = (PRTZIPXARFILE)pvThis;

    RTVfsFileRelease(pThis->hVfsFile);
    pThis->hVfsFile = NIL_RTVFSFILE;

    return rtZipXarFssIos_Close(&pThis->Ios);
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnMode}
 */
static DECLCALLBACK(int) rtZipXarFssFile_SetMode(void *pvThis, RTFMODE fMode, RTFMODE fMask)
{
    NOREF(pvThis);
    NOREF(fMode);
    NOREF(fMask);
    return VERR_NOT_SUPPORTED;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetTimes}
 */
static DECLCALLBACK(int) rtZipXarFssFile_SetTimes(void *pvThis, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
                                                  PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
{
    NOREF(pvThis);
    NOREF(pAccessTime);
    NOREF(pModificationTime);
    NOREF(pChangeTime);
    NOREF(pBirthTime);
    return VERR_NOT_SUPPORTED;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetOwner}
 */
static DECLCALLBACK(int) rtZipXarFssFile_SetOwner(void *pvThis, RTUID uid, RTGID gid)
{
    NOREF(pvThis);
    NOREF(uid);
    NOREF(gid);
    return VERR_NOT_SUPPORTED;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnSeek}
 */
static DECLCALLBACK(int) rtZipXarFssFile_Seek(void *pvThis, RTFOFF offSeek, unsigned uMethod, PRTFOFF poffActual)
{
    PRTZIPXARFILE pThis = (PRTZIPXARFILE)pvThis;

    /* Recalculate the request to RTFILE_SEEK_BEGIN. */
    switch (uMethod)
    {
        case RTFILE_SEEK_BEGIN:
            break;
        case RTFILE_SEEK_CURRENT:
            offSeek += pThis->Ios.offCurPos;
            break;
        case RTFILE_SEEK_END:
            offSeek = pThis->Ios.DataAttr.cbDataArchived + offSeek;
            break;
        default:
            AssertFailedReturn(VERR_INVALID_PARAMETER);
    }

    /* Do limit checks. */
    if (offSeek < 0)
        offSeek = 0;
    else if (offSeek > pThis->Ios.DataAttr.cbDataArchived)
        offSeek = pThis->Ios.DataAttr.cbDataArchived;

    /* Apply and return. */
    pThis->Ios.fEndOfStream = (offSeek >= pThis->Ios.DataAttr.cbDataArchived);
    pThis->Ios.offCurPos    = offSeek;
    if (poffActual)
        *poffActual = offSeek;

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnQuerySize}
 */
static DECLCALLBACK(int) rtZipXarFssFile_QuerySize(void *pvThis, uint64_t *pcbFile)
{
    PRTZIPXARFILE pThis = (PRTZIPXARFILE)pvThis;
    *pcbFile = pThis->Ios.DataAttr.cbDataArchived;
    return VINF_SUCCESS;
}


/**
 * Xar file operations.
 */
static const RTVFSFILEOPS g_rtZipXarFssFileOps =
{
    { /* I/O stream */
        { /* Obj */
            RTVFSOBJOPS_VERSION,
            RTVFSOBJTYPE_FILE,
            "XarFsStream::File",
            rtZipXarFssFile_Close,
            rtZipXarFssIos_QueryInfo,
            NULL,
            RTVFSOBJOPS_VERSION
        },
        RTVFSIOSTREAMOPS_VERSION,
        RTVFSIOSTREAMOPS_FEAT_NO_SG,
        rtZipXarFssIos_Read,
        rtZipXarFssIos_Write,
        rtZipXarFssIos_Flush,
        rtZipXarFssIos_PollOne,
        rtZipXarFssIos_Tell,
        NULL /*Skip*/,
        NULL /*ZeroFill*/,
        RTVFSIOSTREAMOPS_VERSION
    },
    RTVFSFILEOPS_VERSION,
    0,
    { /* ObjSet */
        RTVFSOBJSETOPS_VERSION,
        RT_UOFFSETOF(RTVFSFILEOPS, ObjSet) - RT_UOFFSETOF(RTVFSFILEOPS, Stream.Obj),
        rtZipXarFssFile_SetMode,
        rtZipXarFssFile_SetTimes,
        rtZipXarFssFile_SetOwner,
        RTVFSOBJSETOPS_VERSION
    },
    rtZipXarFssFile_Seek,
    rtZipXarFssFile_QuerySize,
    NULL /*SetSize*/,
    NULL /*QueryMaxSize*/,
    RTVFSFILEOPS_VERSION,
};




/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtZipXarFssDecompIos_Close(void *pvThis)
{
    PRTZIPXARDECOMPIOS pThis = (PRTZIPXARDECOMPIOS)pvThis;

    RTVfsIoStrmRelease(pThis->hVfsIosDecompressor);
    pThis->hVfsIosDecompressor = NIL_RTVFSIOSTREAM;

    RTVfsIoStrmRelease(pThis->hVfsIosRaw);
    pThis->hVfsIosRaw = NIL_RTVFSIOSTREAM;
    pThis->pIosRaw = NULL;

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipXarFssDecompIos_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPXARDECOMPIOS pThis = (PRTZIPXARDECOMPIOS)pvThis;

    int rc = rtZipXarFssBaseObj_QueryInfo(&pThis->pIosRaw->BaseObj, pObjInfo, enmAddAttr);
    pObjInfo->cbObject = pThis->pIosRaw->DataAttr.cbDataExtracted;
    return rc;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnRead}
 */
static DECLCALLBACK(int) rtZipXarFssDecompIos_Read(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbRead)
{
    PRTZIPXARDECOMPIOS pThis = (PRTZIPXARDECOMPIOS)pvThis;
    AssertReturn(pSgBuf->cSegs == 1, VERR_INVALID_PARAMETER);

    /*
     * Enforce the cbDataExtracted limit.
     */
    if (pThis->offCurPos > pThis->pIosRaw->DataAttr.cbDataExtracted)
        return VERR_XAR_EXTRACTED_SIZE_EXCEEDED;

    /*
     * Read the data.
     *
     * ASSUMES the decompressor stream isn't seekable, so we don't have to
     * validate off wrt data digest updating.
     */
    int rc = RTVfsIoStrmReadAt(pThis->hVfsIosDecompressor, off, pSgBuf->paSegs[0].pvSeg, pSgBuf->paSegs[0].cbSeg,
                               fBlocking, pcbRead);
    if (RT_FAILURE(rc))
        return rc;

    /*
     * Hash the data.  When reaching the end match against the expected digest.
     */
    size_t cbActuallyRead = pcbRead ? *pcbRead : pSgBuf->paSegs[0].cbSeg;
    pThis->offCurPos += cbActuallyRead;
    rtZipXarHashUpdate(&pThis->CtxExtracted, pThis->uHashFunExtracted, pSgBuf->paSegs[0].pvSeg, cbActuallyRead);
    if (rc == VINF_EOF)
    {
        if (pThis->offCurPos == pThis->pIosRaw->DataAttr.cbDataExtracted)
        {
            if (pThis->uHashState == RTZIPXAR_HASH_PENDING)
            {
                RTZIPXARHASHDIGEST Digest;
                rtZipXarHashFinal(&pThis->CtxExtracted, pThis->uHashFunExtracted, &Digest);
                if (rtZipXarHashIsEqual(pThis->uHashFunExtracted, &Digest, &pThis->DigestExtracted))
                    pThis->uHashState = RTZIPXAR_HASH_OK;
                else
                {
                    pThis->uHashState = RTZIPXAR_HASH_FAILED_EXTRACTED;
                    rc = VERR_XAR_EXTRACTED_HASH_MISMATCH;
                }
            }
            else if (pThis->uHashState != RTZIPXAR_HASH_OK)
                rc = VERR_XAR_EXTRACTED_HASH_MISMATCH;
        }
        else
            rc = VERR_XAR_EXTRACTED_SIZE_EXCEEDED;

        /* Ensure that the raw stream is also at the end so that both
           message digests are checked. */
        if (RT_SUCCESS(rc))
        {
            if (   pThis->pIosRaw->offCurPos < pThis->pIosRaw->DataAttr.cbDataArchived
                || pThis->pIosRaw->uHashState == RTZIPXAR_HASH_PENDING)
                rc = VERR_XAR_UNUSED_ARCHIVED_DATA;
            else if (pThis->pIosRaw->uHashState != RTZIPXAR_HASH_OK)
                rc = VERR_XAR_ARCHIVED_HASH_MISMATCH;
        }
    }

    return rc;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnWrite}
 */
static DECLCALLBACK(int) rtZipXarFssDecompIos_Write(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbWritten)
{
    /* Cannot write to a read-only I/O stream. */
    NOREF(pvThis); NOREF(off); NOREF(pSgBuf); NOREF(fBlocking); NOREF(pcbWritten);
    return VERR_ACCESS_DENIED;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnFlush}
 */
static DECLCALLBACK(int) rtZipXarFssDecompIos_Flush(void *pvThis)
{
    /* It's a read only stream, nothing dirty to flush. */
    NOREF(pvThis);
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnPollOne}
 */
static DECLCALLBACK(int) rtZipXarFssDecompIos_PollOne(void *pvThis, uint32_t fEvents, RTMSINTERVAL cMillies, bool fIntr,
                                                      uint32_t *pfRetEvents)
{
    PRTZIPXARDECOMPIOS pThis = (PRTZIPXARDECOMPIOS)pvThis;
    return RTVfsIoStrmPoll(pThis->hVfsIosDecompressor, fEvents, cMillies, fIntr, pfRetEvents);
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnTell}
 */
static DECLCALLBACK(int) rtZipXarFssDecompIos_Tell(void *pvThis, PRTFOFF poffActual)
{
    PRTZIPXARDECOMPIOS pThis = (PRTZIPXARDECOMPIOS)pvThis;
    *poffActual = pThis->offCurPos;
    return VINF_SUCCESS;
}


/**
 * Xar I/O stream operations.
 */
static const RTVFSIOSTREAMOPS g_rtZipXarFssDecompIosOps =
{
    { /* Obj */
        RTVFSOBJOPS_VERSION,
        RTVFSOBJTYPE_IO_STREAM,
        "XarFsStream::DecompIoStream",
        rtZipXarFssDecompIos_Close,
        rtZipXarFssDecompIos_QueryInfo,
        NULL,
        RTVFSOBJOPS_VERSION
    },
    RTVFSIOSTREAMOPS_VERSION,
    0,
    rtZipXarFssDecompIos_Read,
    rtZipXarFssDecompIos_Write,
    rtZipXarFssDecompIos_Flush,
    rtZipXarFssDecompIos_PollOne,
    rtZipXarFssDecompIos_Tell,
    NULL /*Skip*/,
    NULL /*ZeroFill*/,
    RTVFSIOSTREAMOPS_VERSION
};




/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtZipXarFssSym_Close(void *pvThis)
{
    PRTZIPXARBASEOBJ pThis = (PRTZIPXARBASEOBJ)pvThis;
    return rtZipXarFssBaseObj_Close(pThis);
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipXarFssSym_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPXARBASEOBJ pThis = (PRTZIPXARBASEOBJ)pvThis;
    return rtZipXarFssBaseObj_QueryInfo(pThis, pObjInfo, enmAddAttr);
}

/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnMode}
 */
static DECLCALLBACK(int) rtZipXarFssSym_SetMode(void *pvThis, RTFMODE fMode, RTFMODE fMask)
{
    NOREF(pvThis); NOREF(fMode); NOREF(fMask);
    return VERR_ACCESS_DENIED;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetTimes}
 */
static DECLCALLBACK(int) rtZipXarFssSym_SetTimes(void *pvThis, PCRTTIMESPEC pAccessTime, PCRTTIMESPEC pModificationTime,
                                                 PCRTTIMESPEC pChangeTime, PCRTTIMESPEC pBirthTime)
{
    NOREF(pvThis); NOREF(pAccessTime); NOREF(pModificationTime); NOREF(pChangeTime); NOREF(pBirthTime);
    return VERR_ACCESS_DENIED;
}


/**
 * @interface_method_impl{RTVFSOBJSETOPS,pfnSetOwner}
 */
static DECLCALLBACK(int) rtZipXarFssSym_SetOwner(void *pvThis, RTUID uid, RTGID gid)
{
    NOREF(pvThis); NOREF(uid); NOREF(gid);
    return VERR_ACCESS_DENIED;
}


/**
 * @interface_method_impl{RTVFSSYMLINKOPS,pfnRead}
 */
static DECLCALLBACK(int) rtZipXarFssSym_Read(void *pvThis, char *pszTarget, size_t cbTarget)
{
    PRTZIPXARBASEOBJ pThis = (PRTZIPXARBASEOBJ)pvThis;
#if 0
    return RTStrCopy(pszTarget, cbXarget, pThis->pXarReader->szTarget);
#else
    RT_NOREF_PV(pThis); RT_NOREF_PV(pszTarget); RT_NOREF_PV(cbTarget);
    return VERR_NOT_IMPLEMENTED;
#endif
}


/**
 * Xar symbolic (and hardlink) operations.
 */
static const RTVFSSYMLINKOPS g_rtZipXarFssSymOps =
{
    { /* Obj */
        RTVFSOBJOPS_VERSION,
        RTVFSOBJTYPE_SYMLINK,
        "XarFsStream::Symlink",
        rtZipXarFssSym_Close,
        rtZipXarFssSym_QueryInfo,
        NULL,
        RTVFSOBJOPS_VERSION
    },
    RTVFSSYMLINKOPS_VERSION,
    0,
    { /* ObjSet */
        RTVFSOBJSETOPS_VERSION,
        RT_UOFFSETOF(RTVFSSYMLINKOPS, ObjSet) - RT_UOFFSETOF(RTVFSSYMLINKOPS, Obj),
        rtZipXarFssSym_SetMode,
        rtZipXarFssSym_SetTimes,
        rtZipXarFssSym_SetOwner,
        RTVFSOBJSETOPS_VERSION
    },
    rtZipXarFssSym_Read,
    RTVFSSYMLINKOPS_VERSION
};


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtZipXarFss_Close(void *pvThis)
{
    PRTZIPXARFSSTREAM pThis = (PRTZIPXARFSSTREAM)pvThis;

    RTVfsIoStrmRelease(pThis->hVfsIos);
    pThis->hVfsIos = NIL_RTVFSIOSTREAM;

    RTVfsFileRelease(pThis->hVfsFile);
    pThis->hVfsFile = NIL_RTVFSFILE;

    if (pThis->XarReader.pDoc)
        delete pThis->XarReader.pDoc;
    pThis->XarReader.pDoc = NULL;
    /* The other XarReader fields only point to elements within pDoc. */
    pThis->XarReader.pToc = NULL;
    pThis->XarReader.cCurDepth = 0;
    pThis->XarReader.pCurFile = NULL;

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipXarFss_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPXARFSSTREAM pThis = (PRTZIPXARFSSTREAM)pvThis;
    /* Take the lazy approach here, with the sideffect of providing some info
       that is actually kind of useful. */
    return RTVfsIoStrmQueryInfo(pThis->hVfsIos, pObjInfo, enmAddAttr);
}


/**
 * @interface_method_impl{RTVFSFSSTREAMOPS,pfnNext}
 */
static DECLCALLBACK(int) rtZipXarFss_Next(void *pvThis, char **ppszName, RTVFSOBJTYPE *penmType, PRTVFSOBJ phVfsObj)
{
    PRTZIPXARFSSTREAM pThis = (PRTZIPXARFSSTREAM)pvThis;

    /*
     * Check if we've already reached the end in some way.
     */
    if (pThis->fEndOfStream)
        return VERR_EOF;
    if (pThis->rcFatal != VINF_SUCCESS)
        return pThis->rcFatal;

    /*
     * Get the next file element.
     */
    xml::ElementNode const *pCurFile = pThis->XarReader.pCurFile;
    if (pCurFile)
        pThis->XarReader.pCurFile = pCurFile = rtZipXarGetNextFileElement(pCurFile, &pThis->XarReader.cCurDepth);
    else if (!pThis->fEndOfStream)
    {
        pThis->XarReader.cCurDepth  = 0;
        pThis->XarReader.pCurFile   = pCurFile = pThis->XarReader.pToc->findChildElement("file");
    }
    if (!pCurFile)
    {
        pThis->fEndOfStream = true;
        return VERR_EOF;
    }

    /*
     * Retrive the fundamental attributes (elements actually).
     */
    const char *pszName = pCurFile->findChildElementValueP("name");
    const char *pszType = pCurFile->findChildElementValueP("type");
    if (RT_UNLIKELY(!pszName || !pszType))
        return pThis->rcFatal = VERR_XAR_BAD_FILE_ELEMENT;

    /*
     * Validate the filename.  Being a little too paranoid here, perhaps, wrt
     * path separators and escapes...
     */
    if (   !*pszName
        || strchr(pszName, '/')
        || strchr(pszName, '\\')
        || strchr(pszName, ':')
        || !strcmp(pszName, "..") )
        return pThis->rcFatal = VERR_XAR_INVALID_FILE_NAME;

    /*
     * Gather any additional attributes that are essential to the file type,
     * then create the VFS object we're going to return.
     */
    int             rc;
    RTVFSOBJ        hVfsObj;
    RTVFSOBJTYPE    enmType;
    if (!strcmp(pszType, "file"))
    {
        RTZIPXARDATASTREAM DataAttr;
        rc = rtZipXarGetDataStreamAttributes(pCurFile, &DataAttr);
        if (RT_FAILURE(rc))
            return pThis->rcFatal = rc;
        DataAttr.offData += pThis->offZero + pThis->offStart;

        if (   pThis->hVfsFile != NIL_RTVFSFILE
            && DataAttr.enmEncoding == RTZIPXARENCODING_STORE)
        {
            /*
             * The input is seekable and the XAR file isn't compressed, so we
             * can provide a seekable file to the user.
             */
            RTVFSFILE           hVfsFile;
            PRTZIPXARFILE       pFileData;
            rc = RTVfsNewFile(&g_rtZipXarFssFileOps,
                              sizeof(*pFileData),
                              RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
                              NIL_RTVFS,
                              NIL_RTVFSLOCK,
                              &hVfsFile,
                              (void **)&pFileData);
            if (RT_FAILURE(rc))
                return pThis->rcFatal = rc;

            pFileData->Ios.BaseObj.pFileElem    = pCurFile;
            pFileData->Ios.BaseObj.fModeType    = RTFS_TYPE_FILE;
            pFileData->Ios.DataAttr             = DataAttr;
            pFileData->Ios.offCurPos            = 0;
            pFileData->Ios.fEndOfStream         = false;
            pFileData->Ios.fSeekable            = true;
            pFileData->Ios.uHashState           = RTZIPXAR_HASH_PENDING;
            pFileData->Ios.cbDigested           = 0;
            rtZipXarHashInit(&pFileData->Ios.CtxArchived,  pFileData->Ios.DataAttr.uHashFunArchived);
            rtZipXarHashInit(&pFileData->Ios.CtxExtracted, pFileData->Ios.DataAttr.uHashFunExtracted);

            pFileData->Ios.hVfsIos              = pThis->hVfsIos;
            RTVfsIoStrmRetain(pFileData->Ios.hVfsIos);
            pFileData->hVfsFile                 = pThis->hVfsFile;
            RTVfsFileRetain(pFileData->hVfsFile);

            /* Try avoid double content hashing. */
            if (pFileData->Ios.DataAttr.uHashFunArchived == pFileData->Ios.DataAttr.uHashFunExtracted)
                pFileData->Ios.DataAttr.uHashFunExtracted = XAR_HASH_NONE;

            enmType = RTVFSOBJTYPE_FILE;
            hVfsObj = RTVfsObjFromFile(hVfsFile);
            RTVfsFileRelease(hVfsFile);
        }
        else
        {
            RTVFSIOSTREAM       hVfsIosRaw;
            PRTZIPXARIOSTREAM   pIosData;
            rc = RTVfsNewIoStream(&g_rtZipXarFssIosOps,
                                  sizeof(*pIosData),
                                  RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
                                  NIL_RTVFS,
                                  NIL_RTVFSLOCK,
                                  &hVfsIosRaw,
                                  (void **)&pIosData);
            if (RT_FAILURE(rc))
                return pThis->rcFatal = rc;

            pIosData->BaseObj.pFileElem     = pCurFile;
            pIosData->BaseObj.fModeType     = RTFS_TYPE_FILE;
            pIosData->DataAttr              = DataAttr;
            pIosData->offCurPos             = 0;
            pIosData->fEndOfStream          = false;
            pIosData->fSeekable             = pThis->hVfsFile != NIL_RTVFSFILE;
            pIosData->uHashState            = RTZIPXAR_HASH_PENDING;
            pIosData->cbDigested            = 0;
            rtZipXarHashInit(&pIosData->CtxArchived,  pIosData->DataAttr.uHashFunArchived);
            rtZipXarHashInit(&pIosData->CtxExtracted, pIosData->DataAttr.uHashFunExtracted);

            pIosData->hVfsIos               = pThis->hVfsIos;
            RTVfsIoStrmRetain(pThis->hVfsIos);

            if (   pIosData->DataAttr.enmEncoding != RTZIPXARENCODING_STORE
                && pIosData->DataAttr.enmEncoding != RTZIPXARENCODING_UNSUPPORTED)
            {
                /*
                 * We need to set up a decompression chain.
                 */
                RTVFSIOSTREAM       hVfsIosDecomp;
                PRTZIPXARDECOMPIOS  pIosDecompData;
                rc = RTVfsNewIoStream(&g_rtZipXarFssDecompIosOps,
                                      sizeof(*pIosDecompData),
                                      RTFILE_O_READ | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
                                      NIL_RTVFS,
                                      NIL_RTVFSLOCK,
                                      &hVfsIosDecomp,
                                      (void **)&pIosDecompData);
                if (RT_FAILURE(rc))
                {
                    RTVfsIoStrmRelease(hVfsIosRaw);
                    return pThis->rcFatal = rc;
                }

                pIosDecompData->hVfsIosDecompressor = NIL_RTVFSIOSTREAM;
                pIosDecompData->hVfsIosRaw          = hVfsIosRaw;
                pIosDecompData->pIosRaw             = pIosData;
                pIosDecompData->offCurPos           = 0;
                pIosDecompData->uHashFunExtracted   = DataAttr.uHashFunExtracted;
                pIosDecompData->uHashState = RTZIPXAR_HASH_PENDING;
                rtZipXarHashInit(&pIosDecompData->CtxExtracted, pIosDecompData->uHashFunExtracted);
                pIosDecompData->DigestExtracted     = DataAttr.DigestExtracted;

                /* Tell the raw end to only hash the archived data. */
                pIosData->DataAttr.uHashFunExtracted = XAR_HASH_NONE;

                /*
                 * Hook up the decompressor.
                 */
                switch (DataAttr.enmEncoding)
                {
                    case RTZIPXARENCODING_GZIP:
                        /* Must allow zlib header, all examples I've got seems
                           to be using it rather than the gzip one.  Makes
                           sense as there is no need to repeat the file name
                           and the attributes. */
                        rc = RTZipGzipDecompressIoStream(hVfsIosRaw, RTZIPGZIPDECOMP_F_ALLOW_ZLIB_HDR,
                                                         &pIosDecompData->hVfsIosDecompressor);
                        break;
                    default:
                        rc = VERR_INTERNAL_ERROR_5;
                        break;
                }
                if (RT_FAILURE(rc))
                {
                    RTVfsIoStrmRelease(hVfsIosDecomp);
                    return pThis->rcFatal = rc;
                }

                /* What to return. */
                hVfsObj = RTVfsObjFromIoStream(hVfsIosDecomp);
                RTVfsIoStrmRelease(hVfsIosDecomp);
            }
            else
            {
                /* Try avoid double content hashing. */
                if (pIosData->DataAttr.uHashFunArchived == pIosData->DataAttr.uHashFunExtracted)
                    pIosData->DataAttr.uHashFunExtracted = XAR_HASH_NONE;

                /* What to return. */
                hVfsObj = RTVfsObjFromIoStream(hVfsIosRaw);
                RTVfsIoStrmRelease(hVfsIosRaw);
            }
            enmType = RTVFSOBJTYPE_IO_STREAM;
        }
    }
    else if (!strcmp(pszType, "directory"))
    {
        PRTZIPXARBASEOBJ pBaseObjData;
        rc = RTVfsNewBaseObj(&g_rtZipXarFssBaseObjOps,
                             sizeof(*pBaseObjData),
                             NIL_RTVFS,
                             NIL_RTVFSLOCK,
                             &hVfsObj,
                             (void **)&pBaseObjData);
        if (RT_FAILURE(rc))
            return pThis->rcFatal = rc;

        pBaseObjData->pFileElem  = pCurFile;
        pBaseObjData->fModeType  = RTFS_TYPE_DIRECTORY;

        enmType = RTVFSOBJTYPE_BASE;
    }
    else if (!strcmp(pszType, "symlink"))
    {
        RTVFSSYMLINK        hVfsSym;
        PRTZIPXARBASEOBJ    pBaseObjData;
        rc = RTVfsNewSymlink(&g_rtZipXarFssSymOps,
                             sizeof(*pBaseObjData),
                             NIL_RTVFS,
                             NIL_RTVFSLOCK,
                             &hVfsSym,
                             (void **)&pBaseObjData);
        if (RT_FAILURE(rc))
            return pThis->rcFatal = rc;

        pBaseObjData->pFileElem  = pCurFile;
        pBaseObjData->fModeType  = RTFS_TYPE_SYMLINK;

        enmType = RTVFSOBJTYPE_SYMLINK;
        hVfsObj = RTVfsObjFromSymlink(hVfsSym);
        RTVfsSymlinkRelease(hVfsSym);
    }
    else
        return pThis->rcFatal = VERR_XAR_UNKNOWN_FILE_TYPE;

    /*
     * Set the return data and we're done.
     */
    if (ppszName)
    {
        /* Figure the length. */
        size_t const            cbCurName  = strlen(pszName) + 1;
        size_t                  cbFullName = cbCurName;
        const xml::ElementNode *pAncestor  = pCurFile;
        uint32_t                cLeft      = pThis->XarReader.cCurDepth;
        while (cLeft-- > 0)
        {
            pAncestor = (const xml::ElementNode *)pAncestor->getParent();               Assert(pAncestor);
            const char *pszAncestorName = pAncestor->findChildElementValueP("name");    Assert(pszAncestorName);
            cbFullName += strlen(pszAncestorName) + 1;
        }

        /* Allocate a buffer. */
        char *psz = *ppszName = RTStrAlloc(cbFullName);
        if (!psz)
        {
            RTVfsObjRelease(hVfsObj);
            return VERR_NO_STR_MEMORY;
        }

        /* Construct it, from the end. */
        psz += cbFullName;
        psz -= cbCurName;
        memcpy(psz, pszName, cbCurName);

        pAncestor = pCurFile;
        cLeft = pThis->XarReader.cCurDepth;
        while (cLeft-- > 0)
        {
            pAncestor = (const xml::ElementNode *)pAncestor->getParent();             Assert(pAncestor);
            const char *pszAncestorName = pAncestor->findChildElementValueP("name");  Assert(pszAncestorName);
            *--psz = '/';
            size_t cchAncestorName = strlen(pszAncestorName);
            psz -= cchAncestorName;
            memcpy(psz, pszAncestorName, cchAncestorName);
        }
        Assert(*ppszName == psz);
    }

    if (phVfsObj)
        *phVfsObj = hVfsObj;
    else
        RTVfsObjRelease(hVfsObj);

    if (penmType)
        *penmType = enmType;

    return VINF_SUCCESS;
}



/**
 * Xar filesystem stream operations.
 */
static const RTVFSFSSTREAMOPS rtZipXarFssOps =
{
    { /* Obj */
        RTVFSOBJOPS_VERSION,
        RTVFSOBJTYPE_FS_STREAM,
        "XarFsStream",
        rtZipXarFss_Close,
        rtZipXarFss_QueryInfo,
        NULL,
        RTVFSOBJOPS_VERSION
    },
    RTVFSFSSTREAMOPS_VERSION,
    0,
    rtZipXarFss_Next,
    NULL,
    NULL,
    NULL,
    RTVFSFSSTREAMOPS_VERSION
};



/**
 * TOC validation part 2.
 *
 * Will advance the input stream past the TOC hash and signature data.
 *
 * @returns IPRT status code.
 * @param   pThis       The FS stream instance being created.
 * @param   pXarHdr     The XAR header.
 * @param   pTocDigest  The TOC input data digest.
 */
static int rtZipXarValidateTocPart2(PRTZIPXARFSSTREAM pThis, PCXARHEADER pXarHdr, PCRTZIPXARHASHDIGEST pTocDigest)
{
    int rc;
    RT_NOREF_PV(pXarHdr);

    /*
     * Check that the hash function in the TOC matches the one in the XAR header.
     */
    const xml::ElementNode *pChecksumElem = pThis->XarReader.pToc->findChildElement("checksum");
    if (pChecksumElem)
    {
        const xml::AttributeNode *pAttr = pChecksumElem->findAttribute("style");
        if (!pAttr)
            return VERR_XAR_BAD_CHECKSUM_ELEMENT;

        const char *pszStyle = pAttr->getValue();
        if (!pszStyle)
            return VERR_XAR_BAD_CHECKSUM_ELEMENT;

        uint8_t uHashFunction;
        rc = rtZipXarParseChecksumStyle(pszStyle, &uHashFunction);
        if (RT_FAILURE(rc))
            return rc;
        if (uHashFunction != pThis->uHashFunction)
            return VERR_XAR_HASH_FUNCTION_MISMATCH;

        /*
         * Verify the checksum if we got one.
         */
        if (pThis->uHashFunction != XAR_HASH_NONE)
        {
            RTFOFF   offChecksum;
            RTFOFF   cbChecksum;
            rc = rtZipXarGetOffsetSizeLengthFromElem(pChecksumElem, &offChecksum, &cbChecksum, NULL);
            if (RT_FAILURE(rc))
                return rc;
            if (cbChecksum != (RTFOFF)pThis->cbHashDigest)
                return VERR_XAR_BAD_DIGEST_LENGTH;
            if (offChecksum != 0 && pThis->hVfsFile == NIL_RTVFSFILE)
                return VERR_XAR_NOT_STREAMBLE_ELEMENT_ORDER;

            RTZIPXARHASHDIGEST StoredDigest;
            rc = RTVfsIoStrmReadAt(pThis->hVfsIos, pThis->offZero + offChecksum, &StoredDigest, pThis->cbHashDigest,
                                   true /*fBlocking*/, NULL /*pcbRead*/);
            if (RT_FAILURE(rc))
                return rc;
            if (memcmp(&StoredDigest, pTocDigest, pThis->cbHashDigest))
                return VERR_XAR_TOC_DIGEST_MISMATCH;
        }
    }
    else if (pThis->uHashFunction != XAR_HASH_NONE)
        return VERR_XAR_BAD_CHECKSUM_ELEMENT;

    /*
     * Check the signature, if we got one.
     */
    /** @todo signing. */

    return VINF_SUCCESS;
}


/**
 * Reads and validates the table of content.
 *
 * @returns IPRT status code.
 * @param   hVfsIosIn   The input stream.
 * @param   pXarHdr     The XAR header.
 * @param   pDoc        The TOC XML document.
 * @param   ppTocElem   Where to return the pointer to the TOC element on
 *                      success.
 * @param   pTocDigest  Where to return the TOC digest on success.
 */
static int rtZipXarReadAndValidateToc(RTVFSIOSTREAM hVfsIosIn, PCXARHEADER pXarHdr,
                                      xml::Document *pDoc, xml::ElementNode const **ppTocElem, PRTZIPXARHASHDIGEST pTocDigest)
{
    /*
     * Decompress it, calculating the hash while doing so.
     */
    char *pszOutput = (char *)RTMemTmpAlloc(pXarHdr->cbTocUncompressed + 1);
    if (!pszOutput)
        return VERR_NO_TMP_MEMORY;
    int rc = VERR_NO_TMP_MEMORY;
    void *pvInput = RTMemTmpAlloc(pXarHdr->cbTocCompressed);
    if (pvInput)
    {
        rc = RTVfsIoStrmRead(hVfsIosIn, pvInput, pXarHdr->cbTocCompressed, true /*fBlocking*/,  NULL);
        if (RT_SUCCESS(rc))
        {
            rtZipXarCalcHash(pXarHdr->uHashFunction, pvInput, pXarHdr->cbTocCompressed, pTocDigest);

            size_t cbActual;
            rc = RTZipBlockDecompress(RTZIPTYPE_ZLIB, 0 /*fFlags*/,
                                      pvInput, pXarHdr->cbTocCompressed, NULL,
                                      pszOutput, pXarHdr->cbTocUncompressed, &cbActual);
            if (RT_SUCCESS(rc) && cbActual != pXarHdr->cbTocUncompressed)
                rc = VERR_XAR_TOC_UNCOMP_SIZE_MISMATCH;
        }
        RTMemTmpFree(pvInput);
    }
    if (RT_SUCCESS(rc))
    {
        pszOutput[pXarHdr->cbTocUncompressed] = '\0';

        /*
         * Parse the TOC (XML document) and do some basic validations.
         */
        size_t cchToc = strlen(pszOutput);
        if (   cchToc     == pXarHdr->cbTocUncompressed
            || cchToc + 1 == pXarHdr->cbTocUncompressed)
        {
            rc = RTStrValidateEncoding(pszOutput);
            if (RT_SUCCESS(rc))
            {
                xml::XmlMemParser Parser;
                try
                {
                    Parser.read(pszOutput, cchToc, RTCString("xar-toc.xml"), *pDoc);
                }
                catch (xml::XmlError &)
                {
                    rc = VERR_XAR_TOC_XML_PARSE_ERROR;
                }
                catch (...)
                {
                    rc = VERR_NO_MEMORY;
                }
                if (RT_SUCCESS(rc))
                {
                    xml::ElementNode const *pRootElem = pDoc->getRootElement();
                    xml::ElementNode const *pTocElem  = NULL;
                    if (pRootElem && pRootElem->nameEquals("xar"))
                        pTocElem = pRootElem ? pRootElem->findChildElement("toc") : NULL;
                    if (pTocElem)
                    {
#ifndef USE_STD_LIST_FOR_CHILDREN
                        Assert(pRootElem->getParent() == NULL);
                        Assert(pTocElem->getParent() == pRootElem);
                        if (   !pTocElem->getNextSibiling()
                            && !pTocElem->getPrevSibiling())
#endif
                        {
                            /*
                             * Further parsing and validation is done after the
                             * caller has created an file system stream instance.
                             */
                            *ppTocElem = pTocElem;

                            RTMemTmpFree(pszOutput);
                            return VINF_SUCCESS;
                        }

                        rc = VERR_XML_TOC_ELEMENT_HAS_SIBLINGS;
                    }
                    else
                        rc = VERR_XML_TOC_ELEMENT_MISSING;
                }
            }
            else
                rc = VERR_XAR_TOC_UTF8_ENCODING;
        }
        else
            rc = VERR_XAR_TOC_STRLEN_MISMATCH;
    }

    RTMemTmpFree(pszOutput);
    return rc;
}


/**
 * Reads and validates the XAR header.
 *
 * @returns IPRT status code.
 * @param   hVfsIosIn   The input stream.
 * @param   pXarHdr     Where to return the XAR header in host byte order.
 */
static int rtZipXarReadAndValidateHeader(RTVFSIOSTREAM hVfsIosIn, PXARHEADER pXarHdr)
{
    /*
     * Read it and check the signature.
     */
    int rc = RTVfsIoStrmRead(hVfsIosIn, pXarHdr, sizeof(*pXarHdr), true /*fBlocking*/,  NULL);
    if (RT_FAILURE(rc))
        return rc;
    if (pXarHdr->u32Magic != XAR_HEADER_MAGIC)
        return VERR_XAR_WRONG_MAGIC;

    /*
     * Correct the byte order.
     */
    pXarHdr->cbHeader             = RT_BE2H_U16(pXarHdr->cbHeader);
    pXarHdr->uVersion             = RT_BE2H_U16(pXarHdr->uVersion);
    pXarHdr->cbTocCompressed      = RT_BE2H_U64(pXarHdr->cbTocCompressed);
    pXarHdr->cbTocUncompressed    = RT_BE2H_U64(pXarHdr->cbTocUncompressed);
    pXarHdr->uHashFunction        = RT_BE2H_U32(pXarHdr->uHashFunction);

    /*
     * Validate the header.
     */
    if (pXarHdr->uVersion > XAR_HEADER_VERSION)
        return VERR_XAR_UNSUPPORTED_VERSION;
    if (pXarHdr->cbHeader < sizeof(XARHEADER))
        return VERR_XAR_BAD_HDR_SIZE;
    if (pXarHdr->uHashFunction > XAR_HASH_MAX)
        return VERR_XAR_UNSUPPORTED_HASH_FUNCTION;
    if (pXarHdr->cbTocUncompressed < 16)
        return VERR_XAR_TOC_TOO_SMALL;
    if (pXarHdr->cbTocUncompressed > _4M)
        return VERR_XAR_TOC_TOO_BIG;
    if (pXarHdr->cbTocCompressed > _4M)
        return VERR_XAR_TOC_TOO_BIG_COMPRESSED;

    /*
     * Skip over bytes we don't understand (could be padding).
     */
    if (pXarHdr->cbHeader > sizeof(XARHEADER))
    {
        rc = RTVfsIoStrmSkip(hVfsIosIn, pXarHdr->cbHeader - sizeof(XARHEADER));
        if (RT_FAILURE(rc))
            return rc;
    }

    return VINF_SUCCESS;
}


RTDECL(int) RTZipXarFsStreamFromIoStream(RTVFSIOSTREAM hVfsIosIn, uint32_t fFlags, PRTVFSFSSTREAM phVfsFss)
{
    /*
     * Input validation.
     */
    AssertPtrReturn(phVfsFss, VERR_INVALID_HANDLE);
    *phVfsFss = NIL_RTVFSFSSTREAM;
    AssertPtrReturn(hVfsIosIn, VERR_INVALID_HANDLE);
    AssertReturn(!fFlags, VERR_INVALID_PARAMETER);

    RTFOFF const offStart = RTVfsIoStrmTell(hVfsIosIn);
    AssertReturn(offStart >= 0, (int)offStart);

    uint32_t cRefs = RTVfsIoStrmRetain(hVfsIosIn);
    AssertReturn(cRefs != UINT32_MAX, VERR_INVALID_HANDLE);

    /*
     * Read and validate the header, then uncompress the TOC.
     */
    XARHEADER XarHdr;
    int rc = rtZipXarReadAndValidateHeader(hVfsIosIn, &XarHdr);
    if (RT_SUCCESS(rc))
    {
        xml::Document *pDoc = NULL;
        try         { pDoc = new xml::Document(); }
        catch (...) { }
        if (pDoc)
        {
            RTZIPXARHASHDIGEST      TocDigest;
            xml::ElementNode const *pTocElem = NULL;
            rc = rtZipXarReadAndValidateToc(hVfsIosIn, &XarHdr, pDoc, &pTocElem, &TocDigest);
            if (RT_SUCCESS(rc))
            {
                size_t offZero = RTVfsIoStrmTell(hVfsIosIn);
                if (offZero > 0)
                {
                    /*
                     * Create a file system stream before we continue the parsing.
                     */
                    PRTZIPXARFSSTREAM pThis;
                    RTVFSFSSTREAM     hVfsFss;
                    rc = RTVfsNewFsStream(&rtZipXarFssOps, sizeof(*pThis), NIL_RTVFS, NIL_RTVFSLOCK, RTFILE_O_READ,
                                          &hVfsFss, (void **)&pThis);
                    if (RT_SUCCESS(rc))
                    {
                        pThis->hVfsIos              = hVfsIosIn;
                        pThis->hVfsFile             = RTVfsIoStrmToFile(hVfsIosIn);
                        pThis->offStart             = offStart;
                        pThis->offZero              = offZero;
                        pThis->uHashFunction        = (uint8_t)XarHdr.uHashFunction;
                        switch (pThis->uHashFunction)
                        {
                            case XAR_HASH_MD5:  pThis->cbHashDigest = sizeof(TocDigest.abMd5); break;
                            case XAR_HASH_SHA1: pThis->cbHashDigest = sizeof(TocDigest.abSha1); break;
                            default:            pThis->cbHashDigest = 0; break;
                        }
                        pThis->fEndOfStream         = false;
                        pThis->rcFatal              = VINF_SUCCESS;
                        pThis->XarReader.pDoc       = pDoc;
                        pThis->XarReader.pToc       = pTocElem;
                        pThis->XarReader.pCurFile   = 0;
                        pThis->XarReader.cCurDepth  = 0;

                        /*
                         * Next validation step.
                         */
                        rc = rtZipXarValidateTocPart2(pThis, &XarHdr, &TocDigest);
                        if (RT_SUCCESS(rc))
                        {
                            *phVfsFss = hVfsFss;
                            return VINF_SUCCESS;
                        }

                        RTVfsFsStrmRelease(hVfsFss);
                        return rc;
                    }
                }
                else
                    rc = (int)offZero;
            }
            delete pDoc;
        }
        else
            rc = VERR_NO_MEMORY;
    }

    RTVfsIoStrmRelease(hVfsIosIn);
    return rc;
}