summaryrefslogtreecommitdiff
path: root/src/VBox/Runtime/common/zip/tar.cpp
blob: e2ced7e67299ca7610e7c601535044573c0452e7 (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
/* $Id: tar.cpp $ */
/** @file
 * IPRT - Tar archive I/O.
 */

/*
 * Copyright (C) 2009-2013 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE 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.
 */


/******************************************************************************
 *   Header Files                                                             *
 ******************************************************************************/
#include "internal/iprt.h"
#include <iprt/tar.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 "internal/magics.h"
#include "tar.h"


/******************************************************************************
 *   Structures and Typedefs                                                  *
 ******************************************************************************/

/** @name RTTARRECORD::h::linkflag
 * @{  */
#define LF_OLDNORMAL '\0' /**< Normal disk file, Unix compatible */
#define LF_NORMAL    '0'  /**< Normal disk file */
#define LF_LINK      '1'  /**< Link to previously dumped file */
#define LF_SYMLINK   '2'  /**< Symbolic link */
#define LF_CHR       '3'  /**< Character special file */
#define LF_BLK       '4'  /**< Block special file */
#define LF_DIR       '5'  /**< Directory */
#define LF_FIFO      '6'  /**< FIFO special file */
#define LF_CONTIG    '7'  /**< Contiguous file */
/** @} */

/**
 * A tar file header.
 */
typedef union RTTARRECORD
{
    char   d[512];
    struct h
    {
        char name[100];
        char mode[8];
        char uid[8];
        char gid[8];
        char size[12];
        char mtime[12];
        char chksum[8];
        char linkflag;
        char linkname[100];
        char magic[8];
        char uname[32];
        char gname[32];
        char devmajor[8];
        char devminor[8];
    } h;
} RTTARRECORD;
AssertCompileSize(RTTARRECORD, 512);
AssertCompileMemberOffset(RTTARRECORD, h.size, 100+8*3);
AssertCompileMemberSize(RTTARRECORD, h.name, RTTAR_NAME_MAX+1);
/** Pointer to a tar file header. */
typedef RTTARRECORD *PRTTARRECORD;

/** Pointer to a tar file handle. */
typedef struct RTTARFILEINTERNAL *PRTTARFILEINTERNAL;

/**
 * The internal data of a tar handle.
 */
typedef struct RTTARINTERNAL
{
    /** The magic (RTTAR_MAGIC). */
    uint32_t            u32Magic;
    /** The handle to the tar file. */
    RTFILE              hTarFile;
    /** The open mode for hTarFile. */
    uint32_t            fOpenMode;
    /** Whether a file within the archive is currently open for writing.
     * Only one can be open.  */
    bool                fFileOpenForWrite;
    /** Whether operating in stream mode. */
    bool                fStreamMode;
    /** The file cache of one file.  */
    PRTTARFILEINTERNAL  pFileCache;
} RTTARINTERNAL;
/** Pointer to a the internal data of a tar handle.  */
typedef RTTARINTERNAL* PRTTARINTERNAL;

/**
 * The internal data of a file within a tar file.
 */
typedef struct RTTARFILEINTERNAL
{
    /** The magic (RTTARFILE_MAGIC). */
    uint32_t        u32Magic;
    /** Pointer to back to the tar file. */
    PRTTARINTERNAL  pTar;
    /** The name of the file. */
    char           *pszFilename;
    /** The offset into the archive where the file header starts. */
    uint64_t        offStart;
    /** The size of the file. */
    uint64_t        cbSize;
    /** The size set by RTTarFileSetSize(). */
    uint64_t        cbSetSize;
    /** The current offset within this file. */
    uint64_t        offCurrent;
    /** The open mode. */
    uint32_t        fOpenMode;
    /** The link flag. */
    char            linkflag;
} RTTARFILEINTERNAL;
/** Pointer to the internal data of a tar file.  */
typedef RTTARFILEINTERNAL *PRTTARFILEINTERNAL;

#if 0 /* not currently used */
typedef struct RTTARFILELIST
{
    char *pszFilename;
    RTTARFILELIST *pNext;
} RTTARFILELIST;
typedef RTTARFILELIST *PRTTARFILELIST;
#endif



/******************************************************************************
 *   Defined Constants And Macros                                             *
 ******************************************************************************/

/** Validates a handle and returns VERR_INVALID_HANDLE if not valid. */
/* RTTAR */
#define RTTAR_VALID_RETURN_RC(hHandle, rc) \
    do { \
        AssertPtrReturn((hHandle), (rc)); \
        AssertReturn((hHandle)->u32Magic == RTTAR_MAGIC, (rc)); \
    } while (0)
/* RTTARFILE */
#define RTTARFILE_VALID_RETURN_RC(hHandle, rc) \
    do { \
        AssertPtrReturn((hHandle), (rc)); \
        AssertReturn((hHandle)->u32Magic == RTTARFILE_MAGIC, (rc)); \
    } while (0)

/** Validates a handle and returns VERR_INVALID_HANDLE if not valid. */
/* RTTAR */
#define RTTAR_VALID_RETURN(hHandle) RTTAR_VALID_RETURN_RC((hHandle), VERR_INVALID_HANDLE)
/* RTTARFILE */
#define RTTARFILE_VALID_RETURN(hHandle) RTTARFILE_VALID_RETURN_RC((hHandle), VERR_INVALID_HANDLE)

/** Validates a handle and returns (void) if not valid. */
/* RTTAR */
#define RTTAR_VALID_RETURN_VOID(hHandle) \
    do { \
        AssertPtrReturnVoid(hHandle); \
        AssertReturnVoid((hHandle)->u32Magic == RTTAR_MAGIC); \
    } while (0)
/* RTTARFILE */
#define RTTARFILE_VALID_RETURN_VOID(hHandle) \
    do { \
        AssertPtrReturnVoid(hHandle); \
        AssertReturnVoid((hHandle)->u32Magic == RTTARFILE_MAGIC); \
    } while (0)


/******************************************************************************
 *   Internal Functions                                                       *
 ******************************************************************************/

DECLINLINE(void) rtTarSizeToRec(PRTTARRECORD pRecord, uint64_t cbSize)
{
    /*
     * 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 (cbSize < _4G * 2U)
        RTStrPrintf(pRecord->h.size, sizeof(pRecord->h.size), "%0.11llo", cbSize);
    else
    {
        /*
         * 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.
         */
        size_t cchField = sizeof(pRecord->h.size) - 1;
        unsigned char *puchField = (unsigned char*)pRecord->h.size;
        puchField[0] = 0x80;
        do
        {
            puchField[cchField--] = cbSize & 0xff;
            cbSize >>= 8;
        } while (cchField);
    }
}

DECLINLINE(uint64_t) rtTarRecToSize(PRTTARRECORD pRecord)
{
    int64_t cbSize = 0;
    if (pRecord->h.size[0] & 0x80)
    {
        size_t cchField = sizeof(pRecord->h.size);
        unsigned char const *puchField = (unsigned char const *)pRecord->h.size;

        /*
         * The first byte has the bit 7 set to indicate base-256, while bit 6
         * is the signed bit. Bits 5:0 are the most significant value bits.
         */
        cbSize = !(0x40 & *puchField) ? 0 : -1;
        cbSize = (cbSize << 6) | (*puchField & 0x3f);
        cchField--;
        puchField++;

        /*
         * The remaining bytes are used in full.
         */
        while (cchField-- > 0)
        {
            if (RT_UNLIKELY(   cbSize > INT64_MAX / 256
                            || cbSize < INT64_MIN / 256))
            {
                cbSize = cbSize < 0 ? INT64_MIN : INT64_MAX;
                break;
            }
            cbSize = (cbSize << 8) | *puchField++;
        }
    }
    else
        RTStrToInt64Full(pRecord->h.size, 8, &cbSize);

    if (cbSize < 0)
        cbSize = 0;

    return (uint64_t)cbSize;
}

/**
 * Calculates the TAR header checksums and detects if it's all zeros.
 *
 * @returns true if all zeros, false if not.
 * @param   pHdr                The header to checksum.
 * @param   pi32Unsigned        Where to store the checksum calculated using
 *                              unsigned chars.   This is the one POSIX
 *                              specifies.
 * @param   pi32Signed          Where to store the checksum calculated using
 *                              signed chars.
 *
 * @remarks The reason why we calculate the checksum as both signed and unsigned
 *          has to do with various the char C type being signed on some hosts
 *          and unsigned on others.
 *
 * @remarks Borrowed from tarvfs.cpp.
 */
static bool rtZipTarCalcChkSum(PCRTZIPTARHDR pHdr, int32_t *pi32Unsigned, int32_t *pi32Signed)
{
    int32_t i32Unsigned = 0;
    int32_t i32Signed   = 0;

    /*
     * Sum up the entire header.
     */
    const char *pch    = (const char *)pHdr;
    const char *pchEnd = pch + sizeof(*pHdr);
    do
    {
        i32Unsigned += *(unsigned char *)pch;
        i32Signed   += *(signed   char *)pch;
    } while (++pch != pchEnd);

    /*
     * Check if it's all zeros and replace the chksum field with spaces.
     */
    bool const fZeroHdr = i32Unsigned == 0;

    pch    = pHdr->Common.chksum;
    pchEnd = pch + sizeof(pHdr->Common.chksum);
    do
    {
        i32Unsigned -= *(unsigned char *)pch;
        i32Signed   -= *(signed   char *)pch;
    } while (++pch != pchEnd);

    i32Unsigned += (unsigned char)' ' * sizeof(pHdr->Common.chksum);
    i32Signed   += (signed   char)' ' * sizeof(pHdr->Common.chksum);

    *pi32Unsigned = i32Unsigned;
    if (pi32Signed)
        *pi32Signed = i32Signed;
    return fZeroHdr;
}

DECLINLINE(int) rtTarReadHeaderRecord(RTFILE hFile, PRTTARRECORD pRecord)
{
    int rc = RTFileRead(hFile, pRecord, sizeof(RTTARRECORD), NULL);
    /* Check for EOF. EOF is valid in this case, cause it indicates no more
     * data in the tar archive. */
    if (rc == VERR_EOF)
        return VERR_TAR_END_OF_FILE;
    /* Report any other errors */
    else if (RT_FAILURE(rc))
        return rc;

    /* Check for data integrity & an EOF record */
    int32_t iUnsignedChksum, iSignedChksum;
    if (rtZipTarCalcChkSum((PCRTZIPTARHDR)pRecord, &iUnsignedChksum, &iSignedChksum))
        return VERR_TAR_END_OF_FILE;

    /* Verify the checksum */
    uint32_t sum;
    rc = RTStrToUInt32Full(pRecord->h.chksum, 8, &sum);
    if (   RT_SUCCESS(rc)
        && (   sum == (uint32_t)iSignedChksum
            || sum == (uint32_t)iUnsignedChksum) )
    {
        /* Make sure the strings are zero terminated. */
        pRecord->h.name[sizeof(pRecord->h.name) - 1]         = 0;
        pRecord->h.linkname[sizeof(pRecord->h.linkname) - 1] = 0;
        pRecord->h.magic[sizeof(pRecord->h.magic) - 1]       = 0;
        pRecord->h.uname[sizeof(pRecord->h.uname) - 1]       = 0;
        pRecord->h.gname[sizeof(pRecord->h.gname) - 1]       = 0;
    }
    else
        rc = VERR_TAR_CHKSUM_MISMATCH;

    return rc;
}

DECLINLINE(int) rtTarCreateHeaderRecord(PRTTARRECORD pRecord, const char *pszSrcName, uint64_t cbSize,
                                        RTUID uid, RTGID gid, RTFMODE fmode, int64_t mtime)
{
    /** @todo check for field overflows. */
    /* Fill the header record */
//    RT_ZERO(pRecord); - done by the caller.
    /** @todo use RTStrCopy */
    size_t cb = RTStrPrintf(pRecord->h.name,  sizeof(pRecord->h.name),  "%s", pszSrcName);
    if (cb < strlen(pszSrcName))
        return VERR_BUFFER_OVERFLOW;
    RTStrPrintf(pRecord->h.mode,  sizeof(pRecord->h.mode),  "%0.7o", fmode);
    RTStrPrintf(pRecord->h.uid,   sizeof(pRecord->h.uid),   "%0.7o", uid);
    RTStrPrintf(pRecord->h.gid,   sizeof(pRecord->h.gid),   "%0.7o", gid);
    rtTarSizeToRec(pRecord, cbSize);
    RTStrPrintf(pRecord->h.mtime, sizeof(pRecord->h.mtime), "%0.11llo", mtime);
    RTStrPrintf(pRecord->h.magic, sizeof(pRecord->h.magic), "ustar  ");
    RTStrPrintf(pRecord->h.uname, sizeof(pRecord->h.uname), "someone");
    RTStrPrintf(pRecord->h.gname, sizeof(pRecord->h.gname), "someone");
    pRecord->h.linkflag = LF_NORMAL;

    /* Create the checksum out of the new header */
    int32_t iUnsignedChksum, iSignedChksum;
    if (rtZipTarCalcChkSum((PCRTZIPTARHDR)pRecord, &iUnsignedChksum, &iSignedChksum))
        return VERR_TAR_END_OF_FILE;

    /* Format the checksum */
    RTStrPrintf(pRecord->h.chksum, sizeof(pRecord->h.chksum), "%0.7o", iUnsignedChksum);

    return VINF_SUCCESS;
}

DECLINLINE(void *) rtTarMemTmpAlloc(size_t *pcbSize)
{
    *pcbSize = 0;
    /* Allocate a reasonably large buffer, fall back on a tiny one.
     * Note: has to be 512 byte aligned and >= 512 byte. */
    size_t cbTmp = _1M;
    void *pvTmp = RTMemTmpAlloc(cbTmp);
    if (!pvTmp)
    {
        cbTmp = sizeof(RTTARRECORD);
        pvTmp = RTMemTmpAlloc(cbTmp);
    }
    *pcbSize = cbTmp;
    return pvTmp;
}

DECLINLINE(int) rtTarAppendZeros(RTTARFILE hFile, uint64_t cbSize)
{
    /* Allocate a temporary buffer for copying the tar content in blocks. */
    size_t cbTmp = 0;
    void *pvTmp = rtTarMemTmpAlloc(&cbTmp);
    if (!pvTmp)
        return VERR_NO_MEMORY;
    RT_BZERO(pvTmp, cbTmp);

    int rc = VINF_SUCCESS;
    uint64_t cbAllWritten = 0;
    size_t cbWritten = 0;
    for (;;)
    {
        if (cbAllWritten >= cbSize)
            break;
        size_t cbToWrite = RT_MIN(cbSize - cbAllWritten, cbTmp);
        rc = RTTarFileWrite(hFile, pvTmp, cbToWrite, &cbWritten);
        if (RT_FAILURE(rc))
            break;
        cbAllWritten += cbWritten;
    }

    RTMemTmpFree(pvTmp);

    return rc;
}

DECLINLINE(PRTTARFILEINTERNAL) rtCreateTarFileInternal(PRTTARINTERNAL pInt, const char *pszFilename, uint32_t fOpen)
{
    PRTTARFILEINTERNAL pFileInt = (PRTTARFILEINTERNAL)RTMemAllocZ(sizeof(RTTARFILEINTERNAL));
    if (!pFileInt)
        return NULL;

    pFileInt->u32Magic = RTTARFILE_MAGIC;
    pFileInt->pTar = pInt;
    pFileInt->fOpenMode = fOpen;
    pFileInt->pszFilename = RTStrDup(pszFilename);
    if (!pFileInt->pszFilename)
    {
        RTMemFree(pFileInt);
        return NULL;
    }

    return pFileInt;
}

DECLINLINE(PRTTARFILEINTERNAL) rtCopyTarFileInternal(PRTTARFILEINTERNAL pInt)
{
    PRTTARFILEINTERNAL pNewInt = (PRTTARFILEINTERNAL)RTMemAllocZ(sizeof(RTTARFILEINTERNAL));
    if (!pNewInt)
        return NULL;

    memcpy(pNewInt, pInt, sizeof(RTTARFILEINTERNAL));
    pNewInt->pszFilename = RTStrDup(pInt->pszFilename);
    if (!pNewInt->pszFilename)
    {
        RTMemFree(pNewInt);
        return NULL;
    }

    return pNewInt;
}

DECLINLINE(void) rtDeleteTarFileInternal(PRTTARFILEINTERNAL pInt)
{
    if (pInt)
    {
        if (pInt->pszFilename)
            RTStrFree(pInt->pszFilename);
        pInt->u32Magic = RTTARFILE_MAGIC_DEAD;
        RTMemFree(pInt);
    }
}

static int rtTarExtractFileToFile(RTTARFILE hFile, const char *pszTargetName, const uint64_t cbOverallSize, uint64_t &cbOverallWritten, PFNRTPROGRESS pfnProgressCallback, void *pvUser)
{
    /* Open the target file */
    RTFILE hNewFile;
    int rc = RTFileOpen(&hNewFile, pszTargetName, RTFILE_O_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
    if (RT_FAILURE(rc))
        return rc;

    void *pvTmp = NULL;
    do
    {
        /* Allocate a temporary buffer for reading the tar content in blocks. */
        size_t cbTmp = 0;
        pvTmp = rtTarMemTmpAlloc(&cbTmp);
        if (!pvTmp)
        {
            rc = VERR_NO_MEMORY;
            break;
        }

        /* Get the size of the source file */
        uint64_t cbToCopy = 0;
        rc = RTTarFileGetSize(hFile, &cbToCopy);
        if (RT_FAILURE(rc))
            break;

        /* Copy the content from hFile over to pszTargetName. */
        uint64_t cbAllWritten = 0; /* Already copied */
        uint64_t cbRead = 0; /* Actually read in the last step */
        for (;;)
        {
            if (pfnProgressCallback)
                pfnProgressCallback((unsigned)(100.0 / cbOverallSize * cbOverallWritten), pvUser);

            /* Finished already? */
            if (cbAllWritten == cbToCopy)
                break;

            /* Read one block. */
            cbRead = RT_MIN(cbToCopy - cbAllWritten, cbTmp);
            rc = RTTarFileRead(hFile, pvTmp, cbRead, NULL);
            if (RT_FAILURE(rc))
                break;

            /* Write the block */
            rc = RTFileWrite(hNewFile, pvTmp, cbRead, NULL);
            if (RT_FAILURE(rc))
                break;

            /* Count how many bytes are written already */
            cbAllWritten += cbRead;
            cbOverallWritten += cbRead;
        }

    } while(0);

    /* Cleanup */
    if (pvTmp)
        RTMemTmpFree(pvTmp);

    /* Now set all file attributes */
    if (RT_SUCCESS(rc))
    {
        uint32_t mode;
        rc = RTTarFileGetMode(hFile, &mode);
        if (RT_SUCCESS(rc))
        {
            mode |= RTFS_TYPE_FILE; /* For now we support regular files only */
            /* Set the mode */
            rc = RTFileSetMode(hNewFile, mode);
        }
    }

    RTFileClose(hNewFile);

    /* Delete the freshly created file in the case of an error */
    if (RT_FAILURE(rc))
        RTFileDelete(pszTargetName);

    return rc;
}

static int rtTarAppendFileFromFile(RTTAR hTar, const char *pszSrcName, const uint64_t cbOverallSize, uint64_t &cbOverallWritten, PFNRTPROGRESS pfnProgressCallback, void *pvUser)
{
    /* Open the source file */
    RTFILE hOldFile;
    int rc = RTFileOpen(&hOldFile, pszSrcName, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_WRITE);
    if (RT_FAILURE(rc))
        return rc;

    RTTARFILE hFile = NIL_RTTARFILE;
    void *pvTmp = NULL;
    do
    {
        /* Get the size of the source file */
        uint64_t cbToCopy;
        rc = RTFileGetSize(hOldFile, &cbToCopy);
        if (RT_FAILURE(rc))
            break;

        rc = RTTarFileOpen(hTar, &hFile, RTPathFilename(pszSrcName), RTFILE_O_OPEN | RTFILE_O_WRITE);
        if (RT_FAILURE(rc))
            break;

        /* Get some info from the source file */
        RTFSOBJINFO info;
        RTUID uid = 0;
        RTGID gid = 0;
        RTFMODE fmode = 0600; /* Make some save default */
        int64_t mtime = 0;

        /* This isn't critical. Use the defaults if it fails. */
        rc = RTFileQueryInfo(hOldFile, &info, RTFSOBJATTRADD_UNIX);
        if (RT_SUCCESS(rc))
        {
            fmode = info.Attr.fMode & RTFS_UNIX_MASK;
            uid = info.Attr.u.Unix.uid;
            gid = info.Attr.u.Unix.gid;
            mtime = RTTimeSpecGetSeconds(&info.ModificationTime);
        }

        /* Set the mode from the other file */
        rc = RTTarFileSetMode(hFile, fmode);
        if (RT_FAILURE(rc))
            break;

        /* Set the modification time from the other file */
        RTTIMESPEC time;
        RTTimeSpecSetSeconds(&time, mtime);
        rc = RTTarFileSetTime(hFile, &time);
        if (RT_FAILURE(rc))
            break;

        /* Set the owner from the other file */
        rc = RTTarFileSetOwner(hFile, uid, gid);
        if (RT_FAILURE(rc))
            break;

        /* Allocate a temporary buffer for copying the tar content in blocks. */
        size_t cbTmp = 0;
        pvTmp = rtTarMemTmpAlloc(&cbTmp);
        if (!pvTmp)
        {
            rc = VERR_NO_MEMORY;
            break;
        }

        /* Copy the content from pszSrcName over to hFile. This is done block
         * wise in 512 byte steps. After this copying is finished hFile will be
         * on a 512 byte boundary, regardless if the file copied is 512 byte
         * size aligned. */
        uint64_t cbAllWritten = 0; /* Already copied */
        uint64_t cbRead       = 0; /* Actually read in the last step */
        for (;;)
        {
            if (pfnProgressCallback)
                pfnProgressCallback((unsigned)(100.0 / cbOverallSize * cbOverallWritten), pvUser);
            if (cbAllWritten >= cbToCopy)
                break;

            /* Read one block. Either its the buffer size or the rest of the
             * file. */
            cbRead = RT_MIN(cbToCopy - cbAllWritten, cbTmp);
            rc = RTFileRead(hOldFile, pvTmp, cbRead, NULL);
            if (RT_FAILURE(rc))
                break;

            /* Write one block. */
            rc = RTTarFileWriteAt(hFile, cbAllWritten, pvTmp, cbRead, NULL);
            if (RT_FAILURE(rc))
                break;

            /* Count how many bytes (of the original file) are written already */
            cbAllWritten += cbRead;
            cbOverallWritten += cbRead;
        }
    } while (0);

    /* Cleanup */
    if (pvTmp)
        RTMemTmpFree(pvTmp);

    if (hFile)
        RTTarFileClose(hFile);

    RTFileClose(hOldFile);

    return rc;
}

static int rtTarSkipData(RTFILE hFile, PRTTARRECORD pRecord)
{
    int rc = VINF_SUCCESS;
    /* Seek over the data parts (512 bytes aligned) */
    int64_t offSeek = RT_ALIGN(rtTarRecToSize(pRecord), sizeof(RTTARRECORD));
    if (offSeek > 0)
        rc = RTFileSeek(hFile, offSeek, RTFILE_SEEK_CURRENT, NULL);
    return rc;
}

static int rtTarFindFile(RTFILE hFile, const char *pszFile, uint64_t *poff, uint64_t *pcbSize)
{
    /* Assume we are on the file head. */
    int         rc      = VINF_SUCCESS;
    bool        fFound  = false;
    RTTARRECORD record;
    for (;;)
    {
        /* Read & verify a header record */
        rc = rtTarReadHeaderRecord(hFile, &record);
        /* Check for error or EOF. */
        if (RT_FAILURE(rc))
            break;

        /* We support normal files only */
        if (   record.h.linkflag == LF_OLDNORMAL
            || record.h.linkflag == LF_NORMAL)
        {
            if (!RTStrCmp(record.h.name, pszFile))
            {
                /* Get the file size */
                *pcbSize = rtTarRecToSize(&record);
                /* Seek back, to position the file pointer at the start of the header. */
                rc = RTFileSeek(hFile, -(int64_t)sizeof(RTTARRECORD), RTFILE_SEEK_CURRENT, poff);
                fFound = true;
                break;
            }
        }
        rc = rtTarSkipData(hFile, &record);
        if (RT_FAILURE(rc))
            break;
    }

    if (rc == VERR_TAR_END_OF_FILE)
        rc = VINF_SUCCESS;

    /* Something found? */
    if (    RT_SUCCESS(rc)
        &&  !fFound)
        rc = VERR_FILE_NOT_FOUND;

    return rc;
}

#ifdef SOME_UNUSED_FUNCTION
static int rtTarGetFilesOverallSize(RTFILE hFile, const char * const *papszFiles, size_t cFiles, uint64_t *pcbOverallSize)
{
    int rc = VINF_SUCCESS;
    size_t cFound = 0;
    RTTARRECORD record;
    for (;;)
    {
        /* Read & verify a header record */
        rc = rtTarReadHeaderRecord(hFile, &record);
        /* Check for error or EOF. */
        if (RT_FAILURE(rc))
            break;

        /* We support normal files only */
        if (   record.h.linkflag == LF_OLDNORMAL
            || record.h.linkflag == LF_NORMAL)
        {
            for (size_t i = 0; i < cFiles; ++i)
            {
                if (!RTStrCmp(record.h.name, papszFiles[i]))
                {
                    /* Sum up the overall size */
                    *pcbOverallSize += rtTarRecToSize(&record);
                    ++cFound;
                    break;
                }
            }
            if (   cFound == cFiles
                || RT_FAILURE(rc))
                break;
        }
        rc = rtTarSkipData(hFile, &record);
        if (RT_FAILURE(rc))
            break;
    }
    if (rc == VERR_TAR_END_OF_FILE)
        rc = VINF_SUCCESS;

    /* Make sure the file pointer is at the begin of the file again. */
    if (RT_SUCCESS(rc))
        rc = RTFileSeek(hFile, 0, RTFILE_SEEK_BEGIN, 0);
    return rc;
}
#endif /* SOME_UNUSED_FUNCTION */

/******************************************************************************
 *   Public Functions                                                         *
 ******************************************************************************/

RTR3DECL(int) RTTarOpen(PRTTAR phTar, const char *pszTarname, uint32_t fMode, bool fStream)
{
    /*
     * Create a tar instance.
     */
    PRTTARINTERNAL pThis = (PRTTARINTERNAL)RTMemAllocZ(sizeof(RTTARINTERNAL));
    if (!pThis)
        return VERR_NO_MEMORY;

    pThis->u32Magic    = RTTAR_MAGIC;
    pThis->fOpenMode   = fMode;
    pThis->fStreamMode = fStream && (fMode & RTFILE_O_READ);

    /*
     * Open the tar file.
     */
    int rc = RTFileOpen(&pThis->hTarFile, pszTarname, fMode);
    if (RT_SUCCESS(rc))
    {
        *phTar = pThis;
        return VINF_SUCCESS;
    }

    RTMemFree(pThis);
    return rc;
}

RTR3DECL(int) RTTarClose(RTTAR hTar)
{
    if (hTar == NIL_RTTAR)
        return VINF_SUCCESS;

    PRTTARINTERNAL pInt = hTar;
    RTTAR_VALID_RETURN(pInt);

    int rc = VINF_SUCCESS;

    /* gtar gives a warning, but the documentation says EOF is indicated by a
     * zero block. Disabled for now. */
#if 0
    {
        /* Append the EOF record which is filled all by zeros */
        RTTARRECORD record;
        RT_ZERO(record);
        rc = RTFileWrite(pInt->hTarFile, &record, sizeof(record), NULL);
    }
#endif

    if (pInt->hTarFile != NIL_RTFILE)
        rc = RTFileClose(pInt->hTarFile);

    /* Delete any remaining cached file headers. */
    if (pInt->pFileCache)
    {
        rtDeleteTarFileInternal(pInt->pFileCache);
        pInt->pFileCache = NULL;
    }

    pInt->u32Magic = RTTAR_MAGIC_DEAD;

    RTMemFree(pInt);

    return rc;
}

RTR3DECL(int) RTTarFileOpen(RTTAR hTar, PRTTARFILE phFile, const char *pszFilename, uint32_t fOpen)
{
    AssertReturn((fOpen & RTFILE_O_READ) || (fOpen & RTFILE_O_WRITE), VERR_INVALID_PARAMETER);

    PRTTARINTERNAL pInt = hTar;
    RTTAR_VALID_RETURN(pInt);

    if (!pInt->hTarFile)
        return VERR_INVALID_HANDLE;

    if (pInt->fStreamMode)
        return VERR_INVALID_STATE;

    if (fOpen & RTFILE_O_WRITE)
    {
        if (!(pInt->fOpenMode & RTFILE_O_WRITE))
            return VERR_WRITE_PROTECT;
        if (pInt->fFileOpenForWrite)
            return VERR_TOO_MANY_OPEN_FILES;
    }

    PRTTARFILEINTERNAL pFileInt = rtCreateTarFileInternal(pInt, pszFilename, fOpen);
    if (!pFileInt)
        return VERR_NO_MEMORY;

    int rc = VINF_SUCCESS;
    do /* break loop */
    {
        if (pFileInt->fOpenMode & RTFILE_O_WRITE)
        {
            pInt->fFileOpenForWrite = true;

            /* If we are in write mode, we also in append mode. Add an dummy
             * header at the end of the current file. It will be filled by the
             * close operation. */
            rc = RTFileSeek(pFileInt->pTar->hTarFile, 0, RTFILE_SEEK_END, &pFileInt->offStart);
            if (RT_FAILURE(rc))
                break;
            RTTARRECORD record;
            RT_ZERO(record);
            rc = RTFileWrite(pFileInt->pTar->hTarFile, &record, sizeof(RTTARRECORD), NULL);
            if (RT_FAILURE(rc))
                break;
        }
        else if (pFileInt->fOpenMode & RTFILE_O_READ)
        {
            /* We need to be on the start of the file */
            rc = RTFileSeek(pFileInt->pTar->hTarFile, 0, RTFILE_SEEK_BEGIN, NULL);
            if (RT_FAILURE(rc))
                break;

            /* Search for the file. */
            rc = rtTarFindFile(pFileInt->pTar->hTarFile, pszFilename, &pFileInt->offStart, &pFileInt->cbSize);
            if (RT_FAILURE(rc))
                break;
        }
        else
        {
            /** @todo is something missing here? */
        }

    } while (0);

    /* Cleanup on failure */
    if (RT_FAILURE(rc))
    {
        if (pFileInt->pszFilename)
            RTStrFree(pFileInt->pszFilename);
        RTMemFree(pFileInt);
    }
    else
        *phFile = (RTTARFILE)pFileInt;

    return rc;
}

RTR3DECL(int) RTTarFileClose(RTTARFILE hFile)
{
    /* Already closed? */
    if (hFile == NIL_RTTARFILE)
        return VINF_SUCCESS;

    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    int rc = VINF_SUCCESS;

    /* In write mode: */
    if (pFileInt->fOpenMode & RTFILE_O_READ)
    {
        /* In read mode, we want to make sure to stay at the aligned end of this
         * file, so the next file could be read immediately. */
        uint64_t offCur = RTFileTell(pFileInt->pTar->hTarFile);

        /* Check that the file pointer is somewhere within the last open file.
         * If we are at the beginning (nothing read yet) nothing will be done.
         * A user could open/close a file more than once, without reading
         * something. */
        if (   pFileInt->offStart + sizeof(RTTARRECORD) < offCur
            && offCur < RT_ALIGN(pFileInt->offStart + sizeof(RTTARRECORD) + pFileInt->cbSize, sizeof(RTTARRECORD)))
        {
            /* Seek to the next file header. */
            uint64_t offNext = RT_ALIGN(pFileInt->offStart + sizeof(RTTARRECORD) + pFileInt->cbSize, sizeof(RTTARRECORD));
            rc = RTFileSeek(pFileInt->pTar->hTarFile, offNext - offCur, RTFILE_SEEK_CURRENT, NULL);
        }
    }
    else if (pFileInt->fOpenMode & RTFILE_O_WRITE)
    {
        pFileInt->pTar->fFileOpenForWrite = false;
        do
        {
            /* If the user has called RTTarFileSetSize in the meantime, we have
               to make sure the file has the right size. */
            if (pFileInt->cbSetSize > pFileInt->cbSize)
            {
                rc = rtTarAppendZeros(hFile, pFileInt->cbSetSize - pFileInt->cbSize);
                if (RT_FAILURE(rc))
                    break;
            }

            /* If the written size isn't 512 byte aligned, we need to fix this. */
            RTTARRECORD record;
            RT_ZERO(record);
            uint64_t cbSizeAligned = RT_ALIGN(pFileInt->cbSize, sizeof(RTTARRECORD));
            if (cbSizeAligned != pFileInt->cbSize)
            {
                /* Note the RTFile method. We didn't increase the cbSize or cbCurrentPos here. */
                rc = RTFileWriteAt(pFileInt->pTar->hTarFile,
                                   pFileInt->offStart + sizeof(RTTARRECORD) + pFileInt->cbSize,
                                   &record,
                                   cbSizeAligned - pFileInt->cbSize,
                                   NULL);
                if (RT_FAILURE(rc))
                    break;
            }

            /* Create a header record for the file */
            /* Todo: mode, gid, uid, mtime should be setable (or detected myself) */
            RTTIMESPEC time;
            RTTimeNow(&time);
            rc = rtTarCreateHeaderRecord(&record, pFileInt->pszFilename, pFileInt->cbSize,
                                         0, 0, 0600, RTTimeSpecGetSeconds(&time));
            if (RT_FAILURE(rc))
                break;

            /* Write this at the start of the file data */
            rc = RTFileWriteAt(pFileInt->pTar->hTarFile, pFileInt->offStart, &record, sizeof(RTTARRECORD), NULL);
            if (RT_FAILURE(rc))
                break;
        }
        while(0);
    }

    /* Now cleanup and delete the handle */
    rtDeleteTarFileInternal(pFileInt);

    return rc;
}

RTR3DECL(int) RTTarFileSeek(RTTARFILE hFile, uint64_t offSeek, unsigned uMethod, uint64_t *poffActual)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    if (pFileInt->pTar->fStreamMode)
        return VERR_INVALID_STATE;

    switch (uMethod)
    {
        case RTFILE_SEEK_BEGIN:
        {
            if (offSeek > pFileInt->cbSize)
                return VERR_SEEK_ON_DEVICE;
            pFileInt->offCurrent = offSeek;
            break;
        }
        case RTFILE_SEEK_CURRENT:
        {
            if (pFileInt->offCurrent + offSeek > pFileInt->cbSize)
                return VERR_SEEK_ON_DEVICE;
            pFileInt->offCurrent += offSeek;
            break;
        }
        case RTFILE_SEEK_END:
        {
            if ((int64_t)pFileInt->cbSize - (int64_t)offSeek < 0)
                return VERR_NEGATIVE_SEEK;
            pFileInt->offCurrent = pFileInt->cbSize - offSeek;
            break;
        }
        default: AssertFailedReturn(VERR_INVALID_PARAMETER);
    }

    if (poffActual)
        *poffActual = pFileInt->offCurrent;

    return VINF_SUCCESS;
}

RTR3DECL(uint64_t) RTTarFileTell(RTTARFILE hFile)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN_RC(pFileInt, UINT64_MAX);

    return pFileInt->offCurrent;
}

RTR3DECL(int) RTTarFileRead(RTTARFILE hFile, void *pvBuf, size_t cbToRead, size_t *pcbRead)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    /* Todo: optimize this, by checking the current pos */
    return RTTarFileReadAt(hFile, pFileInt->offCurrent, pvBuf, cbToRead, pcbRead);
}

RTR3DECL(int) RTTarFileReadAt(RTTARFILE hFile, uint64_t off, void *pvBuf, size_t cbToRead, size_t *pcbRead)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    /* Check that we not read behind the end of file. If so return immediately. */
    if (off > pFileInt->cbSize)
    {
        if (pcbRead)
            *pcbRead = 0;
        return VINF_SUCCESS; /* ??? VERR_EOF */
    }

    size_t cbToCopy = RT_MIN(pFileInt->cbSize - off, cbToRead);
    size_t cbTmpRead = 0;
    int rc = RTFileReadAt(pFileInt->pTar->hTarFile, pFileInt->offStart + 512 + off, pvBuf, cbToCopy, &cbTmpRead);
    pFileInt->offCurrent = off + cbTmpRead;
    if (pcbRead)
        *pcbRead = cbTmpRead;

    return rc;
}

RTR3DECL(int) RTTarFileWrite(RTTARFILE hFile, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    /** @todo Optimize this, by checking the current pos */
    return RTTarFileWriteAt(hFile, pFileInt->offCurrent, pvBuf, cbToWrite, pcbWritten);
}

RTR3DECL(int) RTTarFileWriteAt(RTTARFILE hFile, uint64_t off, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    if ((pFileInt->fOpenMode & RTFILE_O_WRITE) != RTFILE_O_WRITE)
        return VERR_WRITE_ERROR;

    size_t cbTmpWritten = 0;
    int rc = RTFileWriteAt(pFileInt->pTar->hTarFile, pFileInt->offStart + 512 + off, pvBuf, cbToWrite, &cbTmpWritten);
    pFileInt->cbSize += cbTmpWritten;
    pFileInt->offCurrent = off + cbTmpWritten;
    if (pcbWritten)
        *pcbWritten = cbTmpWritten;

    return rc;
}

RTR3DECL(int) RTTarFileGetSize(RTTARFILE hFile, uint64_t *pcbSize)
{
    /* Validate input */
    AssertPtrReturn(pcbSize, VERR_INVALID_POINTER);

    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    *pcbSize = RT_MAX(pFileInt->cbSetSize, pFileInt->cbSize);

    return VINF_SUCCESS;
}

RTR3DECL(int) RTTarFileSetSize(RTTARFILE hFile, uint64_t cbSize)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    if ((pFileInt->fOpenMode & RTFILE_O_WRITE) != RTFILE_O_WRITE)
        return VERR_WRITE_ERROR;

    /** @todo If cbSize is smaller than pFileInt->cbSize we have to
     * truncate the current file. */
    pFileInt->cbSetSize = cbSize;

    return VINF_SUCCESS;
}

RTR3DECL(int) RTTarFileGetMode(RTTARFILE hFile, uint32_t *pfMode)
{
    /* Validate input */
    AssertPtrReturn(pfMode, VERR_INVALID_POINTER);

    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    /* Read the mode out of the header entry */
    char szMode[RT_SIZEOFMEMB(RTTARRECORD, h.mode)+1];
    int rc = RTFileReadAt(pFileInt->pTar->hTarFile,
                          pFileInt->offStart + RT_OFFSETOF(RTTARRECORD, h.mode),
                          szMode,
                          RT_SIZEOFMEMB(RTTARRECORD, h.mode),
                          NULL);
    if (RT_FAILURE(rc))
        return rc;
    szMode[sizeof(szMode) - 1] = '\0';

    /* Convert it to an integer */
    return RTStrToUInt32Full(szMode, 8, pfMode);
}

RTR3DECL(int) RTTarFileSetMode(RTTARFILE hFile, uint32_t fMode)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    if ((pFileInt->fOpenMode & RTFILE_O_WRITE) != RTFILE_O_WRITE)
        return VERR_WRITE_ERROR;

    /* Convert the mode to an string. */
    char szMode[RT_SIZEOFMEMB(RTTARRECORD, h.mode)];
    RTStrPrintf(szMode, sizeof(szMode), "%0.7o", fMode);

    /* Write it directly into the header */
    return RTFileWriteAt(pFileInt->pTar->hTarFile,
                         pFileInt->offStart + RT_OFFSETOF(RTTARRECORD, h.mode),
                         szMode,
                         RT_SIZEOFMEMB(RTTARRECORD, h.mode),
                         NULL);
}

RTR3DECL(int) RTTarFileGetTime(RTTARFILE hFile, PRTTIMESPEC pTime)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    /* Read the time out of the header entry */
    char szModTime[RT_SIZEOFMEMB(RTTARRECORD, h.mtime) + 1];
    int rc = RTFileReadAt(pFileInt->pTar->hTarFile,
                          pFileInt->offStart + RT_OFFSETOF(RTTARRECORD, h.mtime),
                          szModTime,
                          RT_SIZEOFMEMB(RTTARRECORD, h.mtime),
                          NULL);
    if (RT_FAILURE(rc))
        return rc;
    szModTime[sizeof(szModTime) - 1] = '\0';

    /* Convert it to an integer */
    int64_t cSeconds;
    rc = RTStrToInt64Full(szModTime, 12, &cSeconds);

    /* And back to our time structure */
    if (RT_SUCCESS(rc))
        RTTimeSpecSetSeconds(pTime, cSeconds);

    return rc;
}

RTR3DECL(int) RTTarFileSetTime(RTTARFILE hFile, PRTTIMESPEC pTime)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    if ((pFileInt->fOpenMode & RTFILE_O_WRITE) != RTFILE_O_WRITE)
        return VERR_WRITE_ERROR;

    /* Convert the time to an string. */
    char szModTime[RT_SIZEOFMEMB(RTTARRECORD, h.mtime)];
    RTStrPrintf(szModTime, sizeof(szModTime), "%0.11llo", RTTimeSpecGetSeconds(pTime));

    /* Write it directly into the header */
    return RTFileWriteAt(pFileInt->pTar->hTarFile,
                         pFileInt->offStart + RT_OFFSETOF(RTTARRECORD, h.mtime),
                         szModTime,
                         RT_SIZEOFMEMB(RTTARRECORD, h.mtime),
                         NULL);
}

RTR3DECL(int) RTTarFileGetOwner(RTTARFILE hFile, uint32_t *pUid, uint32_t *pGid)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    /* Read the uid and gid out of the header entry */
    AssertCompileAdjacentMembers(RTTARRECORD, h.uid, h.gid);
    char szUidGid[RT_SIZEOFMEMB(RTTARRECORD, h.uid) + RT_SIZEOFMEMB(RTTARRECORD, h.gid) + 1];
    int rc = RTFileReadAt(pFileInt->pTar->hTarFile,
                          pFileInt->offStart + RT_OFFSETOF(RTTARRECORD, h.uid),
                          szUidGid,
                          sizeof(szUidGid) - 1,
                          NULL);
    if (RT_FAILURE(rc))
        return rc;
    szUidGid[sizeof(szUidGid) - 1] = '\0';

    /* Convert it to integer */
    rc = RTStrToUInt32Full(&szUidGid[RT_SIZEOFMEMB(RTTARRECORD, h.uid)], 8, pGid);
    if (RT_SUCCESS(rc))
    {
        szUidGid[RT_SIZEOFMEMB(RTTARRECORD, h.uid)] = '\0';
        rc = RTStrToUInt32Full(szUidGid, 8, pUid);
    }
    return rc;
}

RTR3DECL(int) RTTarFileSetOwner(RTTARFILE hFile, uint32_t uid, uint32_t gid)
{
    PRTTARFILEINTERNAL pFileInt = hFile;
    RTTARFILE_VALID_RETURN(pFileInt);

    if ((pFileInt->fOpenMode & RTFILE_O_WRITE) != RTFILE_O_WRITE)
        return VERR_WRITE_ERROR;
    AssertReturn(uid == (uint32_t)-1 || uid <= 07777777, VERR_OUT_OF_RANGE);
    AssertReturn(gid == (uint32_t)-1 || gid <= 07777777, VERR_OUT_OF_RANGE);

    int rc = VINF_SUCCESS;

    if (uid != (uint32_t)-1)
    {
        /* Convert the uid to an string. */
        char szUid[RT_SIZEOFMEMB(RTTARRECORD, h.uid)];
        RTStrPrintf(szUid, sizeof(szUid), "%0.7o", uid);

        /* Write it directly into the header */
        rc = RTFileWriteAt(pFileInt->pTar->hTarFile,
                           pFileInt->offStart + RT_OFFSETOF(RTTARRECORD, h.uid),
                           szUid,
                           RT_SIZEOFMEMB(RTTARRECORD, h.uid),
                           NULL);
        if (RT_FAILURE(rc))
            return rc;
    }

    if (gid != (uint32_t)-1)
    {
        /* Convert the gid to an string. */
        char szGid[RT_SIZEOFMEMB(RTTARRECORD, h.gid)];
        RTStrPrintf(szGid, sizeof(szGid), "%0.7o", gid);

        /* Write it directly into the header */
        rc = RTFileWriteAt(pFileInt->pTar->hTarFile,
                           pFileInt->offStart + RT_OFFSETOF(RTTARRECORD, h.gid),
                           szGid,
                           RT_SIZEOFMEMB(RTTARRECORD, h.gid),
                           NULL);
        if (RT_FAILURE(rc))
            return rc;
    }

    return rc;
}

/******************************************************************************
 *   Convenience Functions                                                    *
 ******************************************************************************/

RTR3DECL(int) RTTarFileExists(const char *pszTarFile, const char *pszFile)
{
    /* Validate input */
    AssertPtrReturn(pszTarFile, VERR_INVALID_POINTER);
    AssertPtrReturn(pszFile, VERR_INVALID_POINTER);

    /* Open the tar file */
    RTTAR hTar;
    int rc = RTTarOpen(&hTar, pszTarFile, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, false /*fStream*/);
    if (RT_FAILURE(rc))
        return rc;

    /* Just try to open that file readonly. If this succeed the file exists. */
    RTTARFILE hFile;
    rc = RTTarFileOpen(hTar, &hFile, pszFile, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
    if (RT_SUCCESS(rc))
        RTTarFileClose(hFile);

    RTTarClose(hTar);

    return rc;
}

RTR3DECL(int) RTTarList(const char *pszTarFile, char ***ppapszFiles, size_t *pcFiles)
{
    /* Validate input */
    AssertPtrReturn(pszTarFile, VERR_INVALID_POINTER);
    AssertPtrReturn(ppapszFiles, VERR_INVALID_POINTER);
    AssertPtrReturn(pcFiles, VERR_INVALID_POINTER);

    /* Open the tar file */
    RTTAR hTar;
    int rc = RTTarOpen(&hTar, pszTarFile, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, false /*fStream*/);
    if (RT_FAILURE(rc))
        return rc;

    /* This is done by internal methods, cause we didn't have a RTTARDIR
     * interface, yet. This should be fixed someday. */

    PRTTARINTERNAL pInt = hTar;
    char **papszFiles = NULL;
    size_t cFiles = 0;
    do /* break loop */
    {
        /* Initialize the file name array with one slot */
        size_t cFilesAlloc = 1;
        papszFiles = (char **)RTMemAlloc(sizeof(char *));
        if (!papszFiles)
        {
            rc = VERR_NO_MEMORY;
            break;
        }

        /* Iterate through the tar file record by record. Skip data records as we
         * didn't need them. */
        RTTARRECORD record;
        for (;;)
        {
            /* Read & verify a header record */
            rc = rtTarReadHeaderRecord(pInt->hTarFile, &record);
            /* Check for error or EOF. */
            if (RT_FAILURE(rc))
                break;
            /* We support normal files only */
            if (   record.h.linkflag == LF_OLDNORMAL
                || record.h.linkflag == LF_NORMAL)
            {
                if (cFiles >= cFilesAlloc)
                {
                    /* Double the array size, make sure the size doesn't wrap. */
                    void  *pvNew = NULL;
                    size_t cbNew = cFilesAlloc * sizeof(char *) * 2;
                    if (cbNew / sizeof(char *) / 2 == cFilesAlloc)
                        pvNew = RTMemRealloc(papszFiles, cbNew);
                    if (!pvNew)
                    {
                        rc = VERR_NO_MEMORY;
                        break;
                    }
                    papszFiles = (char **)pvNew;
                    cFilesAlloc *= 2;
                }

                /* Duplicate the name */
                papszFiles[cFiles] = RTStrDup(record.h.name);
                if (!papszFiles[cFiles])
                {
                    rc = VERR_NO_MEMORY;
                    break;
                }
                cFiles++;
            }
            rc = rtTarSkipData(pInt->hTarFile, &record);
            if (RT_FAILURE(rc))
                break;
        }
    } while(0);

    if (rc == VERR_TAR_END_OF_FILE)
        rc = VINF_SUCCESS;

    /* Return the file array on success, dispose of it on failure. */
    if (RT_SUCCESS(rc))
    {
        *pcFiles = cFiles;
        *ppapszFiles = papszFiles;
    }
    else
    {
        while (cFiles-- > 0)
            RTStrFree(papszFiles[cFiles]);
        RTMemFree(papszFiles);
    }

    RTTarClose(hTar);

    return rc;
}

RTR3DECL(int) RTTarExtractFileToBuf(const char *pszTarFile, void **ppvBuf, size_t *pcbSize, const char *pszFile,
                                    PFNRTPROGRESS pfnProgressCallback, void *pvUser)
{
    /*
     * Validate input
     */
    AssertPtrReturn(pszTarFile, VERR_INVALID_POINTER);
    AssertPtrReturn(ppvBuf, VERR_INVALID_POINTER);
    AssertPtrReturn(pcbSize, VERR_INVALID_POINTER);
    AssertPtrReturn(pszFile, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pfnProgressCallback, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pvUser, VERR_INVALID_POINTER);

    /** @todo progress bar - is this TODO still valid? */

    int         rc      = VINF_SUCCESS;
    RTTAR       hTar    = NIL_RTTAR;
    RTTARFILE   hFile   = NIL_RTTARFILE;
    char       *pvTmp   = NULL;
    uint64_t    cbToCopy= 0;
    do /* break loop */
    {
        rc = RTTarOpen(&hTar, pszTarFile, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, false /*fStream*/);
        if (RT_FAILURE(rc))
            break;
        rc = RTTarFileOpen(hTar, &hFile, pszFile, RTFILE_O_OPEN | RTFILE_O_READ);
        if (RT_FAILURE(rc))
            break;
        rc = RTTarFileGetSize(hFile, &cbToCopy);
        if (RT_FAILURE(rc))
            break;

        /* Allocate the memory for the file content. */
        pvTmp = (char *)RTMemAlloc(cbToCopy);
        if (!pvTmp)
        {
            rc = VERR_NO_MEMORY;
            break;
        }
        size_t cbRead = 0;
        size_t cbAllRead = 0;
        for (;;)
        {
            if (pfnProgressCallback)
                pfnProgressCallback((unsigned)(100.0 / cbToCopy * cbAllRead), pvUser);
            if (cbAllRead == cbToCopy)
                break;
            rc = RTTarFileReadAt(hFile, 0, &pvTmp[cbAllRead], cbToCopy - cbAllRead, &cbRead);
            if (RT_FAILURE(rc))
                break;
            cbAllRead += cbRead;
        }
    } while (0);

    /* Set output values on success */
    if (RT_SUCCESS(rc))
    {
        *pcbSize = cbToCopy;
        *ppvBuf = pvTmp;
    }

    /* Cleanup */
    if (   RT_FAILURE(rc)
        && pvTmp)
        RTMemFree(pvTmp);
    if (hFile)
        RTTarFileClose(hFile);
    if (hTar)
        RTTarClose(hTar);

    return rc;
}

RTR3DECL(int) RTTarExtractFiles(const char *pszTarFile, const char *pszOutputDir, const char * const *papszFiles,
                                size_t cFiles, PFNRTPROGRESS pfnProgressCallback, void *pvUser)
{
    /* Validate input */
    AssertPtrReturn(pszTarFile, VERR_INVALID_POINTER);
    AssertPtrReturn(pszOutputDir, VERR_INVALID_POINTER);
    AssertPtrReturn(papszFiles, VERR_INVALID_POINTER);
    AssertReturn(cFiles, VERR_INVALID_PARAMETER);
    AssertPtrNullReturn(pfnProgressCallback, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pvUser, VERR_INVALID_POINTER);

    /* Open the tar file */
    RTTAR hTar;
    int rc = RTTarOpen(&hTar, pszTarFile, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE, false /*fStream*/);
    if (RT_FAILURE(rc))
        return rc;

    do /* break loop */
    {
        /* Get the overall size of all files to extract out of the tar archive
           headers. Only necessary if there is a progress callback. */
        uint64_t cbOverallSize = 0;
        if (pfnProgressCallback)
        {
//            rc = rtTarGetFilesOverallSize(hFile, papszFiles, cFiles, &cbOverallSize);
//            if (RT_FAILURE(rc))
//                break;
        }

        uint64_t cbOverallWritten = 0;
        for (size_t i = 0; i < cFiles; ++i)
        {
            RTTARFILE hFile;
            rc = RTTarFileOpen(hTar, &hFile, papszFiles[i], RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
            if (RT_FAILURE(rc))
                break;
            char *pszTargetFile = RTPathJoinA(pszOutputDir, papszFiles[i]);
            if (pszTargetFile)
                rc = rtTarExtractFileToFile(hFile, pszTargetFile, cbOverallSize, cbOverallWritten, pfnProgressCallback, pvUser);
            else
                rc = VERR_NO_STR_MEMORY;
            RTStrFree(pszTargetFile);
            RTTarFileClose(hFile);
            if (RT_FAILURE(rc))
                break;
        }
    } while (0);

    RTTarClose(hTar);

    return rc;
}

RTR3DECL(int) RTTarExtractAll(const char *pszTarFile, const char *pszOutputDir, PFNRTPROGRESS pfnProgressCallback, void *pvUser)
{
    /* Validate input */
    AssertPtrReturn(pszTarFile, VERR_INVALID_POINTER);
    AssertPtrReturn(pszOutputDir, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pfnProgressCallback, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pvUser, VERR_INVALID_POINTER);

    char **papszFiles;
    size_t cFiles;

    /* First fetch the files names contained in the tar file */
    int rc = RTTarList(pszTarFile, &papszFiles, &cFiles);
    if (RT_FAILURE(rc))
        return rc;

    /* Extract all files */
    return RTTarExtractFiles(pszTarFile, pszOutputDir, papszFiles, cFiles, pfnProgressCallback, pvUser);
}

RTR3DECL(int) RTTarCreate(const char *pszTarFile, const char * const *papszFiles, size_t cFiles, PFNRTPROGRESS pfnProgressCallback, void *pvUser)
{
    /* Validate input */
    AssertPtrReturn(pszTarFile, VERR_INVALID_POINTER);
    AssertPtrReturn(papszFiles, VERR_INVALID_POINTER);
    AssertReturn(cFiles, VERR_INVALID_PARAMETER);
    AssertPtrNullReturn(pfnProgressCallback, VERR_INVALID_POINTER);
    AssertPtrNullReturn(pvUser, VERR_INVALID_POINTER);

    RTTAR hTar;
    int rc = RTTarOpen(&hTar, pszTarFile, RTFILE_O_CREATE | RTFILE_O_READWRITE | RTFILE_O_DENY_NONE, false /*fStream*/);
    if (RT_FAILURE(rc))
        return rc;

    /* Get the overall size of all files to pack into the tar archive. Only
       necessary if there is a progress callback. */
    uint64_t cbOverallSize = 0;
    if (pfnProgressCallback)
        for (size_t i = 0; i < cFiles; ++i)
        {
            uint64_t cbSize;
            rc = RTFileQuerySize(papszFiles[i], &cbSize);
            if (RT_FAILURE(rc))
                break;
            cbOverallSize += cbSize;
        }
    uint64_t cbOverallWritten = 0;
    for (size_t i = 0; i < cFiles; ++i)
    {
        rc = rtTarAppendFileFromFile(hTar, papszFiles[i], cbOverallSize, cbOverallWritten, pfnProgressCallback, pvUser);
        if (RT_FAILURE(rc))
            break;
    }

    /* Cleanup */
    RTTarClose(hTar);

    return rc;
}

/******************************************************************************
 *   Streaming Functions                                                      *
 ******************************************************************************/

RTR3DECL(int) RTTarCurrentFile(RTTAR hTar, char **ppszFilename)
{
    /* Validate input. */
    AssertPtrNullReturn(ppszFilename, VERR_INVALID_POINTER);

    PRTTARINTERNAL pInt = hTar;
    RTTAR_VALID_RETURN(pInt);

    /* Open and close the file on the current position. This makes sure the
     * cache is filled in case we never read something before. On success it
     * will return the current filename. */
    RTTARFILE hFile;
    int rc = RTTarFileOpenCurrentFile(hTar, &hFile, ppszFilename, RTFILE_O_OPEN | RTFILE_O_READ | RTFILE_O_DENY_NONE);
    if (RT_SUCCESS(rc))
        RTTarFileClose(hFile);

    return rc;
}

RTR3DECL(int) RTTarSeekNextFile(RTTAR hTar)
{
    PRTTARINTERNAL pInt = hTar;
    RTTAR_VALID_RETURN(pInt);

    int rc = VINF_SUCCESS;

    if (!pInt->fStreamMode)
        return VERR_INVALID_STATE;

    /* If there is nothing in the cache, it means we never read something. Just
     * ask for the current filename to fill the cache. */
    if (!pInt->pFileCache)
    {
        rc = RTTarCurrentFile(hTar, NULL);
        if (RT_FAILURE(rc))
            return rc;
    }

    /* Check that the file pointer is somewhere within the last open file.
     * If not we are somehow busted. */
    uint64_t offCur = RTFileTell(pInt->hTarFile);
    if (!(   pInt->pFileCache->offStart <= offCur
          && offCur <= pInt->pFileCache->offStart + sizeof(RTTARRECORD) + pInt->pFileCache->cbSize))
        return VERR_INVALID_STATE;

    /* Seek to the next file header. */
    uint64_t offNext = RT_ALIGN(pInt->pFileCache->offStart + sizeof(RTTARRECORD) + pInt->pFileCache->cbSize, sizeof(RTTARRECORD));
    if (pInt->pFileCache->cbSize != 0)
    {
        rc = RTFileSeek(pInt->hTarFile, offNext - offCur, RTFILE_SEEK_CURRENT, NULL);
        if (RT_FAILURE(rc))
            return rc;
    }
    else
    {
        /* Else delete the last open file cache. Might be recreated below. */
        rtDeleteTarFileInternal(pInt->pFileCache);
        pInt->pFileCache = NULL;
    }

    /* Again check the current filename to fill the cache with the new value. */
    return RTTarCurrentFile(hTar, NULL);
}

RTR3DECL(int) RTTarFileOpenCurrentFile(RTTAR hTar, PRTTARFILE phFile, char **ppszFilename, uint32_t fOpen)
{
    /* Validate input. */
    AssertPtrReturn(phFile, VERR_INVALID_POINTER);
    AssertPtrNullReturn(ppszFilename, VERR_INVALID_POINTER);
    AssertReturn((fOpen & RTFILE_O_READ), VERR_INVALID_PARAMETER); /* Only valid in read mode. */

    PRTTARINTERNAL pInt = hTar;
    RTTAR_VALID_RETURN(pInt);

    if (!pInt->fStreamMode)
        return VERR_INVALID_STATE;

    int rc = VINF_SUCCESS;

    /* Is there some cached entry? */
    if (pInt->pFileCache)
    {
        if (pInt->pFileCache->offStart + sizeof(RTTARRECORD) < RTFileTell(pInt->hTarFile))
        {
            /* Else delete the last open file cache. Might be recreated below. */
            rtDeleteTarFileInternal(pInt->pFileCache);
            pInt->pFileCache = NULL;
        }
        else/* Are we still directly behind that header? */
        {
            /* Yes, so the streaming can start. Just return the cached file
             * structure to the caller. */
            *phFile = rtCopyTarFileInternal(pInt->pFileCache);
            if (ppszFilename)
                *ppszFilename = RTStrDup(pInt->pFileCache->pszFilename);
            if (pInt->pFileCache->linkflag == LF_DIR)
                return VINF_TAR_DIR_PATH;
            return VINF_SUCCESS;
        }

    }

    PRTTARFILEINTERNAL pFileInt = NULL;
    do /* break loop */
    {
        /* Try to read a header entry from the current position. If we aren't
         * on a header record, the header checksum will show and an error will
         * be returned. */
        RTTARRECORD record;
        /* Read & verify a header record */
        rc = rtTarReadHeaderRecord(pInt->hTarFile, &record);
        /* Check for error or EOF. */
        if (RT_FAILURE(rc))
            break;

        /* We support normal files only */
        if (   record.h.linkflag == LF_OLDNORMAL
            || record.h.linkflag == LF_NORMAL
            || record.h.linkflag == LF_DIR)
        {
            pFileInt = rtCreateTarFileInternal(pInt, record.h.name, fOpen);
            if (!pFileInt)
            {
                rc = VERR_NO_MEMORY;
                break;
            }

            /* Get the file size */
            pFileInt->cbSize = rtTarRecToSize(&record);
            /* The start is -512 from here. */
            pFileInt->offStart = RTFileTell(pInt->hTarFile) - sizeof(RTTARRECORD);
            /* remember the type of a file */
            pFileInt->linkflag = record.h.linkflag;

            /* Copy the new file structure to our cache. */
            pInt->pFileCache = rtCopyTarFileInternal(pFileInt);
            if (ppszFilename)
                *ppszFilename = RTStrDup(pFileInt->pszFilename);

            if (pFileInt->linkflag == LF_DIR)
                rc = VINF_TAR_DIR_PATH;
        }
    } while (0);

    if (RT_FAILURE(rc))
    {
        if (pFileInt)
            rtDeleteTarFileInternal(pFileInt);
    }
    else
        *phFile = pFileInt;

    return rc;
}