forked from adamdruppe/arsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
archive.d
3252 lines (2851 loc) · 98.9 KB
/
archive.d
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
/++
Provides LZMA (aka .xz) and .tar file read-only support.
Combine to read .tar.xz files, or use in conjunction with
other files to read other types of .tar files.
Also has a custom archive called arcz read and write support.
It is designed to efficiently pack and randomly access large
numbers of similar files. Unlike .zip files, it will do
cross-file compression (meaning it can significantly shrink
archives with several small but similar files), and unlike
tar.gz files, it supports random access without decompressing
the whole archive to get an individual file. It is designed
for large numbers of small, similar files.
+/
module arsd.archive;
version(WithoutLzmaDecoder) {} else
version=WithLzmaDecoder;
version(WithoutArczCode) {} else
version=WithArczCode;
/+
/++
Reads a tar file and passes the chunks to your handler. Use it like:
TarFile f = TarFile("filename.tar");
foreach(part; f) {
if(part.isNewFile) {
}
}
FIXME not implemented
+/
struct TarFile {
this(string filename) {
}
}
+/
inout(char)[] upToZero(inout(char)[] a) {
int i = 0;
while(i < a.length && a[i]) i++;
return a[0 .. i];
}
/++
A header of a file in the archive. This represents the
binary format of the header block.
+/
align(512)
struct TarFileHeader {
align(1):
char[100] fileName_ = 0;
char[8] fileMode_ = 0;
char[8] ownerUid_ = 0;
char[8] ownerGid_ = 0;
char[12] size_ = 0; // in octal
char[12] mtime_ = 0; // octal unix timestamp
char[8] checksum_ = 0; // right?????
char[1] fileType_ = 0; // hard link, soft link, etc
char[100] linkFileName_ = 0;
char[6] ustarMagic_ = 0; // if "ustar\0", remaining fields are set
char[2] ustarVersion_ = 0;
char[32] ownerName_ = 0;
char[32] groupName_ = 0;
char[8] deviceMajorNumber_ = 0;
char[8] deviceMinorNumber_ = 0;
char[155] filenamePrefix_ = 0;
/// Returns the filename. You should cache the return value as long as TarFileHeader is in scope (it returns a slice after calling strlen)
const(char)[] filename() {
import core.stdc.string;
if(filenamePrefix_[0])
return upToZero(filenamePrefix_[]) ~ upToZero(fileName_[]);
return upToZero(fileName_[]);
}
///
ulong size() {
import core.stdc.stdlib;
return strtoul(size_.ptr, null, 8);
}
///
TarFileType type() {
if(fileType_[0] == 0)
return TarFileType.normal;
else
return cast(TarFileType) (fileType_[0] - '0');
}
}
/// There's other types but this is all I care about. You can still detect the char by `((cast(char) type) + '0')`
enum TarFileType {
normal = 0, ///
hardLink = 1, ///
symLink = 2, ///
characterSpecial = 3, ///
blockSpecial = 4, ///
directory = 5, ///
fifo = 6 ///
}
/++
Low level tar file processor. You must pass it a
TarFileHeader buffer as well as a size_t for context.
Both must be initialized to all zeroes on first call,
then not modified in between calls.
Each call must populate the dataBuffer with 512 bytes.
returns true if still work to do.
+/
bool processTar(
TarFileHeader* header,
long* bytesRemainingOnCurrentFile,
ubyte[] dataBuffer,
scope void delegate(TarFileHeader* header, bool isNewFile, bool fileFinished, ubyte[] data) handleData
)
{
assert(dataBuffer.length == 512);
assert(bytesRemainingOnCurrentFile !is null);
assert(header !is null);
if(*bytesRemainingOnCurrentFile) {
bool isNew = *bytesRemainingOnCurrentFile == header.size();
if(*bytesRemainingOnCurrentFile <= 512) {
handleData(header, isNew, true, dataBuffer[0 .. cast(size_t) *bytesRemainingOnCurrentFile]);
*bytesRemainingOnCurrentFile = 0;
} else {
handleData(header, isNew, false, dataBuffer[]);
*bytesRemainingOnCurrentFile -= 512;
}
} else {
*header = *(cast(TarFileHeader*) dataBuffer.ptr);
auto s = header.size();
*bytesRemainingOnCurrentFile = s;
if(header.type() == TarFileType.directory)
handleData(header, true, false, null);
if(s == 0 && header.type == TarFileType.normal)
return false;
}
return true;
}
///
unittest {
void main() {
TarFileHeader tfh;
long size;
import std.stdio;
ubyte[512] buffer;
foreach(chunk; File("/home/me/test/pl.tar", "r").byChunk(buffer[])) {
processTar(&tfh, &size, buffer[],
(header, isNewFile, fileFinished, data) {
if(isNewFile)
writeln("**** " , header.filename, " ", header.size);
write(cast(string) data);
if(fileFinished)
writeln("+++++++++++++++");
});
}
}
main();
}
ulong readVla(ref ubyte[] data) {
ulong n;
n = data[0] & 0x7f;
if(!(data[0] & 0x80))
data = data[1 .. $];
int i = 0;
while(data[0] & 0x80) {
i++;
data = data[1 .. $];
ubyte b = data[0];
if(b == 0) return 0;
n |= cast(ulong) (b & 0x7F) << (i * 7);
}
return n;
}
/++
A simple .xz file decoder.
FIXME: it doesn't implement very many checks, instead
assuming things are what it expects. Don't use this without
assertions enabled!
Use it by feeding it xz file data chunks. It will give you
back decompressed data chunks;
BEWARE OF REUSED BUFFERS. See the example.
+/
version(WithLzmaDecoder)
struct XzDecoder {
/++
Start decoding by feeding it some initial data. You must
send it at least enough bytes for the header (> 16 bytes prolly);
try to send it a reasonably sized chunk.
+/
this(ubyte[] initialData) {
ubyte[6] magic;
magic[] = initialData[0 .. magic.length];
initialData = initialData[magic.length .. $];
if(cast(string) magic != "\xFD7zXZ\0")
throw new Exception("not an xz file");
ubyte[2] streamFlags = initialData[0 .. 2];
initialData = initialData[2 .. $];
// size of the check at the end in the footer. im just ignoring tbh
checkSize = streamFlags[1] == 0 ? 0 : (4 << ((streamFlags[1]-1) / 3));
//uint crc32 = initialData[0 .. 4]; // FIXME just cast it. this is the crc of the flags.
initialData = initialData[4 .. $];
// now we are into an xz block...
int blockHeaderSize = (initialData[0] + 1) * 4;
auto srcPostHeader = initialData[blockHeaderSize .. $];
initialData = initialData[1 .. $];
ubyte blockFlags = initialData[0];
initialData = initialData[1 .. $];
if(blockFlags & 0x40) {
compressedSize = readVla(initialData);
}
if(blockFlags & 0x80) {
uncompressedSize = readVla(initialData);
}
auto filterCount = (blockFlags & 0b11) + 1;
ubyte props;
foreach(f; 0 .. filterCount) {
auto fid = readVla(initialData);
auto sz = readVla(initialData);
assert(fid == 0x21);
assert(sz == 1);
props = initialData[0];
initialData = initialData[1 .. $];
}
//writeln(src.ptr);
//writeln(srcPostHeader.ptr);
// there should be some padding to a multiple of 4...
// three bytes of zeroes given the assumptions here
initialData = initialData[3 .. $];
// and then a header crc
initialData = initialData[4 .. $]; // skip header crc
assert(initialData.ptr is srcPostHeader.ptr);
// skip unknown header bytes
while(initialData.ptr < srcPostHeader.ptr) {
initialData = initialData[1 .. $];
}
// should finally be at compressed data...
//writeln(compressedSize);
//writeln(uncompressedSize);
if(Lzma2Dec_Allocate(&lzmaDecoder, props) != SRes.OK) {
assert(0);
}
Lzma2Dec_Init(&lzmaDecoder);
unprocessed = initialData;
}
~this() {
LzmaDec_FreeProbs(&lzmaDecoder.decoder);
}
/++
You tell it where you want the data.
You must pass it the existing unprocessed data
Returns slice of dest that is actually filled up so far.
+/
ubyte[] processData(ubyte[] dest, ubyte[] src) {
size_t destLen = dest.length;
size_t srcLen = src.length;
ELzmaStatus status;
auto res = Lzma2Dec_DecodeToBuf(
&lzmaDecoder,
dest.ptr,
&destLen,
src.ptr,
&srcLen,
LZMA_FINISH_ANY,
&status
);
if(res != 0) {
import std.conv;
throw new Exception(to!string(res));
}
/+
import std.stdio;
writeln(res, " ", status);
writeln(srcLen);
writeln(destLen, ": ", cast(string) dest[0 .. destLen]);
+/
if(status == LZMA_STATUS_NEEDS_MORE_INPUT) {
unprocessed = src[srcLen .. $];
finished_ = false;
needsMoreData_ = true;
} else if(status == LZMA_STATUS_FINISHED_WITH_MARK || status == LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK) {
unprocessed = null;
finished_ = true;
needsMoreData_ = false;
} else if(status == LZMA_STATUS_NOT_FINISHED) {
unprocessed = src[srcLen .. $];
finished_ = false;
needsMoreData_ = false;
} else {
// wtf
import std.conv;
assert(0, to!string(status));
}
return dest[0 .. destLen];
}
///
bool finished() {
return finished_;
}
///
bool needsMoreData() {
return needsMoreData_;
}
bool finished_;
bool needsMoreData_;
CLzma2Dec lzmaDecoder;
int checkSize;
ulong compressedSize; ///
ulong uncompressedSize; ///
ubyte[] unprocessed; ///
}
///
version(WithLzmaDecoder)
unittest {
void main() {
ubyte[512] dest; // into tar size chunks!
ubyte[1024] src;
import std.stdio;
//auto file = File("/home/me/test/amazing.txt.xz", "rb");
auto file = File("/home/me/Android/ldcdl/test.tar.xz", "rb");
auto bfr = file.rawRead(src[]);
XzDecoder xzd = XzDecoder(bfr);
// not necessarily set, don't rely on them
writeln(xzd.compressedSize, " / ", xzd.uncompressedSize);
// for tar
TarFileHeader tfh;
long size;
long sum = 0;
while(!xzd.finished) {
// as long as your are not finished, there is more work to do. But it doesn't
// necessarily need more data, so that is a separate check.
if(xzd.needsMoreData) {
// if it needs more data, append new stuff to the end of the buffer, after
// the existing unprocessed stuff. If your buffer is too small, you may be
// forced to grow it here, but anything >= 1 KB seems OK in my tests.
bfr = file.rawRead(src[bfr.length - xzd.unprocessed.length .. $]);
} else {
// otherwise, you want to continue working with existing unprocessed data
bfr = xzd.unprocessed;
}
//write(cast(string) xzd.processData(dest[], bfr));
auto buffer = xzd.processData(dest[], bfr);
// if the buffer is empty we are probably done
// or need more data, so continue the loop to evaluate.
if(buffer.length == 0)
continue;
// our tar code requires specifically 512 byte pieces
while(!xzd.finished && buffer.length != 512) {
// need more data hopefully
assert(xzd.needsMoreData);
// using the existing buffer...
bfr = file.rawRead(src[bfr.length - xzd.unprocessed.length .. $]);
auto nbuffer = xzd.processData(dest[buffer.length .. $], bfr);
buffer = dest[0 .. buffer.length + nbuffer.length];
}
sum += buffer.length;
// process the buffer through the tar file handler
processTar(&tfh, &size, buffer[],
(header, isNewFile, fileFinished, data) {
if(isNewFile)
writeln("**** " , header.filename, " ", header.size);
//write(cast(string) data);
if(fileFinished)
writeln("+++++++++++++++");
});
}
writeln(sum);
}
main();
}
version(WithArczCode) {
/* The code in this section was originally written by Ketmar Dark for his arcz.d module. I modified it afterward. */
/** ARZ chunked archive format processor.
*
* This module provides `std.stdio.File`-like interface to ARZ archives.
*
* Copyright: Copyright Ketmar Dark, 2016
*
* License: Boost License 1.0
*/
// module iv.arcz;
// use Balz compressor if available
static if (__traits(compiles, { import iv.balz; })) enum arcz_has_balz = true; else enum arcz_has_balz = false;
static if (__traits(compiles, { import iv.zopfli; })) enum arcz_has_zopfli = true; else enum arcz_has_zopfli = false;
static if (arcz_has_balz) import iv.balz;
static if (arcz_has_zopfli) import iv.zopfli;
// comment this to free pakced chunk buffer right after using
// i.e. `AZFile` will allocate new block for each new chunk
//version = arcz_use_more_memory;
public import core.stdc.stdio : SEEK_SET, SEEK_CUR, SEEK_END;
// ////////////////////////////////////////////////////////////////////////// //
/// ARZ archive accessor. Use this to open ARZ archives, and open packed files from ARZ archives.
public struct ArzArchive {
private:
static assert(size_t.sizeof >= (void*).sizeof);
private import core.stdc.stdio : FILE, fopen, fclose, fread, fseek;
private import etc.c.zlib;
static struct ChunkInfo {
uint ofs; // offset in file
uint pksize; // packed chunk size (same as chunk size: chunk is unpacked)
}
static struct FileInfo {
string name;
uint chunk;
uint chunkofs; // offset of first file byte in unpacked chunk
uint size; // unpacked file size
}
static struct Nfo {
uint rc = 1; // refcounter
ChunkInfo[] chunks;
FileInfo[string] files;
uint chunkSize;
uint lastChunkSize;
bool useBalz;
FILE* afl; // archive file, we'll keep it opened
@disable this (this); // no copies!
static void decRef (size_t me) {
if (me) {
auto nfo = cast(Nfo*)me;
assert(nfo.rc);
if (--nfo.rc == 0) {
import core.memory : GC;
import core.stdc.stdlib : free;
if (nfo.afl !is null) fclose(nfo.afl);
nfo.chunks.destroy;
nfo.files.destroy;
nfo.afl = null;
GC.removeRange(cast(void*)nfo/*, Nfo.sizeof*/);
free(nfo);
debug(arcz_rc) { import core.stdc.stdio : printf; printf("Nfo %p freed\n", nfo); }
}
}
}
}
size_t nfop; // hide it from GC
private @property Nfo* nfo () { pragma(inline, true); return cast(Nfo*)nfop; }
void decRef () { pragma(inline, true); Nfo.decRef(nfop); nfop = 0; }
static uint readUint (FILE* fl) {
if (fl is null) throw new Exception("cannot read from closed file");
uint v;
if (fread(&v, 1, v.sizeof, fl) != v.sizeof) throw new Exception("file reading error");
version(BigEndian) {
import core.bitop : bswap;
v = bswap(v);
} else version(LittleEndian) {
// nothing to do
} else {
static assert(0, "wtf?!");
}
return v;
}
static uint readUbyte (FILE* fl) {
if (fl is null) throw new Exception("cannot read from closed file");
ubyte v;
if (fread(&v, 1, v.sizeof, fl) != v.sizeof) throw new Exception("file reading error");
return v;
}
static void readBuf (FILE* fl, void[] buf) {
if (buf.length > 0) {
if (fl is null) throw new Exception("cannot read from closed file");
if (fread(buf.ptr, 1, buf.length, fl) != buf.length) throw new Exception("file reading error");
}
}
static T* xalloc(T, bool clear=true) (uint mem) if (T.sizeof > 0) {
import core.exception : onOutOfMemoryError;
assert(mem != 0);
static if (clear) {
import core.stdc.stdlib : calloc;
auto res = calloc(mem, T.sizeof);
if (res is null) onOutOfMemoryError();
static if (is(T == struct)) {
import core.stdc.string : memcpy;
static immutable T i = T.init;
foreach (immutable idx; 0..mem) memcpy(res+idx, &i, T.sizeof);
}
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("allocated %u bytes at %p\n", cast(uint)(mem*T.sizeof), res); }
return cast(T*)res;
} else {
import core.stdc.stdlib : malloc;
auto res = malloc(mem*T.sizeof);
if (res is null) onOutOfMemoryError();
static if (is(T == struct)) {
import core.stdc.string : memcpy;
static immutable T i = T.init;
foreach (immutable idx; 0..mem) memcpy(res+idx, &i, T.sizeof);
}
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("allocated %u bytes at %p\n", cast(uint)(mem*T.sizeof), res); }
return cast(T*)res;
}
}
static void xfree(T) (T* ptr) {
if (ptr !is null) {
import core.stdc.stdlib : free;
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("freing at %p\n", ptr); }
free(ptr);
}
}
static if (arcz_has_balz) static ubyte balzDictSize (uint blockSize) {
foreach (ubyte bits; Balz.MinDictBits..Balz.MaxDictBits+1) {
if ((1U<<bits) >= blockSize) return bits;
}
return Balz.MaxDictBits;
}
// unpack exactly `destlen` bytes
static if (arcz_has_balz) static void unpackBlockBalz (void* dest, uint destlen, const(void)* src, uint srclen, uint blocksize) {
Unbalz bz;
bz.reinit(balzDictSize(blocksize));
int ipos, opos;
auto dc = bz.decompress(
// reader
(buf) {
import core.stdc.string : memcpy;
if (ipos >= srclen) return 0;
uint rd = destlen-ipos;
if (rd > buf.length) rd = cast(uint)buf.length;
memcpy(buf.ptr, src+ipos, rd);
ipos += rd;
return rd;
},
// writer
(buf) {
//if (opos+buf.length > destlen) throw new Exception("error unpacking archive");
uint wr = destlen-opos;
if (wr > buf.length) wr = cast(uint)buf.length;
if (wr > 0) {
import core.stdc.string : memcpy;
memcpy(dest+opos, buf.ptr, wr);
opos += wr;
}
},
// unpack length
destlen
);
if (opos != destlen) throw new Exception("error unpacking archive");
}
static void unpackBlockZLib (void* dest, uint destlen, const(void)* src, uint srclen, uint blocksize) {
z_stream zs;
zs.avail_in = 0;
zs.avail_out = 0;
// initialize unpacker
if (inflateInit2(&zs, 15) != Z_OK) throw new Exception("can't initialize zlib");
scope(exit) inflateEnd(&zs);
zs.next_in = cast(typeof(zs.next_in))src;
zs.avail_in = srclen;
zs.next_out = cast(typeof(zs.next_out))dest;
zs.avail_out = destlen;
while (zs.avail_out > 0) {
auto err = inflate(&zs, Z_SYNC_FLUSH);
if (err != Z_STREAM_END && err != Z_OK) throw new Exception("error unpacking archive");
if (err == Z_STREAM_END) break;
}
if (zs.avail_out != 0) throw new Exception("error unpacking archive");
}
static void unpackBlock (void* dest, uint destlen, const(void)* src, uint srclen, uint blocksize, bool useBalz) {
if (useBalz) {
static if (arcz_has_balz) {
unpackBlockBalz(dest, destlen, src, srclen, blocksize);
} else {
throw new Exception("no Balz support was compiled in ArcZ");
}
} else {
unpackBlockZLib(dest, destlen, src, srclen, blocksize);
}
}
public:
this (in ArzArchive arc) {
assert(nfop == 0);
nfop = arc.nfop;
if (nfop) ++nfo.rc;
}
this (this) {
if (nfop) ++nfo.rc;
}
~this () { close(); }
void opAssign (in ArzArchive arc) {
if (arc.nfop) {
auto n = cast(Nfo*)arc.nfop;
++n.rc;
}
decRef();
nfop = arc.nfop;
}
void close () { decRef(); }
@property FileInfo[string] files () { return (nfop ? nfo.files : null); }
void openArchive (const(char)[] filename) {
debug/*(arcz)*/ import core.stdc.stdio : printf;
FILE* fl = null;
scope(exit) if (fl !is null) fclose(fl);
close();
if (filename.length == 0) throw new Exception("cannot open unnamed archive file");
if (false && filename.length < 2048) { // FIXME the alloca fails on win64 for some reason
import core.stdc.stdlib : alloca;
auto tfn = (cast(char*)alloca(filename.length+1))[0..filename.length+1];
tfn[0..filename.length] = filename[];
tfn[filename.length] = 0;
fl = fopen(tfn.ptr, "rb");
} else {
import core.stdc.stdlib : malloc, free;
auto tfn = (cast(char*)malloc(filename.length+1))[0..filename.length+1];
if (tfn !is null) {
tfn[0 .. filename.length] = filename[];
tfn[filename.length] = 0;
scope(exit) free(tfn.ptr);
fl = fopen(tfn.ptr, "rb");
}
}
if (fl is null) throw new Exception("cannot open archive file '"~filename.idup~"'");
char[4] sign;
bool useBalz;
readBuf(fl, sign[]);
if (sign != "CZA2") throw new Exception("invalid archive file '"~filename.idup~"'");
switch (readUbyte(fl)) {
case 0: useBalz = false; break;
case 1: useBalz = true; break;
default: throw new Exception("invalid version of archive file '"~filename.idup~"'");
}
uint indexofs = readUint(fl); // index offset in file
uint pkidxsize = readUint(fl); // packed index size
uint idxsize = readUint(fl); // unpacked index size
if (pkidxsize == 0 || idxsize == 0 || indexofs == 0) throw new Exception("invalid archive file '"~filename.idup~"'");
// now read index
ubyte* idxbuf = null;
scope(exit) xfree(idxbuf);
{
auto pib = xalloc!ubyte(pkidxsize);
scope(exit) xfree(pib);
if (fseek(fl, indexofs, 0) < 0) throw new Exception("seek error in archive file '"~filename.idup~"'");
readBuf(fl, pib[0..pkidxsize]);
idxbuf = xalloc!ubyte(idxsize);
unpackBlock(idxbuf, idxsize, pib, pkidxsize, idxsize, useBalz);
}
// parse index and build structures
uint idxbufpos = 0;
ubyte getUbyte () {
if (idxsize-idxbufpos < ubyte.sizeof) throw new Exception("invalid index for archive file '"~filename.idup~"'");
return idxbuf[idxbufpos++];
}
uint getUint () {
if (idxsize-idxbufpos < uint.sizeof) throw new Exception("invalid index for archive file '"~filename.idup~"'");
version(BigEndian) {
import core.bitop : bswap;
uint v = *cast(uint*)(idxbuf+idxbufpos);
idxbufpos += 4;
return bswap(v);
} else version(LittleEndian) {
uint v = *cast(uint*)(idxbuf+idxbufpos);
idxbufpos += 4;
return v;
} else {
static assert(0, "wtf?!");
}
}
void getBuf (void[] buf) {
if (buf.length > 0) {
import core.stdc.string : memcpy;
if (idxsize-idxbufpos < buf.length) throw new Exception("invalid index for archive file '"~filename.idup~"'");
memcpy(buf.ptr, idxbuf+idxbufpos, buf.length);
idxbufpos += buf.length;
}
}
// allocate shared info struct
Nfo* nfo = xalloc!Nfo(1);
assert(nfo.rc == 1);
debug(arcz_rc) { import core.stdc.stdio : printf; printf("Nfo %p allocated\n", nfo); }
scope(failure) decRef();
nfop = cast(size_t)nfo;
{
import core.memory : GC;
GC.addRange(nfo, Nfo.sizeof);
}
// read chunk info and data
nfo.useBalz = useBalz;
nfo.chunkSize = getUint;
auto ccount = getUint; // chunk count
nfo.lastChunkSize = getUint;
debug(arcz_dirread) printf("chunk size: %u\nchunk count: %u\nlast chunk size:%u\n", nfo.chunkSize, ccount, nfo.lastChunkSize);
if (ccount == 0 || nfo.chunkSize < 1 || nfo.lastChunkSize < 1 || nfo.lastChunkSize > nfo.chunkSize) throw new Exception("invalid archive file '"~filename.idup~"'");
nfo.chunks.length = ccount;
// chunk offsets and sizes
foreach (ref ci; nfo.chunks) {
ci.ofs = getUint;
ci.pksize = getUint;
}
// read file count and info
auto fcount = getUint;
if (fcount == 0) throw new Exception("empty archive file '"~filename.idup~"'");
// calc name buffer position and size
//immutable uint nbofs = idxbufpos+fcount*(5*4);
//if (nbofs >= idxsize) throw new Exception("invalid index in archive file '"~filename.idup~"'");
//immutable uint nbsize = idxsize-nbofs;
debug(arcz_dirread) printf("file count: %u\n", fcount);
foreach (immutable _; 0..fcount) {
uint nameofs = getUint;
uint namelen = getUint;
if (namelen == 0) {
// skip unnamed file
//throw new Exception("invalid archive file '"~filename.idup~"'");
getUint; // chunk number
getUint; // offset in chunk
getUint; // unpacked size
debug(arcz_dirread) printf("skipped empty file\n");
} else {
//if (nameofs >= nbsize || namelen > nbsize || nameofs+namelen > nbsize) throw new Exception("invalid index in archive file '"~filename.idup~"'");
if (nameofs >= idxsize || namelen > idxsize || nameofs+namelen > idxsize) throw new Exception("invalid index in archive file '"~filename.idup~"'");
FileInfo fi;
auto nb = new char[](namelen);
nb[0..namelen] = (cast(char*)idxbuf)[nameofs..nameofs+namelen];
fi.name = cast(string)(nb); // it is safe here
fi.chunk = getUint; // chunk number
fi.chunkofs = getUint; // offset in chunk
fi.size = getUint; // unpacked size
debug(arcz_dirread) printf("file size: %u\nfile chunk: %u\noffset in chunk:%u; name: [%.*s]\n", fi.size, fi.chunk, fi.chunkofs, cast(uint)fi.name.length, fi.name.ptr);
nfo.files[fi.name] = fi;
}
}
// transfer achive file ownership
nfo.afl = fl;
fl = null;
}
bool exists (const(char)[] name) { if (nfop) return ((name in nfo.files) !is null); else return false; }
AZFile open (const(char)[] name) {
if (!nfop) throw new Exception("can't open file from non-opened archive");
if (auto fi = name in nfo.files) {
auto zl = xalloc!LowLevelPackedRO(1);
scope(failure) xfree(zl);
debug(arcz_rc) { import core.stdc.stdio : printf; printf("Zl %p allocated\n", zl); }
zl.setup(nfo, fi.chunk, fi.chunkofs, fi.size);
AZFile fl;
fl.zlp = cast(size_t)zl;
return fl;
}
throw new Exception("can't open file '"~name.idup~"' from archive");
}
private:
static struct LowLevelPackedRO {
private import etc.c.zlib;
uint rc = 1;
size_t nfop; // hide it from GC
private @property inout(Nfo*) nfo () inout pure nothrow @trusted @nogc { pragma(inline, true); return cast(typeof(return))nfop; }
static void decRef (size_t me) {
if (me) {
auto zl = cast(LowLevelPackedRO*)me;
assert(zl.rc);
if (--zl.rc == 0) {
import core.stdc.stdlib : free;
if (zl.chunkData !is null) free(zl.chunkData);
version(arcz_use_more_memory) if (zl.pkdata !is null) free(zl.pkdata);
Nfo.decRef(zl.nfop);
free(zl);
debug(arcz_rc) { import core.stdc.stdio : printf; printf("Zl %p freed\n", zl); }
} else {
//debug(arcz_rc) { import core.stdc.stdio : printf; printf("Zl %p; rc after decRef is %u\n", zl, zl.rc); }
}
}
}
uint nextchunk; // next chunk to read
uint curcpos; // position in current chunk
uint curcsize; // number of valid bytes in `chunkData`
uint stchunk; // starting chunk
uint stofs; // offset in starting chunk
uint totalsize; // total file size
uint pos; // current file position
uint lastrdpos; // last actual read position
z_stream zs;
ubyte* chunkData; // can be null
version(arcz_use_more_memory) {
ubyte* pkdata;
uint pkdatasize;
}
@disable this (this);
void setup (Nfo* anfo, uint astchunk, uint astofs, uint asize) {
assert(anfo !is null);
assert(rc == 1);
nfop = cast(size_t)anfo;
++anfo.rc;
nextchunk = stchunk = astchunk;
//curcpos = 0;
stofs = astofs;
totalsize = asize;
}
@property bool eof () { pragma(inline, true); return (pos >= totalsize); }
// return less than chunk size if our file fits in one non-full chunk completely
uint justEnoughMemory () pure const nothrow @safe @nogc {
pragma(inline, true);
version(none) {
return nfo.chunkSize;
} else {
return (totalsize < nfo.chunkSize && stofs+totalsize < nfo.chunkSize ? stofs+totalsize : nfo.chunkSize);
}
}
void unpackNextChunk () {
if (nfop == 0) assert(0, "wtf?!");
//scope(failure) if (chunkData !is null) { xfree(chunkData); chunkData = null; }
debug(arcz_unp) { import core.stdc.stdio : printf; printf("unpacking chunk %u\n", nextchunk); }
// allocate buffer for unpacked data
if (chunkData is null) {
// optimize things a little: if our file fits in less then one chunk, allocate "just enough" memory
chunkData = xalloc!(ubyte, false)(justEnoughMemory);
}
auto chunk = &nfo.chunks[nextchunk];
if (chunk.pksize == nfo.chunkSize) {
// unpacked chunk, just read it
debug(arcz_unp) { import core.stdc.stdio : printf; printf(" chunk is not packed\n"); }
if (fseek(nfo.afl, chunk.ofs, 0) < 0) throw new Exception("ARCZ reading error");
if (fread(chunkData, 1, nfo.chunkSize, nfo.afl) != nfo.chunkSize) throw new Exception("ARCZ reading error");
curcsize = nfo.chunkSize;
} else {
// packed chunk, unpack it
// allocate buffer for packed data
version(arcz_use_more_memory) {
import core.stdc.stdlib : realloc;
if (pkdatasize < chunk.pksize) {
import core.exception : onOutOfMemoryError;
auto newpk = realloc(pkdata, chunk.pksize);
if (newpk is null) onOutOfMemoryError();
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("reallocated from %u to %u bytes; %p -> %p\n", cast(uint)pkdatasize, cast(uint)chunk.pksize, pkdata, newpk); }
pkdata = cast(ubyte*)newpk;
pkdatasize = chunk.pksize;
}
alias pkd = pkdata;
} else {
auto pkd = xalloc!(ubyte, false)(chunk.pksize);
scope(exit) xfree(pkd);
}
if (fseek(nfo.afl, chunk.ofs, 0) < 0) throw new Exception("ARCZ reading error");
if (fread(pkd, 1, chunk.pksize, nfo.afl) != chunk.pksize) throw new Exception("ARCZ reading error");
uint upsize = (nextchunk == nfo.chunks.length-1 ? nfo.lastChunkSize : nfo.chunkSize); // unpacked chunk size
immutable uint cksz = upsize;
immutable uint jem = justEnoughMemory;
if (upsize > jem) upsize = jem;
debug(arcz_unp) { import core.stdc.stdio : printf; printf(" unpacking %u bytes to %u bytes\n", chunk.pksize, upsize); }
ArzArchive.unpackBlock(chunkData, upsize, pkd, chunk.pksize, cksz, nfo.useBalz);
curcsize = upsize;
}
curcpos = 0;
// fix first chunk offset if necessary
if (nextchunk == stchunk && stofs > 0) {
// it's easier to just memmove it
import core.stdc.string : memmove;
assert(stofs < curcsize);
memmove(chunkData, chunkData+stofs, curcsize-stofs);
curcsize -= stofs;
}
++nextchunk; // advance to next chunk
}
void syncReadPos () {
if (pos >= totalsize || pos == lastrdpos) return;
immutable uint fcdata = nfo.chunkSize-stofs; // number of our bytes in the first chunk
// does our pos lie in the first chunk?
if (pos < fcdata) {
// yep, just read it
if (nextchunk != stchunk+1) {
nextchunk = stchunk;
unpackNextChunk(); // we'll need it anyway
} else {
// just rewind
curcpos = 0;
}
curcpos += pos;
lastrdpos = pos;
return;