summaryrefslogtreecommitdiffstats
path: root/src/VBox/Runtime/common/zip/tarvfswriter.cpp
blob: ac5d603abdc3e8726d79923f6011566f3060d0c9 (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
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
/* $Id: tarvfswriter.cpp $ */
/** @file
 * IPRT - TAR Virtual Filesystem, Writer.
 */

/*
 * 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/err.h>
#include <iprt/file.h>
#include <iprt/mem.h>
#include <iprt/path.h>
#include <iprt/string.h>
#include <iprt/vfs.h>
#include <iprt/vfslowlevel.h>
#include <iprt/zero.h>

#include "tarvfsreader.h"


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/** The TAR block size we're using in this implementation.
 * @remarks Should technically be user configurable, but we don't currently need that. */
#define RTZIPTAR_BLOCKSIZE      sizeof(RTZIPTARHDR)

/** Minimum file size we consider for sparse files. */
#define RTZIPTAR_MIN_SPARSE     _64K


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * A data span descriptor in a sparse file.
 */
typedef struct RTZIPTARSPARSESPAN
{
    /** Byte offset into the file of the data. */
    uint64_t        off;
    /** Number of bytes of data, rounded up to a multiple of blocksize. */
    uint64_t        cb;
} RTZIPTARSPARSESPAN;
/** Pointer to a data span. */
typedef RTZIPTARSPARSESPAN *PRTZIPTARSPARSESPAN;
/** Pointer to a const data span. */
typedef RTZIPTARSPARSESPAN const *PCRTZIPTARSPARSESPAN;

/**
 * Chunk of TAR sparse file data spans.
 */
typedef struct RTZIPTARSPARSECHUNK
{
    /** List entry. */
    RTLISTNODE          Entry;
    /** Array of data spans. */
    RTZIPTARSPARSESPAN  aSpans[63];
} RTZIPTARSPARSECHUNK;
AssertCompile(sizeof(RTZIPTARSPARSECHUNK) <= 1024);
AssertCompile(sizeof(RTZIPTARSPARSECHUNK) >= 1008);
/** Pointer to a chunk of TAR data spans. */
typedef RTZIPTARSPARSECHUNK *PRTZIPTARSPARSECHUNK;
/** Pointer to a const chunk of TAR data spans. */
typedef RTZIPTARSPARSECHUNK const *PCRTZIPTARSPARSECHUNK;

/**
 * TAR sparse file info.
 */
typedef struct RTZIPTARSPARSE
{
    /** Number of data bytes (real size).  */
    uint64_t            cbDataSpans;
    /** Number of data spans. */
    uint32_t            cDataSpans;
    /** The index of the next span in the tail chunk (to avoid modulus 63). */
    uint32_t            iNextSpan;
    /** Head of the data span chunk list (PRTZIPTARSPARSECHUNK). */
    RTLISTANCHOR        ChunkHead;
} RTZIPTARSPARSE;
/** Pointer to TAR sparse file info. */
typedef RTZIPTARSPARSE *PRTZIPTARSPARSE;
/** Pointer to a const TAR sparse file info. */
typedef RTZIPTARSPARSE const *PCRTZIPTARSPARSE;


/** Pointer to a the private data of a TAR filesystem stream. */
typedef struct RTZIPTARFSSTREAMWRITER *PRTZIPTARFSSTREAMWRITER;


/**
 * Instance data for a file or I/O stream returned by
 * RTVFSFSSTREAMOPS::pfnPushFile.
 */
typedef struct RTZIPTARFSSTREAMWRITERPUSH
{
    /** Pointer to the parent FS stream writer instance.
     * This is set to NULL should the push object live longer than the stream. */
    PRTZIPTARFSSTREAMWRITER pParent;
    /** The header offset, UINT64_MAX if non-seekable output. */
    uint64_t                offHdr;
    /** The data offset, UINT64_MAX if non-seekable output. */
    uint64_t                offData;
    /** The current I/O stream position (relative to offData). */
    uint64_t                offCurrent;
    /** The expected size amount of file content, or max file size if open-ended. */
    uint64_t                cbExpected;
    /** The current amount of file content written. */
    uint64_t                cbCurrent;
    /** Object info copy for rtZipTarWriterPush_QueryInfo. */
    RTFSOBJINFO             ObjInfo;
    /** Set if open-ended file size requiring a tar header update when done. */
    bool                    fOpenEnded;
} RTZIPTARFSSTREAMWRITERPUSH;
/** Pointer to a push I/O instance. */
typedef RTZIPTARFSSTREAMWRITERPUSH *PRTZIPTARFSSTREAMWRITERPUSH;


/**
 * Tar filesystem stream private data.
 */
typedef struct RTZIPTARFSSTREAMWRITER
{
    /** The output I/O stream. */
    RTVFSIOSTREAM           hVfsIos;
    /** Non-nil if the output is a file.  */
    RTVFSFILE               hVfsFile;

    /** The current push file.  NULL if none. */
    PRTZIPTARFSSTREAMWRITERPUSH pPush;

    /** The TAR format. */
    RTZIPTARFORMAT          enmFormat;
    /** Set if we've encountered a fatal error. */
    int                     rcFatal;
    /** Flags, RTZIPTAR_C_XXX. */
    uint32_t                fFlags;

    /** Number of bytes written. */
    uint64_t                cbWritten;

    /** @name Attribute overrides.
     * @{
     */
    RTUID                   uidOwner;           /**< Owner, NIL_RTUID if no change. */
    char                   *pszOwner;           /**< Owner, NULL if no change. */
    RTGID                   gidGroup;           /**< Group, NIL_RTGID if no change. */
    char                   *pszGroup;           /**< Group, NULL if no change. */
    char                   *pszPrefix;          /**< Path prefix, NULL if no change. */
    size_t                  cchPrefix;          /**< The length of pszPrefix. */
    PRTTIMESPEC             pModTime;           /**< Modification time, NULL of no change. */
    RTTIMESPEC              ModTime;            /**< pModTime points to this. */
    RTFMODE                 fFileModeAndMask;   /**< File mode AND mask. */
    RTFMODE                 fFileModeOrMask;    /**< File mode OR mask. */
    RTFMODE                 fDirModeAndMask;    /**< Directory mode AND mask. */
    RTFMODE                 fDirModeOrMask;     /**< Directory mode OR mask. */
    /** @} */

    /** When in update mode (RTZIPTAR_C_UPDATE) we have an reader FSS instance,
     * though w/o the RTVFSFSSTREAM bits. (Allocated after this structure.) */
    PRTZIPTARFSSTREAM       pRead;
    /** Set if we're in writing mode and pfnNext shall fail. */
    bool                    fWriting;


    /** Number of headers returned by rtZipTarFssWriter_ObjInfoToHdr. */
    uint32_t                cHdrs;
    /** Header buffers returned by rtZipTarFssWriter_ObjInfoToHdr. */
    RTZIPTARHDR             aHdrs[3];
} RTZIPTARFSSTREAMWRITER;


/*********************************************************************************************************************************
*   Internal Functions                                                                                                           *
*********************************************************************************************************************************/
static DECLCALLBACK(int) rtZipTarWriterPush_Seek(void *pvThis, RTFOFF offSeek, unsigned uMethod, PRTFOFF poffActual);
static int rtZipTarFssWriter_CompleteCurrentPushFile(PRTZIPTARFSSTREAMWRITER pThis);
static int rtZipTarFssWriter_AddFile(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath, RTVFSIOSTREAM hVfsIos,
                                     PCRTFSOBJINFO pObjInfo, const char *pszOwnerNm, const char *pszGroupNm);


/**
 * Calculates the header checksum and stores it in the chksum field.
 *
 * @returns IPRT status code.
 * @param   pHdr                The header.
 */
static int rtZipTarFssWriter_ChecksumHdr(PRTZIPTARHDR pHdr)
{
    int32_t iUnsignedChksum;
    rtZipTarCalcChkSum(pHdr, &iUnsignedChksum, NULL);

    int rc = RTStrFormatU32(pHdr->Common.chksum, sizeof(pHdr->Common.chksum), iUnsignedChksum,
                            8 /*uBase*/, -1 /*cchWidth*/, sizeof(pHdr->Common.chksum) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
    AssertRCReturn(rc, VERR_TAR_NUM_VALUE_TOO_LARGE);
    return VINF_SUCCESS;
}



/**
 * Formats a 12 character wide file offset or size field.
 *
 * This is mainly used for RTZIPTARHDR::Common.size, but also for formatting the
 * sparse map.
 *
 * @returns IPRT status code.
 * @param   pach12Field     The 12 character wide destination field.
 * @param   off             The offset to set.
 */
static int rtZipTarFssWriter_FormatOffset(char pach12Field[12], uint64_t off)
{
    /*
     * Is the size small enough for the standard octal string encoding?
     *
     * Note! We could actually use the terminator character as well if we liked,
     *       but let not do that as it's easier to test this way.
     */
    if (off < _4G * 2U)
    {
        int rc = RTStrFormatU64(pach12Field, 12, off, 8 /*uBase*/, -1 /*cchWidth*/, 12 - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
        AssertRCReturn(rc, rc);
    }
    /*
     * No, use the base 256 extension. Set the highest bit of the left most
     * character.  We don't deal with negatives here, cause the size have to
     * be greater than zero.
     *
     * Note! The base-256 extension are never used by gtar or libarchive
     *       with the "ustar  \0" format version, only the later
     *       "ustar\000" version.  However, this shouldn't cause much
     *       trouble as they are not picky about what they read.
     */
    /** @todo above note is wrong:  GNU tar only uses base-256 with the GNU tar
     * format, i.e. "ustar   \0", see create.c line 303 in v1.29. */
    else
    {
        size_t         cchField  = 12 - 1;
        unsigned char *puchField = (unsigned char *)pach12Field;
        puchField[0] = 0x80;
        do
        {
            puchField[cchField--] = off & 0xff;
            off >>= 8;
        } while (cchField);
    }

    return VINF_SUCCESS;
}


/**
 * Creates one or more tar headers for the object.
 *
 * Returns RTZIPTARFSSTREAMWRITER::aHdrs and RTZIPTARFSSTREAMWRITER::cHdrs.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 * @param   pszPath         The path to the file.
 * @param   hVfsIos         The I/O stream of the file.
 * @param   fFlags          The RTVFSFSSTREAMOPS::pfnAdd flags.
 * @param   pObjInfo        The object information.
 * @param   pszOwnerNm      The owner name.
 * @param   pszGroupNm      The group name.
 * @param   chType          The tar record type, UINT8_MAX for default.
 */
static int rtZipTarFssWriter_ObjInfoToHdr(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath, PCRTFSOBJINFO pObjInfo,
                                          const char *pszOwnerNm, const char *pszGroupNm, uint8_t chType)
{
    pThis->cHdrs = 0;
    RT_ZERO(pThis->aHdrs[0]);

    /*
     * The path name first.  Make sure to flip DOS slashes.
     */
    size_t cchPath = strlen(pszPath);
    if (cchPath < sizeof(pThis->aHdrs[0].Common.name))
    {
        memcpy(pThis->aHdrs[0].Common.name, pszPath, cchPath + 1);
#if RTPATH_STYLE != RTPATH_STR_F_STYLE_UNIX
        char *pszDosSlash = strchr(pThis->aHdrs[0].Common.name, '\\');
        while (pszDosSlash)
        {
            *pszDosSlash = '/';
            pszDosSlash = strchr(pszDosSlash + 1, '\\');
        }
#endif
    }
    else
    {
        /** @todo implement gnu and pax long name extensions. */
        return VERR_TAR_NAME_TOO_LONG;
    }

    /*
     * File mode.  ASSUME that the unix part of the IPRT mode mask is
     * compatible with the TAR/Unix world.
     */
    uint32_t uValue = pObjInfo->Attr.fMode & RTFS_UNIX_MASK;
    if (RTFS_IS_DIRECTORY(pObjInfo->Attr.fMode))
        uValue = (uValue & pThis->fDirModeAndMask) | pThis->fDirModeOrMask;
    else
        uValue = (uValue & pThis->fFileModeAndMask) | pThis->fFileModeOrMask;
    int rc = RTStrFormatU32(pThis->aHdrs[0].Common.mode, sizeof(pThis->aHdrs[0].Common.mode), uValue, 8 /*uBase*/,
                            -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Common.mode) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
    AssertRCReturn(rc, VERR_TAR_NUM_VALUE_TOO_LARGE);

    /*
     * uid & gid.  Just guard against NIL values as they won't fit.
     */
    uValue = pThis->uidOwner != NIL_RTUID ? pThis->uidOwner
           : pObjInfo->Attr.u.Unix.uid != NIL_RTUID ? pObjInfo->Attr.u.Unix.uid : 0;
    rc = RTStrFormatU32(pThis->aHdrs[0].Common.uid, sizeof(pThis->aHdrs[0].Common.uid), uValue,
                        8 /*uBase*/, -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Common.uid) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
    AssertRCReturn(rc, VERR_TAR_NUM_VALUE_TOO_LARGE);

    uValue = pThis->gidGroup != NIL_RTGID ? pThis->gidGroup
           : pObjInfo->Attr.u.Unix.gid != NIL_RTGID ? pObjInfo->Attr.u.Unix.gid : 0;
    rc = RTStrFormatU32(pThis->aHdrs[0].Common.gid, sizeof(pThis->aHdrs[0].Common.gid), uValue,
                        8 /*uBase*/, -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Common.gid) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
    AssertRCReturn(rc, VERR_TAR_NUM_VALUE_TOO_LARGE);

    /*
     * The file size.
     */
    rc = rtZipTarFssWriter_FormatOffset(pThis->aHdrs[0].Common.size, pObjInfo->cbObject);
    AssertRCReturn(rc, rc);

    /*
     * Modification time relative to unix epoc.
     */
    rc = RTStrFormatU64(pThis->aHdrs[0].Common.mtime, sizeof(pThis->aHdrs[0].Common.mtime),
                        RTTimeSpecGetSeconds(pThis->pModTime ? pThis->pModTime : &pObjInfo->ModificationTime),
                        8 /*uBase*/, -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Common.mtime) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
    AssertRCReturn(rc, rc);

    /* Skipping checksum for now */

    /*
     * The type flag.
     */
    if (chType == UINT8_MAX)
        switch (pObjInfo->Attr.fMode & RTFS_TYPE_MASK)
        {
            case RTFS_TYPE_FIFO:        chType = RTZIPTAR_TF_FIFO; break;
            case RTFS_TYPE_DEV_CHAR:    chType = RTZIPTAR_TF_CHR; break;
            case RTFS_TYPE_DIRECTORY:   chType = RTZIPTAR_TF_DIR; break;
            case RTFS_TYPE_DEV_BLOCK:   chType = RTZIPTAR_TF_BLK; break;
            case RTFS_TYPE_FILE:        chType = RTZIPTAR_TF_NORMAL; break;
            case RTFS_TYPE_SYMLINK:     chType = RTZIPTAR_TF_SYMLINK; break;
            case RTFS_TYPE_SOCKET:      chType = RTZIPTAR_TF_FIFO; break;
            case RTFS_TYPE_WHITEOUT:    AssertFailedReturn(VERR_WRONG_TYPE);
        }
    pThis->aHdrs[0].Common.typeflag = chType;

    /* No link name, at least not for now.  Caller might set it. */

    /*
     * Set TAR record magic and version.
     */
    if (pThis->enmFormat == RTZIPTARFORMAT_GNU)
        memcpy(pThis->aHdrs[0].Gnu.magic, RTZIPTAR_GNU_MAGIC, sizeof(pThis->aHdrs[0].Gnu.magic));
    else if (   pThis->enmFormat == RTZIPTARFORMAT_USTAR
             || pThis->enmFormat == RTZIPTARFORMAT_PAX)
    {
        memcpy(pThis->aHdrs[0].Common.magic, RTZIPTAR_USTAR_MAGIC, sizeof(pThis->aHdrs[0].Common.magic));
        memcpy(pThis->aHdrs[0].Common.version, RTZIPTAR_USTAR_VERSION, sizeof(pThis->aHdrs[0].Common.version));
    }
    else
        AssertFailedReturn(VERR_INTERNAL_ERROR_4);

    /*
     * Owner and group names.  Silently truncate them for now.
     */
    RTStrCopy(pThis->aHdrs[0].Common.uname, sizeof(pThis->aHdrs[0].Common.uname), pThis->pszOwner ? pThis->pszOwner : pszOwnerNm);
    RTStrCopy(pThis->aHdrs[0].Common.gname, sizeof(pThis->aHdrs[0].Common.uname), pThis->pszGroup ? pThis->pszGroup : pszGroupNm);

    /*
     * Char/block device numbers.
     */
    if (   RTFS_IS_DEV_BLOCK(pObjInfo->Attr.fMode)
        || RTFS_IS_DEV_CHAR(pObjInfo->Attr.fMode) )
    {
        rc = RTStrFormatU32(pThis->aHdrs[0].Common.devmajor, sizeof(pThis->aHdrs[0].Common.devmajor),
                            RTDEV_MAJOR(pObjInfo->Attr.u.Unix.Device),
                            8 /*uBase*/, -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Common.devmajor) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
        AssertRCReturn(rc, VERR_TAR_NUM_VALUE_TOO_LARGE);

        rc = RTStrFormatU32(pThis->aHdrs[0].Common.devminor, sizeof(pThis->aHdrs[0].Common.devmajor),
                            RTDEV_MINOR(pObjInfo->Attr.u.Unix.Device),
                            8 /*uBase*/, -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Common.devmajor) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
        AssertRCReturn(rc, VERR_TAR_NUM_VALUE_TOO_LARGE);
    }

#if 0 /** @todo why doesn't this work? */
    /*
     * Set GNU specific stuff.
     */
    if (pThis->enmFormat == RTZIPTARFORMAT_GNU)
    {
        rc = RTStrFormatU64(pThis->aHdrs[0].Gnu.ctime, sizeof(pThis->aHdrs[0].Gnu.ctime),
                            RTTimeSpecGetSeconds(&pObjInfo->ChangeTime),
                            8 /*uBase*/, -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Gnu.ctime) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
        AssertRCReturn(rc, rc);

        rc = RTStrFormatU64(pThis->aHdrs[0].Gnu.atime, sizeof(pThis->aHdrs[0].Gnu.atime),
                            RTTimeSpecGetSeconds(&pObjInfo->ChangeTime),
                            8 /*uBase*/, -1 /*cchWidth*/, sizeof(pThis->aHdrs[0].Gnu.atime) - 1, RTSTR_F_ZEROPAD | RTSTR_F_PRECISION);
        AssertRCReturn(rc, rc);
    }
#endif

    /*
     * Finally the checksum.
     */
    pThis->cHdrs = 1;
    return rtZipTarFssWriter_ChecksumHdr(&pThis->aHdrs[0]);
}




/**
 * @interface_method_impl{RTVFSOBJOPS,pfnClose}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_Close(void *pvThis)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush   = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;
    PRTZIPTARFSSTREAMWRITER     pParent = pPush->pParent;
    if (pParent)
    {
        if (pParent->pPush == pPush)
            rtZipTarFssWriter_CompleteCurrentPushFile(pParent);
        else
            AssertFailedStmt(pPush->pParent = NULL);
    }
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;

    /* Basic info (w/ additional unix attribs). */
    *pObjInfo = pPush->ObjInfo;
    pObjInfo->cbObject = pPush->cbCurrent;
    pObjInfo->cbAllocated = RT_ALIGN_64(pPush->cbCurrent, RTZIPTAR_BLOCKSIZE);

    /* Additional info. */
    switch (enmAddAttr)
    {
        case RTFSOBJATTRADD_NOTHING:
        case RTFSOBJATTRADD_UNIX:
            Assert(pObjInfo->Attr.enmAdditional == RTFSOBJATTRADD_UNIX);
            break;

        case RTFSOBJATTRADD_UNIX_OWNER:
            pObjInfo->Attr.u.UnixOwner.uid = pPush->ObjInfo.Attr.u.Unix.uid;
            if (pPush->pParent)
                strcpy(pObjInfo->Attr.u.UnixOwner.szName, pPush->pParent->aHdrs[0].Common.uname);
            else
                pObjInfo->Attr.u.UnixOwner.szName[0] = '\0';
            pObjInfo->Attr.enmAdditional = enmAddAttr;
            break;

        case RTFSOBJATTRADD_UNIX_GROUP:
            pObjInfo->Attr.u.UnixGroup.gid = pPush->ObjInfo.Attr.u.Unix.gid;
            if (pPush->pParent)
                strcpy(pObjInfo->Attr.u.UnixGroup.szName, pPush->pParent->aHdrs[0].Common.uname);
            else
                pObjInfo->Attr.u.UnixGroup.szName[0] = '\0';
            pObjInfo->Attr.enmAdditional = enmAddAttr;
            break;

        case RTFSOBJATTRADD_EASIZE:
            pObjInfo->Attr.u.EASize.cb = 0;
            pObjInfo->Attr.enmAdditional = enmAddAttr;
            break;

        default:
        AssertFailed();
    }

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnRead}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_Read(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbRead)
{
    /* No read support, sorry. */
    RT_NOREF(pvThis, off, pSgBuf, fBlocking, pcbRead);
    AssertFailed();
    return VERR_ACCESS_DENIED;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnWrite}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_Write(void *pvThis, RTFOFF off, PCRTSGBUF pSgBuf, bool fBlocking, size_t *pcbWritten)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush   = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;
    PRTZIPTARFSSTREAMWRITER     pParent = pPush->pParent;
    AssertPtrReturn(pParent, VERR_WRONG_ORDER);

    int rc = pParent->rcFatal;
    AssertRCReturn(rc, rc);

    /*
     * Single segment at a time.
     */
    Assert(pSgBuf->cSegs == 1);
    size_t      cbToWrite = pSgBuf->paSegs[0].cbSeg;
    void const *pvToWrite = pSgBuf->paSegs[0].pvSeg;

    /*
     * Hopefully we don't need to seek.  But if we do, let the seek method do
     * it as it's not entirely trivial.
     */
    if (   off < 0
        || (uint64_t)off == pPush->offCurrent)
        rc = VINF_SUCCESS;
    else
        rc = rtZipTarWriterPush_Seek(pvThis, off, RTFILE_SEEK_BEGIN, NULL);
    if (RT_SUCCESS(rc))
    {
        Assert(pPush->offCurrent <= pPush->cbExpected);
        Assert(pPush->offCurrent <= pPush->cbCurrent);
        AssertMsgReturn(cbToWrite <= pPush->cbExpected - pPush->offCurrent,
                        ("offCurrent=%#RX64 + cbToWrite=%#zx = %#RX64; cbExpected=%RX64\n",
                         pPush->offCurrent, cbToWrite, pPush->offCurrent + cbToWrite, pPush->cbExpected),
                        VERR_DISK_FULL);
        size_t cbWritten = 0;
        rc = RTVfsIoStrmWrite(pParent->hVfsIos, pvToWrite, cbToWrite, fBlocking, &cbWritten);
        if (RT_SUCCESS(rc))
        {
            pPush->offCurrent += cbWritten;
            if (pPush->offCurrent > pPush->cbCurrent)
            {
                pParent->cbWritten = pPush->offCurrent - pPush->cbCurrent;
                pPush->cbCurrent   = pPush->offCurrent;
            }
            if (pcbWritten)
                *pcbWritten = cbWritten;
        }
    }

    /*
     * Fatal errors get down here, non-fatal ones returns earlier.
     */
    if (RT_SUCCESS(rc))
        return VINF_SUCCESS;
    pParent->rcFatal = rc;
    return rc;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnFlush}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_Flush(void *pvThis)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush   = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;
    PRTZIPTARFSSTREAMWRITER     pParent = pPush->pParent;
    AssertPtrReturn(pParent, VERR_WRONG_ORDER);
    int rc = pParent->rcFatal;
    if (RT_SUCCESS(rc))
        pParent->rcFatal = rc = RTVfsIoStrmFlush(pParent->hVfsIos);
    return rc;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnPollOne}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_PollOne(void *pvThis, uint32_t fEvents, RTMSINTERVAL cMillies, bool fIntr,
                                                    uint32_t *pfRetEvents)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;
    PRTZIPTARFSSTREAMWRITER     pParent = pPush->pParent;
    AssertPtrReturn(pParent, VERR_WRONG_ORDER);
    return RTVfsIoStrmPoll(pParent->hVfsIos, fEvents, cMillies, fIntr, pfRetEvents);
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnTell}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_Tell(void *pvThis, PRTFOFF poffActual)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;
    *poffActual = (RTFOFF)pPush->offCurrent;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSIOSTREAMOPS,pfnSkip}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_Skip(void *pvThis, RTFOFF cb)
{
    RT_NOREF(pvThis, cb);
    AssertFailed();
    return VERR_ACCESS_DENIED;
}


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


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


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


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnSeek}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_Seek(void *pvThis, RTFOFF offSeek, unsigned uMethod, PRTFOFF poffActual)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush   = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;
    PRTZIPTARFSSTREAMWRITER     pParent = pPush->pParent;
    AssertPtrReturn(pParent, VERR_WRONG_ORDER);

    int rc = pParent->rcFatal;
    AssertRCReturn(rc, rc);
    Assert(pPush->offCurrent <= pPush->cbCurrent);

    /*
     * Calculate the new file offset.
     */
    RTFOFF offNewSigned;
    switch (uMethod)
    {
        case RTFILE_SEEK_BEGIN:
            offNewSigned = offSeek;
            break;
        case RTFILE_SEEK_CURRENT:
            offNewSigned = pPush->offCurrent + offSeek;
            break;
        case RTFILE_SEEK_END:
            offNewSigned = pPush->cbCurrent + offSeek;
            break;
        default:
            AssertFailedReturn(VERR_INVALID_PARAMETER);
    }

    /*
     * Check the new file offset against expectations.
     */
    AssertMsgReturn(offNewSigned >= 0, ("offNewSigned=%RTfoff\n", offNewSigned), VERR_NEGATIVE_SEEK);

    uint64_t offNew = (uint64_t)offNewSigned;
    AssertMsgReturn(offNew <= pPush->cbExpected, ("offNew=%#RX64 cbExpected=%#Rx64\n", offNew, pPush->cbExpected), VERR_SEEK);

    /*
     * Any change at all?  We can always hope...
     */
    if (offNew == pPush->offCurrent)
    { }
    /*
     * Gap that needs zero filling?
     */
    else if (offNew > pPush->cbCurrent)
    {
        if (pPush->offCurrent != pPush->cbCurrent)
        {
            AssertReturn(pParent->hVfsFile != NIL_RTVFSFILE, VERR_NOT_A_FILE);
            rc = RTVfsFileSeek(pParent->hVfsFile, pPush->offData + pPush->cbCurrent, RTFILE_SEEK_BEGIN, NULL);
            if (RT_FAILURE(rc))
                return pParent->rcFatal = rc;
            pPush->offCurrent = pPush->cbCurrent;
        }

        uint64_t cbToZero = offNew - pPush->cbCurrent;
        rc = RTVfsIoStrmZeroFill(pParent->hVfsIos, cbToZero);
        if (RT_FAILURE(rc))
            return pParent->rcFatal = rc;
        pParent->cbWritten += cbToZero;
        pPush->cbCurrent = pPush->offCurrent = offNew;
    }
    /*
     * Just change the file position to somewhere we've already written.
     */
    else
    {
        AssertReturn(pParent->hVfsFile != NIL_RTVFSFILE, VERR_NOT_A_FILE);
        rc = RTVfsFileSeek(pParent->hVfsFile, pPush->offData + offNew, RTFILE_SEEK_BEGIN, NULL);
        if (RT_FAILURE(rc))
            return pParent->rcFatal = rc;
        pPush->offCurrent = offNew;
    }
    Assert(pPush->offCurrent <= pPush->cbCurrent);

    if (poffActual)
        *poffActual = pPush->offCurrent;
    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSFILEOPS,pfnQuerySize}
 */
static DECLCALLBACK(int) rtZipTarWriterPush_QuerySize(void *pvThis, uint64_t *pcbFile)
{
    PRTZIPTARFSSTREAMWRITERPUSH pPush = (PRTZIPTARFSSTREAMWRITERPUSH)pvThis;
    *pcbFile = pPush->cbCurrent;
    return VINF_SUCCESS;
}


/**
 * TAR writer push I/O stream operations.
 */
DECL_HIDDEN_CONST(const RTVFSIOSTREAMOPS) g_rtZipTarWriterIoStrmOps =
{
    { /* Obj */
        RTVFSOBJOPS_VERSION,
        RTVFSOBJTYPE_IO_STREAM,
        "TAR push I/O Stream",
        rtZipTarWriterPush_Close,
        rtZipTarWriterPush_QueryInfo,
        NULL,
        RTVFSOBJOPS_VERSION
    },
    RTVFSIOSTREAMOPS_VERSION,
    RTVFSIOSTREAMOPS_FEAT_NO_SG,
    rtZipTarWriterPush_Read,
    rtZipTarWriterPush_Write,
    rtZipTarWriterPush_Flush,
    rtZipTarWriterPush_PollOne,
    rtZipTarWriterPush_Tell,
    rtZipTarWriterPush_Skip,
    NULL /*ZeroFill*/,
    RTVFSIOSTREAMOPS_VERSION,
};


/**
 * TAR writer push file operations.
 */
DECL_HIDDEN_CONST(const RTVFSFILEOPS) g_rtZipTarWriterFileOps =
{
    { /* Stream */
        { /* Obj */
            RTVFSOBJOPS_VERSION,
            RTVFSOBJTYPE_FILE,
            "TAR push file",
            rtZipTarWriterPush_Close,
            rtZipTarWriterPush_QueryInfo,
            NULL,
            RTVFSOBJOPS_VERSION
        },
        RTVFSIOSTREAMOPS_VERSION,
        RTVFSIOSTREAMOPS_FEAT_NO_SG,
        rtZipTarWriterPush_Read,
        rtZipTarWriterPush_Write,
        rtZipTarWriterPush_Flush,
        rtZipTarWriterPush_PollOne,
        rtZipTarWriterPush_Tell,
        rtZipTarWriterPush_Skip,
        NULL /*ZeroFill*/,
        RTVFSIOSTREAMOPS_VERSION,
    },
    RTVFSFILEOPS_VERSION,
    0,
    { /* ObjSet */
        RTVFSOBJSETOPS_VERSION,
        RT_UOFFSETOF(RTVFSFILEOPS, ObjSet) - RT_UOFFSETOF(RTVFSFILEOPS, Stream.Obj),
        rtZipTarWriterPush_SetMode,
        rtZipTarWriterPush_SetTimes,
        rtZipTarWriterPush_SetOwner,
        RTVFSOBJSETOPS_VERSION
    },
    rtZipTarWriterPush_Seek,
    rtZipTarWriterPush_QuerySize,
    NULL /*SetSize*/,
    NULL /*QueryMaxSize*/,
    RTVFSFILEOPS_VERSION
};



/**
 * Checks rcFatal and completes any current push file.
 *
 * On return the output stream position will be at the next header location.
 *
 * After this call, the push object no longer can write anything.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 */
static int rtZipTarFssWriter_CompleteCurrentPushFile(PRTZIPTARFSSTREAMWRITER pThis)
{
    /*
     * Check if there is a push file pending, remove it if there is.
     * We also check for fatal errors at this point so the caller doesn't need to.
     */
    PRTZIPTARFSSTREAMWRITERPUSH pPush = pThis->pPush;
    if (!pPush)
    {
        AssertRC(pThis->rcFatal);
        return pThis->rcFatal;
    }

    pThis->pPush   = NULL;
    pPush->pParent = NULL;

    int rc = pThis->rcFatal;
    AssertRCReturn(rc, rc);

    /*
     * Do we need to update the header.  pThis->aHdrs[0] will retain the current
     * content at pPush->offHdr and we only need to update the size.
     */
    if (pPush->fOpenEnded)
    {
        rc = rtZipTarFssWriter_FormatOffset(pThis->aHdrs[0].Common.size, pPush->cbCurrent);
        if (RT_SUCCESS(rc))
            rc = rtZipTarFssWriter_ChecksumHdr(&pThis->aHdrs[0]);
        if (RT_SUCCESS(rc))
        {
            rc = RTVfsFileWriteAt(pThis->hVfsFile, pPush->offHdr, &pThis->aHdrs[0], sizeof(pThis->aHdrs[0]), NULL);
            if (RT_SUCCESS(rc))
                rc = RTVfsFileSeek(pThis->hVfsFile, pPush->offData + pPush->cbCurrent, RTFILE_SEEK_BEGIN, NULL);
        }
    }
    /*
     * Check that we've received all the data we were promissed in the PushFile
     * call, fail if we weren't.
     */
    else
        AssertMsgStmt(pPush->cbCurrent == pPush->cbExpected,
                      ("cbCurrent=%#RX64 cbExpected=%#RX64\n", pPush->cbCurrent, pPush->cbExpected),
                      rc = VERR_BUFFER_UNDERFLOW);
    if (RT_SUCCESS(rc))
    {
        /*
         * Do zero padding if necessary.
         */
        if (pPush->cbCurrent & (RTZIPTAR_BLOCKSIZE - 1))
        {
            size_t cbToZero = RTZIPTAR_BLOCKSIZE - (pPush->cbCurrent & (RTZIPTAR_BLOCKSIZE - 1));
            rc = RTVfsIoStrmWrite(pThis->hVfsIos, g_abRTZero4K, cbToZero, true /*fBlocking*/, NULL);
            if (RT_SUCCESS(rc))
                pThis->cbWritten += cbToZero;
        }
    }

    if (RT_SUCCESS(rc))
        return VINF_SUCCESS;
    pThis->rcFatal = rc;
    return rc;
}


/**
 * Does the actual work for rtZipTarFssWriter_SwitchToWriteMode().
 *
 * @note    We won't be here if we've truncate the tar file.   Truncation
 *          switches it into write mode.
 */
DECL_NO_INLINE(static, int) rtZipTarFssWriter_SwitchToWriteModeSlow(PRTZIPTARFSSTREAMWRITER pThis)
{
    /* Always go thru rtZipTarFssWriter_SwitchToWriteMode(). */
    AssertRCReturn(pThis->rcFatal, pThis->rcFatal);
    AssertReturn(!pThis->fWriting, VINF_SUCCESS);
    AssertReturn(pThis->fFlags & RTZIPTAR_C_UPDATE, VERR_INTERNAL_ERROR_3);

    /*
     * If we're not at the end, locate the end of the tar file.
     * Because I'm lazy, we do that using rtZipTarFss_Next.  This isn't entirely
     * optimial as it involves VFS object instantations and such.
     */
    /** @todo Optimize skipping to end of tar file in update mode. */
    while (!pThis->pRead->fEndOfStream)
    {
        int rc = rtZipTarFss_Next(pThis->pRead, NULL, NULL, NULL);
        if (rc == VERR_EOF)
            break;
        AssertRCReturn(rc, rc);
    }

    /*
     * Seek to the desired cut-off point and indicate that we've switched to writing.
     */
    Assert(pThis->pRead->offNextHdr == pThis->pRead->offCurHdr);
    int rc = RTVfsFileSeek(pThis->hVfsFile, pThis->pRead->offNextHdr, RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
    if (RT_SUCCESS(rc))
        pThis->fWriting = true;
    else
        pThis->rcFatal = rc;

    return rc;
}


/**
 * Switches the stream into writing mode if necessary.
 *
 * @returns VBox status code.
 * @param   pThis           The TAR writer instance.
 *
 */
DECLINLINE(int) rtZipTarFssWriter_SwitchToWriteMode(PRTZIPTARFSSTREAMWRITER pThis)
{
    if (pThis->fWriting)
        return VINF_SUCCESS; /* ASSUMES caller already checked pThis->rcFatal. */
    return rtZipTarFssWriter_SwitchToWriteModeSlow(pThis);
}


/**
 * Allocates a buffer for transfering file data.
 *
 * @note    Will use the 3rd TAR header as fallback buffer if we're out of
 *          memory!
 *
 * @returns Pointer to buffer (won't ever fail).
 * @param   pThis           The TAR writer instance.
 * @param   pcbBuf          Where to return the buffer size.  This will be a
 *                          multiple of the TAR block size.
 * @param   ppvFree         Where to return the pointer to pass to RTMemTmpFree
 *                          when done with the buffer.
 * @param   cbFile          The file size.  Used as a buffer size hint.
 */
static uint8_t *rtZipTarFssWriter_AllocBuf(PRTZIPTARFSSTREAMWRITER pThis, size_t *pcbBuf, void **ppvFree, uint64_t cbObject)
{
    uint8_t *pbBuf;

    /*
     * If this is a large file, try for a large buffer with 16KB alignment.
     */
    if (cbObject >= _64M)
    {
        pbBuf = (uint8_t *)RTMemTmpAlloc(_2M + _16K - 1);
        if (pbBuf)
        {
            *pcbBuf  = _2M;
            *ppvFree = pbBuf;
            return RT_ALIGN_PT(pbBuf, _16K, uint8_t *);
        }
    }
    /*
     * 4KB aligned 512KB buffer if larger 512KB or larger.
     */
    else if (cbObject >= _512K)
    {
        pbBuf = (uint8_t *)RTMemTmpAlloc(_512K + _4K - 1);
        if (pbBuf)
        {
            *pcbBuf  = _512K;
            *ppvFree = pbBuf;
            return RT_ALIGN_PT(pbBuf, _4K, uint8_t *);
        }
    }
    /*
     * Otherwise a 4KB aligned 128KB buffer.
     */
    else
    {
        pbBuf = (uint8_t *)RTMemTmpAlloc(_128K + _4K - 1);
        if (pbBuf)
        {
            *pcbBuf  = _128K;
            *ppvFree = pbBuf;
            return RT_ALIGN_PT(pbBuf, _4K, uint8_t *);
        }
    }

    /*
     * If allocation failed, fallback on a 16KB buffer without any extra alignment.
     */
    pbBuf = (uint8_t *)RTMemTmpAlloc(_16K);
    if (pbBuf)
    {
        *pcbBuf  = _16K;
        *ppvFree = pbBuf;
        return pbBuf;
    }

    /*
     * Final fallback, 512KB buffer using the 3rd header.
     */
    AssertCompile(RT_ELEMENTS(pThis->aHdrs) >= 3);
    *pcbBuf  = sizeof(pThis->aHdrs[2]);
    *ppvFree = NULL;
    return (uint8_t *)&pThis->aHdrs[2];
}


/**
 * Frees the sparse info for a TAR file.
 *
 * @param   pSparse         The sparse info to free.
 */
static void rtZipTarFssWriter_SparseInfoDestroy(PRTZIPTARSPARSE pSparse)
{
    PRTZIPTARSPARSECHUNK pCur;
    PRTZIPTARSPARSECHUNK pNext;
    RTListForEachSafe(&pSparse->ChunkHead, pCur, pNext, RTZIPTARSPARSECHUNK, Entry)
        RTMemTmpFree(pCur);
    RTMemTmpFree(pSparse);
}


/**
 * Adds a data span to the sparse info.
 *
 * @returns VINF_SUCCESS or VINF_NO_TMP_MEMORY.
 * @param   pSparse         The sparse info to free.
 * @param   offSpan         Offset of the span.
 * @param   cbSpan          Number of bytes.
 */
static int rtZipTarFssWriter_SparseInfoAddSpan(PRTZIPTARSPARSE pSparse, uint64_t offSpan, uint64_t cbSpan)
{
    /*
     * Get the chunk we're adding it to.
     */
    PRTZIPTARSPARSECHUNK pChunk;
    if (pSparse->iNextSpan != 0)
    {
        pChunk = RTListGetLast(&pSparse->ChunkHead, RTZIPTARSPARSECHUNK, Entry);
        Assert(pSparse->iNextSpan < RT_ELEMENTS(pChunk->aSpans));
    }
    else
    {
        pChunk = (PRTZIPTARSPARSECHUNK)RTMemTmpAllocZ(sizeof(*pChunk));
        if (!pChunk)
            return VERR_NO_TMP_MEMORY;
        RTListAppend(&pSparse->ChunkHead, &pChunk->Entry);
    }

    /*
     * Append it.
     */
    pSparse->cDataSpans  += 1;
    pSparse->cbDataSpans += cbSpan;
    pChunk->aSpans[pSparse->iNextSpan].cb  = cbSpan;
    pChunk->aSpans[pSparse->iNextSpan].off = offSpan;
    if (++pSparse->iNextSpan >= RT_ELEMENTS(pChunk->aSpans))
        pSparse->iNextSpan = 0;
    return VINF_SUCCESS;
}


/**
 * Scans the input stream recording non-zero blocks.
 */
static int rtZipTarFssWriter_ScanSparseFile(PRTZIPTARFSSTREAMWRITER pThis, RTVFSFILE hVfsFile, uint64_t cbFile,
                                            size_t cbBuf, uint8_t *pbBuf, PRTZIPTARSPARSE *ppSparse)
{
    RT_NOREF(pThis);

    /*
     * Create an empty sparse info bundle.
     */
    PRTZIPTARSPARSE pSparse = (PRTZIPTARSPARSE)RTMemTmpAlloc(sizeof(*pSparse));
    AssertReturn(pSparse, VERR_NO_MEMORY);
    pSparse->cbDataSpans = 0;
    pSparse->cDataSpans  = 0;
    pSparse->iNextSpan   = 0;
    RTListInit(&pSparse->ChunkHead);

    /*
     * Scan the file from the start.
     */
    int rc = RTVfsFileSeek(hVfsFile, 0, RTFILE_SEEK_BEGIN, NULL);
    if (RT_SUCCESS(rc))
    {
        bool        fZeroSpan = false;
        uint64_t    offSpan   = 0;
        uint64_t    cbSpan    = 0;

        for (uint64_t off = 0; off < cbFile;)
        {
            uint64_t cbLeft   = cbFile - off;
            size_t   cbToRead = cbLeft >= cbBuf ? cbBuf : (size_t)cbLeft;
            rc = RTVfsFileRead(hVfsFile, pbBuf, cbToRead, NULL);
            if (RT_FAILURE(rc))
                break;
            size_t cBlocks = cbToRead / RTZIPTAR_BLOCKSIZE;

            /* Zero pad the final buffer to a multiple of the blocksize. */
            if (!(cbToRead & (RTZIPTAR_BLOCKSIZE - 1)))
            { /* likely */ }
            else
            {
                AssertBreakStmt(cbLeft == cbToRead, rc = VERR_INTERNAL_ERROR_3);
                RT_BZERO(&pbBuf[cbToRead], RTZIPTAR_BLOCKSIZE - (cbToRead & (RTZIPTAR_BLOCKSIZE - 1)));
                cBlocks++;
            }

            /*
             * Process the blocks we've just read one by one.
             */
            uint8_t const *pbBlock = pbBuf;
            for (size_t iBlock = 0; iBlock < cBlocks; iBlock++)
            {
                bool fZeroBlock = ASMMemIsZero(pbBlock, RTZIPTAR_BLOCKSIZE);
                if (fZeroBlock == fZeroSpan)
                    cbSpan += RTZIPTAR_BLOCKSIZE;
                else
                {
                    if (!fZeroSpan && cbSpan)
                    {
                        rc = rtZipTarFssWriter_SparseInfoAddSpan(pSparse, offSpan, cbSpan);
                        if (RT_FAILURE(rc))
                            break;
                    }
                    fZeroSpan = fZeroBlock;
                    offSpan   = off;
                    cbSpan    = RTZIPTAR_BLOCKSIZE;
                }

                /* next block. */
                pbBlock += RTZIPTAR_BLOCKSIZE;
                off     += RTZIPTAR_BLOCKSIZE;
            }
        }

        /*
         * Deal with the final span.  If we've got zeros thowards the end, we
         * must add a zero byte data span at the end.
         */
        if (RT_SUCCESS(rc))
        {
            if (!fZeroSpan && cbSpan)
            {
                if (cbFile & (RTZIPTAR_BLOCKSIZE - 1))
                {
                    Assert(!(cbSpan & (RTZIPTAR_BLOCKSIZE - 1)));
                    cbSpan -= RTZIPTAR_BLOCKSIZE;
                    cbSpan |= cbFile & (RTZIPTAR_BLOCKSIZE - 1);
                }
                rc = rtZipTarFssWriter_SparseInfoAddSpan(pSparse, offSpan, cbSpan);
            }
            if (RT_SUCCESS(rc))
                rc = rtZipTarFssWriter_SparseInfoAddSpan(pSparse, cbFile, 0);
        }
    }

    if (RT_SUCCESS(rc))
    {
        /*
         * Return the file back to the start position before we return so that we
         * can segue into the regular rtZipTarFssWriter_AddFile without further ado.
         */
        rc = RTVfsFileSeek(hVfsFile, 0, RTFILE_SEEK_BEGIN, NULL);
        if (RT_SUCCESS(rc))
        {
            *ppSparse = pSparse;
            return VINF_SUCCESS;
        }
    }

    rtZipTarFssWriter_SparseInfoDestroy(pSparse);
    *ppSparse = NULL;
    return rc;
}


/**
 * Writes GNU the sparse file headers.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 * @param   pszPath         The path to the file.
 * @param   pObjInfo        The object information.
 * @param   pszOwnerNm      The owner name.
 * @param   pszGroupNm      The group name.
 * @param   pSparse         The sparse file info.
 */
static int rtZipTarFssWriter_WriteGnuSparseHeaders(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath,  PCRTFSOBJINFO pObjInfo,
                                                   const char *pszOwnerNm, const char *pszGroupNm, PCRTZIPTARSPARSE pSparse)
{
    /*
     * Format the first header.
     */
    int rc = rtZipTarFssWriter_ObjInfoToHdr(pThis, pszPath, pObjInfo, pszOwnerNm, pszGroupNm, RTZIPTAR_TF_GNU_SPARSE);
    AssertRCReturn(rc, rc);
    AssertReturn(pThis->cHdrs == 1, VERR_INTERNAL_ERROR_2);

    /* data size. */
    rc = rtZipTarFssWriter_FormatOffset(pThis->aHdrs[0].Common.size, pSparse->cbDataSpans);
    AssertRCReturn(rc, rc);

    /* realsize. */
    rc = rtZipTarFssWriter_FormatOffset(pThis->aHdrs[0].Gnu.realsize, pObjInfo->cbObject);
    AssertRCReturn(rc, rc);

    Assert(pThis->aHdrs[0].Gnu.isextended == 0);

    /*
     * Walk the sparse spans, fill and write headers one by one.
     */
    PRTZIPTARGNUSPARSE  paSparse    = &pThis->aHdrs[0].Gnu.sparse[0];
    uint32_t            cSparse     = RT_ELEMENTS(pThis->aHdrs[0].Gnu.sparse);
    uint32_t            iSparse     = 0;

    PRTZIPTARSPARSECHUNK const pLastChunk = RTListGetLast(&pSparse->ChunkHead, RTZIPTARSPARSECHUNK, Entry);
    PRTZIPTARSPARSECHUNK pChunk;
    RTListForEach(&pSparse->ChunkHead, pChunk, RTZIPTARSPARSECHUNK, Entry)
    {
        uint32_t cSpans = pChunk != pLastChunk || pSparse->iNextSpan == 0
                        ? RT_ELEMENTS(pChunk->aSpans) : pSparse->iNextSpan;
        for (uint32_t iSpan = 0; iSpan < cSpans; iSpan++)
        {
            /* Flush the header? */
            if (iSparse >= cSparse)
            {
                if (cSparse != RT_ELEMENTS(pThis->aHdrs[0].Gnu.sparse))
                    pThis->aHdrs[0].GnuSparse.isextended = 1; /* more headers to come */
                else
                {
                    pThis->aHdrs[0].Gnu.isextended = 1; /* more headers to come */
                    rc = rtZipTarFssWriter_ChecksumHdr(&pThis->aHdrs[0]);
                }
                if (RT_SUCCESS(rc))
                    rc = RTVfsIoStrmWrite(pThis->hVfsIos, &pThis->aHdrs[0], sizeof(pThis->aHdrs[0]), true /*fBlocking*/, NULL);
                if (RT_FAILURE(rc))
                    return rc;
                RT_ZERO(pThis->aHdrs[0]);
                cSparse  = RT_ELEMENTS(pThis->aHdrs[0].GnuSparse.sp);
                iSparse  = 0;
                paSparse = &pThis->aHdrs[0].GnuSparse.sp[0];
            }

            /* Append sparse data segment. */
            rc = rtZipTarFssWriter_FormatOffset(paSparse[iSparse].offset, pChunk->aSpans[iSpan].off);
            AssertRCReturn(rc, rc);
            rc = rtZipTarFssWriter_FormatOffset(paSparse[iSparse].numbytes, pChunk->aSpans[iSpan].cb);
            AssertRCReturn(rc, rc);
            iSparse++;
        }
    }

    /*
     * The final header.
     */
    if (iSparse != 0)
    {
        if (cSparse != RT_ELEMENTS(pThis->aHdrs[0].Gnu.sparse))
            Assert(pThis->aHdrs[0].GnuSparse.isextended == 0);
        else
        {
            Assert(pThis->aHdrs[0].Gnu.isextended == 0);
            rc = rtZipTarFssWriter_ChecksumHdr(&pThis->aHdrs[0]);
        }
        if (RT_SUCCESS(rc))
            rc = RTVfsIoStrmWrite(pThis->hVfsIos, &pThis->aHdrs[0], sizeof(pThis->aHdrs[0]), true /*fBlocking*/, NULL);
    }
    pThis->cHdrs = 0;
    return rc;
}


/**
 * Adds a potentially sparse file to the output.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 * @param   pszPath         The path to the file.
 * @param   hVfsFile        The potentially sparse file.
 * @param   hVfsIos         The I/O stream of the file. Same as @a hVfsFile.
 * @param   pObjInfo        The object information.
 * @param   pszOwnerNm      The owner name.
 * @param   pszGroupNm      The group name.
 */
static int rtZipTarFssWriter_AddFileSparse(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath, RTVFSFILE hVfsFile,
                                           RTVFSIOSTREAM hVfsIos, PCRTFSOBJINFO pObjInfo,
                                           const char *pszOwnerNm, const char *pszGroupNm)
{
    /*
     * Scan the input file to locate all zero blocks.
     */
    void    *pvBufFree;
    size_t   cbBuf;
    uint8_t *pbBuf = rtZipTarFssWriter_AllocBuf(pThis, &cbBuf, &pvBufFree, pObjInfo->cbObject);

    PRTZIPTARSPARSE pSparse;
    int rc = rtZipTarFssWriter_ScanSparseFile(pThis, hVfsFile, pObjInfo->cbObject, cbBuf, pbBuf, &pSparse);
    if (RT_SUCCESS(rc))
    {
        /*
         * If there aren't at least 2 zero blocks in the file, don't bother
         * doing the sparse stuff and store it as a normal file.
         */
        if (pSparse->cbDataSpans + RTZIPTAR_BLOCKSIZE > (uint64_t)pObjInfo->cbObject)
        {
            rtZipTarFssWriter_SparseInfoDestroy(pSparse);
            RTMemTmpFree(pvBufFree);
            return rtZipTarFssWriter_AddFile(pThis, pszPath, hVfsIos, pObjInfo, pszOwnerNm, pszGroupNm);
        }

        /*
         * Produce and write the headers.
         */
        if (pThis->enmFormat == RTZIPTARFORMAT_GNU)
            rc = rtZipTarFssWriter_WriteGnuSparseHeaders(pThis, pszPath, pObjInfo, pszOwnerNm, pszGroupNm, pSparse);
        else
            AssertStmt(pThis->enmFormat != RTZIPTARFORMAT_GNU, rc = VERR_NOT_IMPLEMENTED);
        if (RT_SUCCESS(rc))
        {
            /*
             * Write the file bytes.
             */
            PRTZIPTARSPARSECHUNK const pLastChunk = RTListGetLast(&pSparse->ChunkHead, RTZIPTARSPARSECHUNK, Entry);
            PRTZIPTARSPARSECHUNK pChunk;
            RTListForEach(&pSparse->ChunkHead, pChunk, RTZIPTARSPARSECHUNK, Entry)
            {
                uint32_t cSpans = pChunk != pLastChunk || pSparse->iNextSpan == 0
                                ? RT_ELEMENTS(pChunk->aSpans) : pSparse->iNextSpan;
                for (uint32_t iSpan = 0; iSpan < cSpans; iSpan++)
                {
                    rc = RTVfsFileSeek(hVfsFile, pChunk->aSpans[iSpan].off, RTFILE_SEEK_BEGIN, NULL);
                    if (RT_FAILURE(rc))
                        break;
                    uint64_t cbLeft = pChunk->aSpans[iSpan].cb;
                    Assert(   !(cbLeft & (RTZIPTAR_BLOCKSIZE - 1))
                           || (iSpan + 1 == cSpans && pChunk == pLastChunk));
                    while (cbLeft > 0)
                    {
                        size_t cbToRead = cbLeft >= cbBuf ? cbBuf : (size_t)cbLeft;
                        rc = RTVfsFileRead(hVfsFile, pbBuf, cbToRead, NULL);
                        if (RT_SUCCESS(rc))
                        {
                            rc = RTVfsIoStrmWrite(pThis->hVfsIos, pbBuf, cbToRead, true /*fBlocking*/, NULL);
                            if (RT_SUCCESS(rc))
                            {
                                pThis->cbWritten += cbToRead;
                                cbLeft           -= cbToRead;
                                continue;
                            }
                        }
                        break;
                    }
                    if (RT_FAILURE(rc))
                        break;
                }
            }

            /*
             * Do the zero padding.
             */
            if (   RT_SUCCESS(rc)
                && (pSparse->cbDataSpans & (RTZIPTAR_BLOCKSIZE - 1)))
            {
                size_t cbToZero = RTZIPTAR_BLOCKSIZE - (pSparse->cbDataSpans & (RTZIPTAR_BLOCKSIZE - 1));
                rc = RTVfsIoStrmWrite(pThis->hVfsIos, g_abRTZero4K, cbToZero, true /*fBlocking*/, NULL);
                if (RT_SUCCESS(rc))
                    pThis->cbWritten += cbToZero;
            }
        }

        if (RT_FAILURE(rc))
            pThis->rcFatal = rc;
        rtZipTarFssWriter_SparseInfoDestroy(pSparse);
    }
    RTMemTmpFree(pvBufFree);
    return rc;
}


/**
 * Adds an I/O stream of indeterminate length to the TAR file.
 *
 * This requires the output to be seekable, i.e. a file, because we need to go
 * back and update @c size field of the TAR header after pumping all the data
 * bytes thru and establishing the file length.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 * @param   pszPath         The path to the file.
 * @param   hVfsIos         The I/O stream of the file.
 * @param   pObjInfo        The object information.
 * @param   pszOwnerNm      The owner name.
 * @param   pszGroupNm      The group name.
 */
static int rtZipTarFssWriter_AddFileStream(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath, RTVFSIOSTREAM hVfsIos,
                                           PCRTFSOBJINFO pObjInfo, const char *pszOwnerNm, const char *pszGroupNm)
{
    AssertReturn(pThis->hVfsFile != NIL_RTVFSFILE, VERR_NOT_A_FILE);

    /*
     * Append the header.
     */
    int rc = rtZipTarFssWriter_ObjInfoToHdr(pThis, pszPath, pObjInfo, pszOwnerNm, pszGroupNm, UINT8_MAX);
    if (RT_SUCCESS(rc))
    {
        RTFOFF const offHdr = RTVfsFileTell(pThis->hVfsFile);
        if (offHdr >= 0)
        {
            rc = RTVfsIoStrmWrite(pThis->hVfsIos, pThis->aHdrs, pThis->cHdrs * sizeof(pThis->aHdrs[0]), true /*fBlocking*/, NULL);
            if (RT_SUCCESS(rc))
            {
                pThis->cbWritten += pThis->cHdrs * sizeof(pThis->aHdrs[0]);

                /*
                 * Transfer the bytes.
                 */
                void    *pvBufFree;
                size_t   cbBuf;
                uint8_t *pbBuf = rtZipTarFssWriter_AllocBuf(pThis, &cbBuf, &pvBufFree,
                                                            pObjInfo->cbObject > 0 && pObjInfo->cbObject != RTFOFF_MAX
                                                            ? pObjInfo->cbObject : _1G);

                uint64_t cbReadTotal = 0;
                for (;;)
                {
                    size_t cbRead = 0;
                    int rc2 = rc = RTVfsIoStrmRead(hVfsIos, pbBuf, cbBuf, true /*fBlocking*/, &cbRead);
                    if (RT_SUCCESS(rc))
                    {
                        cbReadTotal += cbRead;
                        rc = RTVfsIoStrmWrite(pThis->hVfsIos, pbBuf, cbRead, true /*fBlocking*/, NULL);
                        if (RT_SUCCESS(rc))
                        {
                            pThis->cbWritten += cbRead;
                            if (rc2 != VINF_EOF)
                                continue;
                        }
                    }
                    Assert(rc != VERR_EOF /* expecting VINF_EOF! */);
                    break;
                }

                RTMemTmpFree(pvBufFree);

                /*
                 * Do the zero padding.
                 */
                if ((cbReadTotal & (RTZIPTAR_BLOCKSIZE - 1)) && RT_SUCCESS(rc))
                {
                    size_t cbToZero = RTZIPTAR_BLOCKSIZE - (cbReadTotal & (RTZIPTAR_BLOCKSIZE - 1));
                    rc = RTVfsIoStrmWrite(pThis->hVfsIos, g_abRTZero4K, cbToZero, true /*fBlocking*/, NULL);
                    if (RT_SUCCESS(rc))
                        pThis->cbWritten += cbToZero;
                }

                /*
                 * Update the header.  We ASSUME that aHdr[0] is unmodified
                 * from before the data pumping above and just update the size.
                 */
                if ((RTFOFF)cbReadTotal != pObjInfo->cbObject && RT_SUCCESS(rc))
                {
                    RTFOFF const offRestore = RTVfsFileTell(pThis->hVfsFile);
                    if (offRestore >= 0)
                    {
                        rc = rtZipTarFssWriter_FormatOffset(pThis->aHdrs[0].Common.size, cbReadTotal);
                        if (RT_SUCCESS(rc))
                            rc = rtZipTarFssWriter_ChecksumHdr(&pThis->aHdrs[0]);
                        if (RT_SUCCESS(rc))
                        {
                            rc = RTVfsFileWriteAt(pThis->hVfsFile, offHdr, &pThis->aHdrs[0], sizeof(pThis->aHdrs[0]), NULL);
                            if (RT_SUCCESS(rc))
                                rc = RTVfsFileSeek(pThis->hVfsFile, offRestore, RTFILE_SEEK_BEGIN, NULL);
                        }
                    }
                    else
                        rc = (int)offRestore;
                }

                if (RT_SUCCESS(rc))
                    return VINF_SUCCESS;
            }
        }
        else
            rc = (int)offHdr;
        pThis->rcFatal = rc;
    }
    return rc;
}


/**
 * Adds a file to the stream.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 * @param   pszPath         The path to the file.
 * @param   hVfsIos         The I/O stream of the file.
 * @param   fFlags          The RTVFSFSSTREAMOPS::pfnAdd flags.
 * @param   pObjInfo        The object information.
 * @param   pszOwnerNm      The owner name.
 * @param   pszGroupNm      The group name.
 */
static int rtZipTarFssWriter_AddFile(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath, RTVFSIOSTREAM hVfsIos,
                                     PCRTFSOBJINFO pObjInfo, const char *pszOwnerNm, const char *pszGroupNm)
{
    /*
     * Append the header.
     */
    int rc = rtZipTarFssWriter_ObjInfoToHdr(pThis, pszPath, pObjInfo, pszOwnerNm, pszGroupNm, UINT8_MAX);
    if (RT_SUCCESS(rc))
    {
        rc = RTVfsIoStrmWrite(pThis->hVfsIos, pThis->aHdrs, pThis->cHdrs * sizeof(pThis->aHdrs[0]), true /*fBlocking*/, NULL);
        if (RT_SUCCESS(rc))
        {
            pThis->cbWritten += pThis->cHdrs * sizeof(pThis->aHdrs[0]);

            /*
             * Copy the bytes.  Padding the last buffer to a multiple of 512.
             */
            void    *pvBufFree;
            size_t   cbBuf;
            uint8_t *pbBuf = rtZipTarFssWriter_AllocBuf(pThis, &cbBuf, &pvBufFree, pObjInfo->cbObject);

            uint64_t cbLeft = pObjInfo->cbObject;
            while (cbLeft > 0)
            {
                size_t cbRead = cbLeft > cbBuf ? cbBuf : (size_t)cbLeft;
                rc = RTVfsIoStrmRead(hVfsIos, pbBuf, cbRead, true /*fBlocking*/, NULL);
                if (RT_FAILURE(rc))
                    break;

                size_t cbToWrite = cbRead;
                if (cbRead & (RTZIPTAR_BLOCKSIZE - 1))
                {
                    size_t cbToZero = RTZIPTAR_BLOCKSIZE - (cbRead & (RTZIPTAR_BLOCKSIZE - 1));
                    memset(&pbBuf[cbRead], 0, cbToZero);
                    cbToWrite += cbToZero;
                }

                rc = RTVfsIoStrmWrite(pThis->hVfsIos, pbBuf, cbToWrite, true /*fBlocking*/, NULL);
                if (RT_FAILURE(rc))
                    break;
                pThis->cbWritten += cbToWrite;
                cbLeft -= cbRead;
            }

            RTMemTmpFree(pvBufFree);

            if (RT_SUCCESS(rc))
                return VINF_SUCCESS;
        }
        pThis->rcFatal = rc;
    }
    return rc;
}


/**
 * Adds a symbolic link to the stream.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 * @param   pszPath         The path to the object.
 * @param   hVfsSymlink     The symbolic link object to add.
 * @param   pObjInfo        The object information.
 * @param   pszOwnerNm      The owner name.
 * @param   pszGroupNm      The group name.
 */
static int rtZipTarFssWriter_AddSymlink(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath, RTVFSSYMLINK hVfsSymlink,
                                        PCRTFSOBJINFO pObjInfo,  const char *pszOwnerNm, const char *pszGroupNm)
{
    /*
     * Read the symlink target first and check that it's not too long.
     * Flip DOS slashes.
     */
    char szTarget[RTPATH_MAX];
    int rc = RTVfsSymlinkRead(hVfsSymlink, szTarget,  sizeof(szTarget));
    if (RT_SUCCESS(rc))
    {
#if RTPATH_STYLE != RTPATH_STR_F_STYLE_UNIX
        char *pszDosSlash = strchr(szTarget, '\\');
        while (pszDosSlash)
        {
            *pszDosSlash = '/';
            pszDosSlash = strchr(pszDosSlash + 1, '\\');
        }
#endif
        size_t cchTarget = strlen(szTarget);
        if (cchTarget < sizeof(pThis->aHdrs[0].Common.linkname))
        {
            /*
             * Create a header, add the link target and push it out.
             */
            rc = rtZipTarFssWriter_ObjInfoToHdr(pThis, pszPath, pObjInfo, pszOwnerNm, pszGroupNm, UINT8_MAX);
            if (RT_SUCCESS(rc))
            {
                memcpy(pThis->aHdrs[0].Common.linkname, szTarget, cchTarget + 1);
                rc = rtZipTarFssWriter_ChecksumHdr(&pThis->aHdrs[0]);
                if (RT_SUCCESS(rc))
                {
                    rc = RTVfsIoStrmWrite(pThis->hVfsIos, pThis->aHdrs, pThis->cHdrs * sizeof(pThis->aHdrs[0]),
                                          true /*fBlocking*/, NULL);
                    if (RT_SUCCESS(rc))
                    {
                        pThis->cbWritten += pThis->cHdrs * sizeof(pThis->aHdrs[0]);
                        return VINF_SUCCESS;
                    }
                    pThis->rcFatal = rc;
                }
            }
        }
        else
        {
            /** @todo implement gnu and pax long name extensions. */
            rc = VERR_TAR_NAME_TOO_LONG;
        }
    }
    return rc;
}


/**
 * Adds a simple object to the stream.
 *
 * Simple objects only contains metadata, no actual data bits.  Directories,
 * devices, fifos, sockets and such.
 *
 * @returns IPRT status code.
 * @param   pThis           The TAR writer instance.
 * @param   pszPath         The path to the object.
 * @param   pObjInfo        The object information.
 * @param   pszOwnerNm      The owner name.
 * @param   pszGroupNm      The group name.
 */
static int rtZipTarFssWriter_AddSimpleObject(PRTZIPTARFSSTREAMWRITER pThis, const char *pszPath, PCRTFSOBJINFO pObjInfo,
                                             const char *pszOwnerNm, const char *pszGroupNm)
{
    int rc = rtZipTarFssWriter_ObjInfoToHdr(pThis, pszPath, pObjInfo, pszOwnerNm, pszGroupNm, UINT8_MAX);
    if (RT_SUCCESS(rc))
    {
        rc = RTVfsIoStrmWrite(pThis->hVfsIos, pThis->aHdrs, pThis->cHdrs * sizeof(pThis->aHdrs[0]), true /*fBlocking*/, NULL);
        if (RT_SUCCESS(rc))
        {
            pThis->cbWritten += pThis->cHdrs * sizeof(pThis->aHdrs[0]);
            return VINF_SUCCESS;
        }
        pThis->rcFatal = rc;
    }
    return rc;
}


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

    rtZipTarFssWriter_CompleteCurrentPushFile(pThis);

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

    if (pThis->hVfsFile != NIL_RTVFSFILE)
    {
        RTVfsFileRelease(pThis->hVfsFile);
        pThis->hVfsFile = NIL_RTVFSFILE;
    }

    if (pThis->pszOwner)
    {
        RTStrFree(pThis->pszOwner);
        pThis->pszOwner = NULL;
    }
    if (pThis->pszGroup)
    {
        RTStrFree(pThis->pszGroup);
        pThis->pszGroup = NULL;
    }
    if (pThis->pszPrefix)
    {
        RTStrFree(pThis->pszPrefix);
        pThis->pszPrefix = NULL;
    }

    return VINF_SUCCESS;
}


/**
 * @interface_method_impl{RTVFSOBJOPS,pfnQueryInfo}
 */
static DECLCALLBACK(int) rtZipTarFssWriter_QueryInfo(void *pvThis, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAddAttr)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)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) rtZipTarFssWriter_Next(void *pvThis, char **ppszName, RTVFSOBJTYPE *penmType, PRTVFSOBJ phVfsObj)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)pvThis;

    /*
     * This only works in update mode and up to the point where
     * modifications takes place (truncating the archive or appending files).
     */
    AssertReturn(pThis->pRead, VERR_ACCESS_DENIED);
    AssertReturn(pThis->fFlags & RTZIPTAR_C_UPDATE, VERR_ACCESS_DENIED);

    AssertReturn(!pThis->fWriting, VERR_WRONG_ORDER);

    return rtZipTarFss_Next(pThis->pRead, ppszName, penmType, phVfsObj);
}


/**
 * @interface_method_impl{RTVFSFSSTREAMOPS,pfnAdd}
 */
static DECLCALLBACK(int) rtZipTarFssWriter_Add(void *pvThis, const char *pszPath, RTVFSOBJ hVfsObj, uint32_t fFlags)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)pvThis;

    /*
     * Before we continue we must complete any current push file and check rcFatal.
     */
    int rc = rtZipTarFssWriter_CompleteCurrentPushFile(pThis);
    AssertRCReturn(rc, rc);

    /*
     * Query information about the object.
     */
    RTFSOBJINFO ObjInfo;
    rc = RTVfsObjQueryInfo(hVfsObj, &ObjInfo, RTFSOBJATTRADD_UNIX);
    AssertRCReturn(rc, rc);

    RTFSOBJINFO ObjOwnerName;
    rc = RTVfsObjQueryInfo(hVfsObj, &ObjOwnerName, RTFSOBJATTRADD_UNIX_OWNER);
    if (RT_FAILURE(rc) || ObjOwnerName.Attr.u.UnixOwner.szName[0] == '\0')
        strcpy(ObjOwnerName.Attr.u.UnixOwner.szName, "someone");

    RTFSOBJINFO ObjGrpName;
    rc = RTVfsObjQueryInfo(hVfsObj, &ObjGrpName, RTFSOBJATTRADD_UNIX_GROUP);
    if (RT_FAILURE(rc) || ObjGrpName.Attr.u.UnixGroup.szName[0] == '\0')
        strcpy(ObjGrpName.Attr.u.UnixGroup.szName, "somegroup");

    /*
     * Switch the stream into write mode if necessary.
     */
    rc = rtZipTarFssWriter_SwitchToWriteMode(pThis);
    AssertRCReturn(rc, rc);

    /*
     * Do type specific handling.  File have several options and variations to
     * take into account, thus the mess.
     */
    if (RTFS_IS_FILE(ObjInfo.Attr.fMode))
    {
        RTVFSIOSTREAM hVfsIos = RTVfsObjToIoStream(hVfsObj);
        AssertReturn(hVfsIos != NIL_RTVFSIOSTREAM, VERR_WRONG_TYPE);

        if (fFlags & RTVFSFSSTRM_ADD_F_STREAM)
            rc = rtZipTarFssWriter_AddFileStream(pThis, pszPath, hVfsIos, &ObjInfo,
                                                 ObjOwnerName.Attr.u.UnixOwner.szName, ObjGrpName.Attr.u.UnixOwner.szName);
        else if (   !(pThis->fFlags & RTZIPTAR_C_SPARSE)
                 || ObjInfo.cbObject < RTZIPTAR_MIN_SPARSE)
            rc = rtZipTarFssWriter_AddFile(pThis, pszPath, hVfsIos, &ObjInfo,
                                           ObjOwnerName.Attr.u.UnixOwner.szName, ObjGrpName.Attr.u.UnixOwner.szName);
        else
        {
            RTVFSFILE hVfsFile = RTVfsObjToFile(hVfsObj);
            if (hVfsFile != NIL_RTVFSFILE)
            {
                rc = rtZipTarFssWriter_AddFileSparse(pThis, pszPath, hVfsFile, hVfsIos, &ObjInfo,
                                                     ObjOwnerName.Attr.u.UnixOwner.szName, ObjGrpName.Attr.u.UnixOwner.szName);
                RTVfsFileRelease(hVfsFile);
            }
            else
                rc = rtZipTarFssWriter_AddFile(pThis, pszPath, hVfsIos, &ObjInfo,
                                               ObjOwnerName.Attr.u.UnixOwner.szName, ObjGrpName.Attr.u.UnixOwner.szName);
        }
        RTVfsIoStrmRelease(hVfsIos);
    }
    else if (RTFS_IS_SYMLINK(ObjInfo.Attr.fMode))
    {
        RTVFSSYMLINK hVfsSymlink = RTVfsObjToSymlink(hVfsObj);
        AssertReturn(hVfsSymlink != NIL_RTVFSSYMLINK, VERR_WRONG_TYPE);
        rc = rtZipTarFssWriter_AddSymlink(pThis, pszPath, hVfsSymlink, &ObjInfo,
                                          ObjOwnerName.Attr.u.UnixOwner.szName, ObjGrpName.Attr.u.UnixOwner.szName);
        RTVfsSymlinkRelease(hVfsSymlink);
    }
    else
        rc = rtZipTarFssWriter_AddSimpleObject(pThis, pszPath, &ObjInfo,
                                               ObjOwnerName.Attr.u.UnixOwner.szName, ObjGrpName.Attr.u.UnixOwner.szName);

    return rc;
}


/**
 * @interface_method_impl{RTVFSFSSTREAMOPS,pfnPushFile}
 */
static DECLCALLBACK(int) rtZipTarFssWriter_PushFile(void *pvThis, const char *pszPath, uint64_t cbFile, PCRTFSOBJINFO paObjInfo,
                                                    uint32_t cObjInfo, uint32_t fFlags, PRTVFSIOSTREAM phVfsIos)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)pvThis;

    /*
     * We can only deal with output of indeterminate length if the output is
     * seekable (see also rtZipTarFssWriter_AddFileStream).
     */
    AssertReturn(cbFile != UINT64_MAX || pThis->hVfsFile != NIL_RTVFSFILE, VERR_NOT_A_FILE);
    AssertReturn(RT_BOOL(cbFile == UINT64_MAX) == RT_BOOL(fFlags & RTVFSFSSTRM_ADD_F_STREAM), VERR_INVALID_FLAGS);

    /*
     * Before we continue we must complete any current push file and check rcFatal.
     */
    int rc = rtZipTarFssWriter_CompleteCurrentPushFile(pThis);
    AssertRCReturn(rc, rc);

    /*
     * If no object info was provideded, fake up some.
     */
    const char *pszOwnerNm = "someone";
    const char *pszGroupNm = "somegroup";
    RTFSOBJINFO ObjInfo;
    if (cObjInfo == 0)
    {
        /* Fake up a info. */
        RT_ZERO(ObjInfo);
        ObjInfo.cbObject                    = cbFile != UINT64_MAX ? cbFile : 0;
        ObjInfo.cbAllocated                 = cbFile != UINT64_MAX ? RT_ALIGN_64(cbFile, RTZIPTAR_BLOCKSIZE) : UINT64_MAX;
        RTTimeNow(&ObjInfo.ModificationTime);
        ObjInfo.BirthTime                   = ObjInfo.ModificationTime;
        ObjInfo.ChangeTime                  = ObjInfo.ModificationTime;
        ObjInfo.AccessTime                  = ObjInfo.ModificationTime;
        ObjInfo.Attr.fMode                  = RTFS_TYPE_FILE | 0666;
        ObjInfo.Attr.enmAdditional          = RTFSOBJATTRADD_UNIX;
        ObjInfo.Attr.u.Unix.uid             = NIL_RTUID;
        ObjInfo.Attr.u.Unix.gid             = NIL_RTGID;
        ObjInfo.Attr.u.Unix.cHardlinks      = 1;
        //ObjInfo.Attr.u.Unix.INodeIdDevice   = 0;
        //ObjInfo.Attr.u.Unix.INodeId         = 0;
        //ObjInfo.Attr.u.Unix.fFlags          = 0;
        //ObjInfo.Attr.u.Unix.GenerationId    = 0;
        //ObjInfo.Attr.u.Unix.Device          = 0;
    }
    else
    {
        /* Make a copy of the object info and adjust the size, if necessary. */
        ObjInfo = paObjInfo[0];
        Assert(ObjInfo.Attr.enmAdditional == RTFSOBJATTRADD_UNIX);
        Assert(RTFS_IS_FILE(ObjInfo.Attr.fMode));
        if ((uint64_t)ObjInfo.cbObject != cbFile)
        {
            ObjInfo.cbObject    = cbFile != UINT64_MAX ? cbFile : 0;
            ObjInfo.cbAllocated = cbFile != UINT64_MAX ? RT_ALIGN_64(cbFile, RTZIPTAR_BLOCKSIZE) : UINT64_MAX;
        }

        /* Lookup the group and user names. */
        for (uint32_t i = 0; i < cObjInfo; i++)
            if (   paObjInfo[i].Attr.enmAdditional == RTFSOBJATTRADD_UNIX_OWNER
                && paObjInfo[i].Attr.u.UnixOwner.szName[0] != '\0')
                pszOwnerNm = paObjInfo[i].Attr.u.UnixOwner.szName;
            else if (   paObjInfo[i].Attr.enmAdditional == RTFSOBJATTRADD_UNIX_GROUP
                     && paObjInfo[i].Attr.u.UnixGroup.szName[0] != '\0')
                pszGroupNm = paObjInfo[i].Attr.u.UnixGroup.szName;
    }

    /*
     * Switch the stream into write mode if necessary.
     */
    rc = rtZipTarFssWriter_SwitchToWriteMode(pThis);
    AssertRCReturn(rc, rc);

    /*
     * Create an I/O stream object for the caller to use.
     */
    RTFOFF const offHdr = RTVfsIoStrmTell(pThis->hVfsIos);
    AssertReturn(offHdr >= 0, (int)offHdr);

    PRTZIPTARFSSTREAMWRITERPUSH pPush;
    RTVFSIOSTREAM hVfsIos;
    if (pThis->hVfsFile == NIL_RTVFSFILE)
    {
        rc = RTVfsNewIoStream(&g_rtZipTarWriterIoStrmOps, sizeof(*pPush), RTFILE_O_WRITE, NIL_RTVFS, NIL_RTVFSLOCK,
                              &hVfsIos, (void **)&pPush);
        if (RT_FAILURE(rc))
            return rc;
    }
    else
    {
        RTVFSFILE hVfsFile;
        rc = RTVfsNewFile(&g_rtZipTarWriterFileOps, sizeof(*pPush), RTFILE_O_WRITE, NIL_RTVFS, NIL_RTVFSLOCK,
                          &hVfsFile, (void **)&pPush);
        if (RT_FAILURE(rc))
            return rc;
        hVfsIos = RTVfsFileToIoStream(hVfsFile);
        RTVfsFileRelease(hVfsFile);
    }
    pPush->pParent      = NULL;
    pPush->cbExpected   = cbFile;
    pPush->offHdr       = (uint64_t)offHdr;
    pPush->offData      = 0;
    pPush->offCurrent   = 0;
    pPush->cbCurrent    = 0;
    pPush->ObjInfo      = ObjInfo;
    pPush->fOpenEnded   = cbFile == UINT64_MAX;

    /*
     * Produce and write file headers.
     */
    rc = rtZipTarFssWriter_ObjInfoToHdr(pThis, pszPath, &ObjInfo, pszOwnerNm, pszGroupNm, RTZIPTAR_TF_NORMAL);
    if (RT_SUCCESS(rc))
    {
        size_t cbHdrs = pThis->cHdrs * sizeof(pThis->aHdrs[0]);
        rc = RTVfsIoStrmWrite(pThis->hVfsIos, pThis->aHdrs, cbHdrs, true /*fBlocking*/, NULL);
        if (RT_SUCCESS(rc))
        {
            pThis->cbWritten += cbHdrs;

            /*
             * Complete the object and return.
             */
            pPush->offData = pPush->offHdr + cbHdrs;
            if (cbFile == UINT64_MAX)
                pPush->cbExpected = (uint64_t)(RTFOFF_MAX - _4K) - pPush->offData;
            pPush->pParent = pThis;
            pThis->pPush   = pPush;

            *phVfsIos = hVfsIos;
            return VINF_SUCCESS;
        }
        pThis->rcFatal = rc;
    }

    RTVfsIoStrmRelease(hVfsIos);
    return rc;
}


/**
 * @interface_method_impl{RTVFSFSSTREAMOPS,pfnEnd}
 */
static DECLCALLBACK(int) rtZipTarFssWriter_End(void *pvThis)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)pvThis;

    /*
     * Make sure to complete any pending push file and that rcFatal is fine.
     */
    int rc = rtZipTarFssWriter_CompleteCurrentPushFile(pThis);
    if (RT_SUCCESS(rc))
    {
        /*
         * There are supposed to be two zero headers at the end of the archive.
         * GNU tar may write more because of the way it does buffering,
         * libarchive OTOH writes exactly two.
         */
        rc = RTVfsIoStrmWrite(pThis->hVfsIos, g_abRTZero4K, RTZIPTAR_BLOCKSIZE * 2, true /*fBlocking*/, NULL);
        if (RT_SUCCESS(rc))
        {
            pThis->cbWritten += RTZIPTAR_BLOCKSIZE * 2;

            /*
             * Flush the output.
             */
            rc = RTVfsIoStrmFlush(pThis->hVfsIos);

            /*
             * If we're in update mode, set the end-of-file here to make sure
             * unwanted bytes are really discarded.
             */
            if (RT_SUCCESS(rc) && (pThis->fFlags & RTZIPTAR_C_UPDATE))
            {
                RTFOFF cbTarFile = RTVfsFileTell(pThis->hVfsFile);
                if (cbTarFile >= 0)
                    rc =  RTVfsFileSetSize(pThis->hVfsFile, (uint64_t)cbTarFile, RTVFSFILE_SIZE_F_NORMAL);
                else
                    rc = (int)cbTarFile;
            }

            /*
             * Success?
             */
            if (RT_SUCCESS(rc))
                return rc;
        }
        pThis->rcFatal = rc;
    }
    return rc;
}


/**
 * Tar filesystem stream operations.
 */
static const RTVFSFSSTREAMOPS g_rtZipTarFssOps =
{
    { /* Obj */
        RTVFSOBJOPS_VERSION,
        RTVFSOBJTYPE_FS_STREAM,
        "TarFsStreamWriter",
        rtZipTarFssWriter_Close,
        rtZipTarFssWriter_QueryInfo,
        NULL,
        RTVFSOBJOPS_VERSION
    },
    RTVFSFSSTREAMOPS_VERSION,
    0,
    rtZipTarFssWriter_Next,
    rtZipTarFssWriter_Add,
    rtZipTarFssWriter_PushFile,
    rtZipTarFssWriter_End,
    RTVFSFSSTREAMOPS_VERSION
};


RTDECL(int) RTZipTarFsStreamToIoStream(RTVFSIOSTREAM hVfsIosOut, RTZIPTARFORMAT enmFormat,
                                       uint32_t fFlags, PRTVFSFSSTREAM phVfsFss)
{
    /*
     * Input validation.
     */
    AssertPtrReturn(phVfsFss, VERR_INVALID_HANDLE);
    *phVfsFss = NIL_RTVFSFSSTREAM;
    AssertPtrReturn(hVfsIosOut, VERR_INVALID_HANDLE);
    AssertReturn(enmFormat > RTZIPTARFORMAT_INVALID && enmFormat < RTZIPTARFORMAT_END, VERR_INVALID_PARAMETER);
    AssertReturn(!(fFlags & ~RTZIPTAR_C_VALID_MASK), VERR_INVALID_FLAGS);
    AssertReturn(!(fFlags & RTZIPTAR_C_UPDATE), VERR_NOT_SUPPORTED); /* Must use RTZipTarFsStreamForFile! */

    if (enmFormat == RTZIPTARFORMAT_DEFAULT)
        enmFormat = RTZIPTARFORMAT_GNU;
    AssertReturn(   enmFormat == RTZIPTARFORMAT_GNU
                 || enmFormat == RTZIPTARFORMAT_USTAR
                 , VERR_NOT_IMPLEMENTED); /* Only implementing GNU and USTAR output at the moment. */

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

    /*
     * Retain the input stream and create a new filesystem stream handle.
     */
    PRTZIPTARFSSTREAMWRITER pThis;
    RTVFSFSSTREAM           hVfsFss;
    int rc = RTVfsNewFsStream(&g_rtZipTarFssOps, sizeof(*pThis), NIL_RTVFS, NIL_RTVFSLOCK, RTFILE_O_WRITE,
                              &hVfsFss, (void **)&pThis);
    if (RT_SUCCESS(rc))
    {
        pThis->hVfsIos          = hVfsIosOut;
        pThis->hVfsFile         = RTVfsIoStrmToFile(hVfsIosOut);

        pThis->enmFormat        = enmFormat;
        pThis->fFlags           = fFlags;
        pThis->rcFatal          = VINF_SUCCESS;

        pThis->uidOwner         = NIL_RTUID;
        pThis->pszOwner         = NULL;
        pThis->gidGroup         = NIL_RTGID;
        pThis->pszGroup         = NULL;
        pThis->pszPrefix        = NULL;
        pThis->pModTime         = NULL;
        pThis->fFileModeAndMask = ~(RTFMODE)0;
        pThis->fFileModeOrMask  = 0;
        pThis->fDirModeAndMask  = ~(RTFMODE)0;
        pThis->fDirModeOrMask   = 0;
        pThis->fWriting         = true;

        *phVfsFss = hVfsFss;
        return VINF_SUCCESS;
    }

    RTVfsIoStrmRelease(hVfsIosOut);
    return rc;
}


RTDECL(int) RTZipTarFsStreamForFile(RTVFSFILE hVfsFile, RTZIPTARFORMAT enmFormat, uint32_t fFlags, PRTVFSFSSTREAM phVfsFss)
{
    /*
     * Input validation.
     */
    AssertPtrReturn(phVfsFss, VERR_INVALID_HANDLE);
    *phVfsFss = NIL_RTVFSFSSTREAM;
    AssertReturn(hVfsFile != NIL_RTVFSFILE, VERR_INVALID_HANDLE);
    AssertReturn(enmFormat > RTZIPTARFORMAT_INVALID && enmFormat < RTZIPTARFORMAT_END, VERR_INVALID_PARAMETER);
    AssertReturn(!(fFlags & ~RTZIPTAR_C_VALID_MASK), VERR_INVALID_FLAGS);

    if (enmFormat == RTZIPTARFORMAT_DEFAULT)
        enmFormat = RTZIPTARFORMAT_GNU;
    AssertReturn(   enmFormat == RTZIPTARFORMAT_GNU
                 || enmFormat == RTZIPTARFORMAT_USTAR
                 , VERR_NOT_IMPLEMENTED); /* Only implementing GNU and USTAR output at the moment. */

    RTFOFF const offStart = RTVfsFileTell(hVfsFile);
    AssertReturn(offStart >= 0, (int)offStart);

    uint32_t cRefs = RTVfsFileRetain(hVfsFile);
    AssertReturn(cRefs != UINT32_MAX, VERR_INVALID_HANDLE);

    RTVFSIOSTREAM hVfsIos = RTVfsFileToIoStream(hVfsFile);
    AssertReturnStmt(hVfsIos != NIL_RTVFSIOSTREAM, RTVfsFileRelease(hVfsFile), VERR_INVALID_HANDLE);

    /*
     * Retain the input stream and create a new filesystem stream handle.
     */
    PRTZIPTARFSSTREAMWRITER pThis;
    size_t const            cbThis = sizeof(*pThis) + (fFlags & RTZIPTAR_C_UPDATE ? sizeof(*pThis->pRead) : 0);
    RTVFSFSSTREAM           hVfsFss;
    int rc = RTVfsNewFsStream(&g_rtZipTarFssOps, cbThis, NIL_RTVFS, NIL_RTVFSLOCK,
                              fFlags & RTZIPTAR_C_UPDATE ? RTFILE_O_READWRITE : RTFILE_O_WRITE,
                              &hVfsFss, (void **)&pThis);
    if (RT_SUCCESS(rc))
    {
        pThis->hVfsIos          = hVfsIos;
        pThis->hVfsFile         = hVfsFile;

        pThis->enmFormat        = enmFormat;
        pThis->fFlags           = fFlags;
        pThis->rcFatal          = VINF_SUCCESS;

        pThis->uidOwner         = NIL_RTUID;
        pThis->pszOwner         = NULL;
        pThis->gidGroup         = NIL_RTGID;
        pThis->pszGroup         = NULL;
        pThis->pszPrefix        = NULL;
        pThis->pModTime         = NULL;
        pThis->fFileModeAndMask = ~(RTFMODE)0;
        pThis->fFileModeOrMask  = 0;
        pThis->fDirModeAndMask  = ~(RTFMODE)0;
        pThis->fDirModeOrMask   = 0;
        if (!(fFlags & RTZIPTAR_C_UPDATE))
            pThis->fWriting     = true;
        else
        {
            pThis->fWriting     = false;
            pThis->pRead        = (PRTZIPTARFSSTREAM)(pThis + 1);
            rtZipTarReaderInit(pThis->pRead, hVfsIos, (uint64_t)offStart);
        }

        *phVfsFss = hVfsFss;
        return VINF_SUCCESS;
    }

    RTVfsIoStrmRelease(hVfsIos);
    RTVfsFileRelease(hVfsFile);
    return rc;
}


RTDECL(int) RTZipTarFsStreamSetOwner(RTVFSFSSTREAM hVfsFss, RTUID uid, const char *pszOwner)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)RTVfsFsStreamToPrivate(hVfsFss, &g_rtZipTarFssOps);
    AssertReturn(pThis, VERR_WRONG_TYPE);

    pThis->uidOwner = uid;
    if (pThis->pszOwner)
    {
        RTStrFree(pThis->pszOwner);
        pThis->pszOwner = NULL;
    }
    if (pszOwner)
    {
        pThis->pszOwner = RTStrDup(pszOwner);
        AssertReturn(pThis->pszOwner, VERR_NO_STR_MEMORY);
    }

    return VINF_SUCCESS;
}


RTDECL(int) RTZipTarFsStreamSetGroup(RTVFSFSSTREAM hVfsFss, RTGID gid, const char *pszGroup)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)RTVfsFsStreamToPrivate(hVfsFss, &g_rtZipTarFssOps);
    AssertReturn(pThis, VERR_WRONG_TYPE);

    pThis->gidGroup = gid;
    if (pThis->pszGroup)
    {
        RTStrFree(pThis->pszGroup);
        pThis->pszGroup = NULL;
    }
    if (pszGroup)
    {
        pThis->pszGroup = RTStrDup(pszGroup);
        AssertReturn(pThis->pszGroup, VERR_NO_STR_MEMORY);
    }

    return VINF_SUCCESS;
}


RTDECL(int) RTZipTarFsStreamSetPrefix(RTVFSFSSTREAM hVfsFss, const char *pszPrefix)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)RTVfsFsStreamToPrivate(hVfsFss, &g_rtZipTarFssOps);
    AssertReturn(pThis, VERR_WRONG_TYPE);
    AssertReturn(!pszPrefix || *pszPrefix, VERR_INVALID_NAME);

    if (pThis->pszPrefix)
    {
        RTStrFree(pThis->pszPrefix);
        pThis->pszPrefix = NULL;
        pThis->cchPrefix = 0;
    }
    if (pszPrefix)
    {
        /*
         * Make a copy of the prefix, make sure it ends with a slash,
         * then flip DOS slashes.
         */
        size_t cchPrefix = strlen(pszPrefix);
        char *pszCopy = RTStrAlloc(cchPrefix + 3);
        AssertReturn(pszCopy, VERR_NO_STR_MEMORY);
        memcpy(pszCopy, pszPrefix, cchPrefix + 1);

        RTPathEnsureTrailingSeparator(pszCopy, cchPrefix + 3);

#if RTPATH_STYLE != RTPATH_STR_F_STYLE_UNIX
        char *pszDosSlash = strchr(pszCopy, '\\');
        while (pszDosSlash)
        {
            *pszDosSlash = '/';
            pszDosSlash = strchr(pszDosSlash + 1, '\\');
        }
#endif

        pThis->cchPrefix = cchPrefix + strlen(&pszCopy[cchPrefix]);
        pThis->pszPrefix = pszCopy;
    }

    return VINF_SUCCESS;
}


RTDECL(int) RTZipTarFsStreamSetModTime(RTVFSFSSTREAM hVfsFss, PCRTTIMESPEC pModificationTime)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)RTVfsFsStreamToPrivate(hVfsFss, &g_rtZipTarFssOps);
    AssertReturn(pThis, VERR_WRONG_TYPE);

    if (pModificationTime)
    {
        pThis->ModTime  = *pModificationTime;
        pThis->pModTime = &pThis->ModTime;
    }
    else
        pThis->pModTime = NULL;

    return VINF_SUCCESS;
}


RTDECL(int) RTZipTarFsStreamSetFileMode(RTVFSFSSTREAM hVfsFss, RTFMODE fAndMode, RTFMODE fOrMode)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)RTVfsFsStreamToPrivate(hVfsFss, &g_rtZipTarFssOps);
    AssertReturn(pThis, VERR_WRONG_TYPE);

    pThis->fFileModeAndMask = fAndMode | ~RTFS_UNIX_ALL_PERMS;
    pThis->fFileModeOrMask  = fOrMode  & RTFS_UNIX_ALL_PERMS;
    return VINF_SUCCESS;
}


RTDECL(int) RTZipTarFsStreamSetDirMode(RTVFSFSSTREAM hVfsFss, RTFMODE fAndMode, RTFMODE fOrMode)
{
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)RTVfsFsStreamToPrivate(hVfsFss, &g_rtZipTarFssOps);
    AssertReturn(pThis, VERR_WRONG_TYPE);

    pThis->fDirModeAndMask = fAndMode | ~RTFS_UNIX_ALL_PERMS;
    pThis->fDirModeOrMask  = fOrMode  & RTFS_UNIX_ALL_PERMS;
    return VINF_SUCCESS;
}


RTDECL(int) RTZipTarFsStreamTruncate(RTVFSFSSTREAM hVfsFss, RTVFSOBJ hVfsObj, bool fAfter)
{
    /*
     * Translate and validate the input.
     */
    PRTZIPTARFSSTREAMWRITER pThis = (PRTZIPTARFSSTREAMWRITER)RTVfsFsStreamToPrivate(hVfsFss, &g_rtZipTarFssOps);
    AssertReturn(pThis, VERR_WRONG_TYPE);

    AssertReturn(hVfsObj != NIL_RTVFSOBJ, VERR_INVALID_HANDLE);
    PRTZIPTARBASEOBJ pThisObj = rtZipTarFsStreamBaseObjToPrivate(pThis->pRead, hVfsObj);
    AssertReturn(pThis, VERR_NOT_OWNER);

    AssertReturn(pThis->pRead, VERR_ACCESS_DENIED);
    AssertReturn(pThis->fFlags & RTZIPTAR_C_UPDATE, VERR_ACCESS_DENIED);
    AssertReturn(!pThis->fWriting, VERR_WRONG_ORDER);

    /*
     * Seek to the desired cut-off point and indicate that we've switched to writing.
     */
    int rc = RTVfsFileSeek(pThis->hVfsFile, fAfter ? pThisObj->offNextHdr : pThisObj->offHdr,
                           RTFILE_SEEK_BEGIN, NULL /*poffActual*/);
    if (RT_SUCCESS(rc))
        pThis->fWriting = true;
    else
        pThis->rcFatal = rc;
    return rc;
}