Repository navigation
Expand file tree
/
Copy pathmodule.ae
More file actions
1340 lines (1224 loc) · 49.1 KB
/
Copy pathmodule.ae
File metadata and controls
1340 lines (1224 loc) · 49.1 KB
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
// std.zip — a ZIP archive READER and WRITER over an in-memory byte buffer,
// plus a safe-by-default extract-to-disk layer (#2010 and follow-ups).
//
// A .zip is a CONTAINER, not a compressed blob: a set of entries (each
// `stored` or `deflate`d) indexed by a Central Directory whose location is
// found from an End-Of-Central-Directory (EOCD) record at the tail of the
// file, extended by the ZIP64 records for archives that exceed the 32-bit
// fields. std.zlib supplies the decompression (raw inflate, RFC 1951); this
// module parses the container.
//
// Buffer, not filesystem: `open(data)` reads a .zip already in memory —
// downloaded over HTTP, unpacked from another archive, embedded in a payload.
// There is no path/fd here, matching std.json / std.cbor / std.resp. (An
// extract-to-disk layer belongs on top and is a separate concern.)
//
// The Central Directory is the source of truth for entry metadata (a local
// file header may zero its sizes and defer them to a trailing data
// descriptor, which streaming writers rely on). Names are decoded as UTF-8
// when the entry's flag bit 11 is set, else treated as raw bytes.
//
// Coverage: `stored` (method 0) and `deflate` (method 8); ZIP64 sizes,
// offsets and entry counts; per-entry CRC-32 verification on read. Encrypted
// entries, multi-disk archives, and other compression methods are REFUSED
// with a clear error rather than silently mis-decoded.
//
// ar, err = zip.open(bytes.view(buf)) // or string.bytes(s)
// n = zip.count(ar)
// i = 0
// while i < n {
// name = zip.entry_name(ar, i)
// body, blen, rerr = zip.entry_read(ar, i) // decompressed + CRC-checked
// // ... use body ...
// i = i + 1
// }
// zip.close(ar)
import std.list
import std.string
import std.bytes
import std.zlib
import std.hash
import std.io
import std.fs
exports(
// compression methods
METHOD_STORED, METHOD_DEFLATE,
// lifecycle
open, close,
// directory
count, find,
// per-entry metadata
entry_name, entry_size, entry_compressed_size, entry_method, entry_crc32,
entry_is_dir, entry_is_encrypted,
// per-entry data
entry_read,
// writer (#2010 follow-up): build a .zip in memory
writer_new, writer_add, writer_add_dir, writer_finish, writer_free,
create,
// directory-tree writer: add a filesystem tree to an archive
add_dir_tree,
// extract to disk (#2010 follow-up): safe by default
ExtractOptions, default_extract_options, extract, extract_file,
)
extern malloc(size: int) -> ptr
@extern("free") libc_free(p: ptr)
extern string_length(s: string) -> int
const METHOD_STORED = 0
const METHOD_DEFLATE = 8
// Signatures (little-endian on the wire).
const SIG_EOCD = 0x06054b50 // "PK\5\6" end of central directory
const SIG_EOCD64 = 0x06064b50 // "PK\6\6" ZIP64 EOCD record
const SIG_EOCD64_LOC = 0x07064b50 // "PK\6\7" ZIP64 EOCD locator
const SIG_CDH = 0x02014b50 // "PK\1\2" central directory header
const SIG_LFH = 0x04034b50 // "PK\3\4" local file header
// One decoded central-directory entry. Sizes/offset are `long` because ZIP64
// carries 64-bit values.
struct ZipEntry {
name: ptr // owned AetherBytes holding the UTF-8/raw name
name_len: int
method: int
flags: int
crc32: int // stored as the wire's unsigned 32-bit value in an int slot
comp_size: long
uncomp_size: long
lfh_offset: long // offset of this entry's local file header
}
// An opened archive: the whole file buffered, plus the parsed entry list.
struct ZipArchive {
buf: ptr // owned AetherBytes: the entire .zip
buf_len: int
entries: ptr // std.list of *ZipEntry
}
// ---- CRC-32 (IEEE 802.3, the ZIP polynomial) -------------------------------
// Pure Aether so std.zip carries its own integrity check rather than reaching
// into zlib internals. Table built once on first use.
var g_crc_table: ptr = null
fn crc_table() -> ptr {
if g_crc_table != null { return g_crc_table }
t = bytes.new(256 * 4)
bytes.set(t, 256 * 4 - 1, 0)
// CRC-32 polynomial (reflected). Held in an int; the mask keeps it 32-bit
// (bit 31 is set, so the literal is wide — the & pins it back to int).
poly = 0xEDB88320 & 0xFFFFFFFF
n = 0
while n < 256 {
var c: int = n
k = 0
while k < 8 {
if (c & 1) == 1 {
c = poly ^ ((c >> 1) & 0x7FFFFFFF)
} else {
c = (c >> 1) & 0x7FFFFFFF
}
k = k + 1
}
bytes.set_le32(t, n * 4, c)
n = n + 1
}
g_crc_table = t
return t
}
// CRC-32 of `len` bytes of `src` starting at `off` in an AetherBytes buffer.
fn crc32_bytes(src: ptr, off: int, len: int) -> int {
t = crc_table()
var crc: int = 0xFFFFFFFF & 0xFFFFFFFF
i = 0
while i < len {
b = bytes.get(src, off + i) & 0xFF
idx = (crc ^ b) & 0xFF
// logical >> 8: mask off the sign bits an arithmetic shift would carry.
crc = bytes.get_le32(t, idx * 4) ^ ((crc >> 8) & 0x00FFFFFF)
i = i + 1
}
return (crc ^ 0xFFFFFFFF) & 0xFFFFFFFF
}
// ---- little helpers over the archive buffer --------------------------------
fn u16(b: ptr, at: int) -> int { return bytes.get_le16(b, at) }
fn u32(b: ptr, at: int) -> int { return bytes.get_le32(b, at) }
fn u64(b: ptr, at: int) -> long { return bytes.get_le64(b, at) }
// get_le32 returns a signed int, so a 32-bit field with the high bit set (any
// value >= 0x80000000, and notably the 0xFFFFFFFF ZIP64 sentinel) comes back
// negative. Read it as an unsigned 32-bit value widened into a long.
fn u32l(b: ptr, at: int) -> long {
v = bytes.get_le32(b, at)
return (v as long) & 0xFFFFFFFF
}
// True when a 32-bit field holds the "see ZIP64" sentinel 0xFFFFFFFF.
const U32_MAX: long = 4294967295
// ---- EOCD + ZIP64 discovery ------------------------------------------------
// Find the EOCD record by scanning backward from the end for its signature.
// The record is 22 bytes plus a variable-length comment (<= 65535), so the
// signature lies within the last 65557 bytes. Returns the offset or -1.
fn find_eocd(b: ptr, blen: int) -> int {
if blen < 22 { return -1 }
max_back = 65557
start = blen - max_back
if start < 0 { start = 0 }
// The record normally ends the file: its comment-length field (at +20)
// reaches exactly the end of the buffer. A signature inside the comment
// fails that test (its own "comment" would end elsewhere), so the scan
// keeps going backward past it to the real record. An archive with bytes
// appended after the record (padding, a signature block) has no exact
// match; then the latest candidate whose comment fits inside the buffer
// is the record, as Python's zipfile reads it. Refusing those archives
// outright was a regression.
fallback = 0 - 1
pos = blen - 22
while pos >= start {
if u32(b, pos) == SIG_EOCD {
end = pos + 22 + u16(b, pos + 20)
if end == blen {
return pos
}
if end < blen && fallback < 0 {
fallback = pos
}
}
pos = pos - 1
}
return fallback
}
// ---- central-directory parse -----------------------------------------------
fn alloc_entry() -> *ZipEntry {
e = malloc(sizeof(ZipEntry)) as *ZipEntry
e.name = null
e.name_len = 0
e.method = 0
e.flags = 0
e.crc32 = 0
e.comp_size = 0
e.uncomp_size = 0
e.lfh_offset = 0
return e
}
fn free_entry(e: *ZipEntry) {
if e.name != null { bytes.free(e.name) }
libc_free(e as ptr)
}
// Parse the central directory starting at `cd_off`, `total` entries expected.
// Returns (list_of_*ZipEntry, "") or (null, err).
fn parse_central_dir(b: ptr, blen: int, cd_off: long, total: long) -> (ptr, string) {
lst = list.new()
pos = cd_off as int
i = 0
while i < total {
if pos + 46 > blen { free_entries(lst); return null, "zip: central directory truncated" }
if u32(b, pos) != SIG_CDH {
free_entries(lst)
return null, "zip: bad central directory header signature"
}
flags = u16(b, pos + 8)
method = u16(b, pos + 10)
crc = u32(b, pos + 16)
comp = u32l(b, pos + 20)
uncomp = u32l(b, pos + 24)
name_len = u16(b, pos + 28)
extra_len = u16(b, pos + 30)
comment_len = u16(b, pos + 32)
lfh = u32l(b, pos + 42)
name_at = pos + 46
if name_at + name_len > blen { free_entries(lst); return null, "zip: entry name truncated" }
e = alloc_entry()
e.flags = flags
e.method = method
e.crc32 = crc
e.comp_size = comp
e.uncomp_size = uncomp
e.lfh_offset = lfh
if name_len > 0 {
nb = bytes.new(name_len)
bytes.set(nb, name_len - 1, 0)
bytes.copy_from_bytes(nb, 0, b, name_at, name_len)
e.name = nb
e.name_len = name_len
}
// ZIP64 extra field (id 0x0001): replaces any 0xFFFFFFFF fields, in the
// fixed order uncompressed, compressed, lfh offset, disk#.
extra_at = name_at + name_len
parse_zip64_extra(b, extra_at, extra_len, e)
// The ZIP64 values are unsigned 64-bit on the wire but held in a
// signed long: one at or past 2^63 reads back negative. No archive
// has a negative size or offset, and a negative size would slip
// under extract's limits (and shrink its running total), so refuse
// the archive here, where every caller of entry_size is covered.
if e.comp_size < 0 || e.uncomp_size < 0 || e.lfh_offset < 0 {
free_entry(e)
free_entries(lst)
return null, "zip: entry size or offset out of range"
}
list.add_raw(lst, e as ptr)
pos = extra_at + extra_len + comment_len
i = i + 1
}
return lst, ""
}
// Walk the extra-field blocks looking for the ZIP64 record, and pull the
// 64-bit values in for any field the 32-bit slot flagged as 0xFFFFFFFF.
fn parse_zip64_extra(b: ptr, at: int, total_len: int, e: *ZipEntry) {
p = at
stop = at + total_len
while p + 4 <= stop {
hid = u16(b, p)
hsz = u16(b, p + 2)
body = p + 4
if hid == 0x0001 {
q = body
if e.uncomp_size == U32_MAX && q + 8 <= stop { e.uncomp_size = u64(b, q); q = q + 8 }
if e.comp_size == U32_MAX && q + 8 <= stop { e.comp_size = u64(b, q); q = q + 8 }
if e.lfh_offset == U32_MAX && q + 8 <= stop { e.lfh_offset = u64(b, q); q = q + 8 }
}
p = body + hsz
}
}
fn free_entries(lst: ptr) {
if lst == null { return }
n = list.size(lst)
i = 0
while i < n {
free_entry(list.get_raw(lst, i) as *ZipEntry)
i = i + 1
}
list.free(lst)
}
// ---- public: open / close --------------------------------------------------
// A slice with no bound (`p as byte[]`, `.len` -1) has no length.
fn unbounded(fname: string) {
panic("zip.${fname}: the slice has no bound (.len -1); give it one, as `(p as byte[])[0..n]`")
}
// Open a ZIP archive held entirely in `data` (#2301: a byte[] whose length
// travels with it — pass a string as `string.bytes(s)`, a `std.bytes` buffer
// as `bytes.view(buf)`). Returns (archive_ptr, "") or (null, err). The
// archive owns a copy of the bytes, so `data` need not outlive this call;
// free the archive with close().
open(data: byte[]) -> (ptr, string) {
if data.len < 0 { unbounded("open") }
int len = data.len
if len < 22 { return null, "zip: too small to be a zip archive" }
buf = bytes.from_slice(data)
eocd = find_eocd(buf, len)
if eocd < 0 {
bytes.free(buf)
return null, "zip: no end-of-central-directory record (not a zip, or truncated)"
}
disk = u16(buf, eocd + 4)
cd_disk = u16(buf, eocd + 6)
total = u16(buf, eocd + 10) as long
cd_off = u32l(buf, eocd + 16)
// ZIP64: any of these fields at their 0xFFFF/0xFFFFFFFF sentinel means the
// real values live in the ZIP64 EOCD record, located via the ZIP64 EOCD
// locator which sits 20 bytes before the EOCD.
need64 = 0
if total == 0xFFFF { need64 = 1 }
if cd_off == U32_MAX { need64 = 1 }
if disk == 0xFFFF { need64 = 1 }
if need64 == 1 {
loc = eocd - 20
if loc >= 0 && u32(buf, loc) == SIG_EOCD64_LOC {
// A 64-bit field read into a signed long: range-check it as a
// long, before any narrowing, so a value past 2^31 or 2^63 is
// refused rather than wrapped into an in-range int.
z64 = u64(buf, loc + 8)
if z64 >= 0 && z64 <= (len as long) - 56 {
zi = z64 as int
if u32(buf, zi) == SIG_EOCD64 {
total = u64(buf, zi + 32)
cd_off = u64(buf, zi + 48)
cd_disk = u16(buf, zi + 16)
disk = cd_disk
}
}
}
}
if disk != cd_disk {
bytes.free(buf)
return null, "zip: multi-disk / spanned archives are not supported"
}
if total < 0 {
bytes.free(buf)
return null, "zip: entry count out of range"
}
if cd_off < 0 || cd_off > len as long {
bytes.free(buf)
return null, "zip: central directory offset out of range"
}
entries, perr = parse_central_dir(buf, len, cd_off, total)
if string.equals(perr, "") != 1 {
bytes.free(buf)
return null, perr
}
ar = malloc(sizeof(ZipArchive)) as *ZipArchive
ar.buf = buf
ar.buf_len = len
ar.entries = entries
return ar as ptr, ""
}
close(arp: ptr) {
if arp == null { return }
ar = arp as *ZipArchive
free_entries(ar.entries)
if ar.buf != null { bytes.free(ar.buf) }
libc_free(arp)
}
// ---- directory access ------------------------------------------------------
count(arp: ptr) -> int {
ar = arp as *ZipArchive
return list.size(ar.entries)
}
fn entry_at(arp: ptr, i: int) -> *ZipEntry {
ar = arp as *ZipArchive
return list.get_raw(ar.entries, i) as *ZipEntry
}
// Index of the entry named `name`, or -1. Exact byte match on the stored name.
find(arp: ptr, name: string) -> int {
ar = arp as *ZipArchive
n = list.size(ar.entries)
i = 0
while i < n {
en = entry_name(arp, i)
if string.equals(en, name) == 1 { return i }
i = i + 1
}
return -1
}
// ---- per-entry metadata ----------------------------------------------------
entry_name(arp: ptr, i: int) -> string {
e = entry_at(arp, i)
if e.name == null || e.name_len == 0 { return string.concat("", "") }
return bytes.to_string(e.name, e.name_len)
}
entry_size(arp: ptr, i: int) -> long { return entry_at(arp, i).uncomp_size }
entry_compressed_size(arp: ptr, i: int) -> long { return entry_at(arp, i).comp_size }
entry_method(arp: ptr, i: int) -> int { return entry_at(arp, i).method }
entry_crc32(arp: ptr, i: int) -> int { return entry_at(arp, i).crc32 }
// A directory entry is conventionally a zero-size name ending in '/'.
entry_is_dir(arp: ptr, i: int) -> int {
e = entry_at(arp, i)
if e.name == null || e.name_len == 0 { return 0 }
last = bytes.get(e.name, e.name_len - 1) & 0xFF
if last == 47 { return 1 } // '/'
return 0
}
// General-purpose bit 0 set = the entry is encrypted.
entry_is_encrypted(arp: ptr, i: int) -> int {
e = entry_at(arp, i)
if (e.flags & 1) == 1 { return 1 }
return 0
}
// ---- per-entry data --------------------------------------------------------
// Read and decompress entry `i`, verifying its CRC-32. Returns
// (bytes_as_string, length, "") or ("", 0, err). The local file header is
// consulted only to skip its variable name+extra fields to reach the data;
// the sizes/CRC come from the central directory.
entry_read(arp: ptr, i: int) -> (string, int, string) {
ar = arp as *ZipArchive
b = ar.buf
blen = ar.buf_len
// An index past the central directory has no entry: say so rather than
// read through the missing one.
if i < 0 || i >= list.size(ar.entries) {
return "", 0, "zip: no entry at index ${i}"
}
e = entry_at(arp, i)
if (e.flags & 1) == 1 {
return "", 0, "zip: entry is encrypted; not supported"
}
if e.method != METHOD_STORED && e.method != METHOD_DEFLATE {
return "", 0, "zip: unsupported compression method"
}
// Offsets and sizes are longs (ZIP64): bound them against the buffer as
// longs, and narrow to int only once they are known to fit.
blen_l = blen as long
if e.lfh_offset < 0 || e.lfh_offset > blen_l - 30 {
return "", 0, "zip: bad local file header"
}
lfh = e.lfh_offset as int
if u32(b, lfh) != SIG_LFH {
return "", 0, "zip: bad local file header"
}
lname = u16(b, lfh + 26)
lextra = u16(b, lfh + 28)
data_at_l = (lfh as long) + 30 + lname + lextra
// data_at_l <= blen_l here, so the subtraction cannot wrap; the sum
// could, for a ZIP64 size near 2^63.
if e.comp_size < 0 || e.comp_size > blen_l - data_at_l {
return "", 0, "zip: entry data out of range"
}
data_at = data_at_l as int
comp = e.comp_size as int
if e.method == METHOD_STORED {
// No compression: data is the content verbatim, so its size IS the
// uncompressed size. A central directory that says otherwise is
// lying about entry_size, and extract's limits are checked against
// entry_size: refuse it rather than return more than it claimed.
if e.comp_size != e.uncomp_size {
return "", 0, "zip: stored entry size mismatch"
}
got = crc32_bytes(b, data_at, comp)
if (got & 0xFFFFFFFF) != (e.crc32 & 0xFFFFFFFF) {
return "", 0, "zip: CRC mismatch (stored entry)"
}
out = slice_string(b, data_at, comp)
return out, comp, ""
}
// DEFLATE (method 8): the compressed span is a raw deflate stream.
// Inflated with a cap at the stated uncompressed size, so an entry
// that lies about its size is stopped as it crosses the claim, not
// after expanding (up to ~1032x its compressed size) in memory.
if e.uncomp_size > 2147483647 {
return "", 0, "zip: entry too large to read into memory"
}
comp_str = slice_string(b, data_at, comp)
body, blen2, ie = zlib.inflate_raw_max(string.bytes(comp_str)[0..comp], e.uncomp_size as int)
if string.equals(ie, "") != 1 {
return "", 0, "zip: ${ie}"
}
// Verify against the central-directory CRC and size: a stream that
// ends short of the stated size is as wrong as one that runs past it.
if blen2 as long != e.uncomp_size {
return "", 0, "zip: decompressed size mismatch"
}
chk = bytes.new(blen2)
if blen2 > 0 { bytes.set(chk, blen2 - 1, 0) }
bytes.copy_from_string(chk, 0, body, blen2)
got = crc32_bytes(chk, 0, blen2)
bytes.free(chk)
if (got & 0xFFFFFFFF) != (e.crc32 & 0xFFFFFFFF) {
return "", 0, "zip: CRC mismatch (deflate entry)"
}
return body, blen2, ""
}
// Copy the [off, off+len) span of an AetherBytes buffer out as an owned
// string (binary-safe: the length is carried, not strlen-derived).
fn slice_string(b: ptr, off: int, len: int) -> string {
tmp = bytes.new(len)
if len > 0 { bytes.set(tmp, len - 1, 0) }
bytes.copy_from_bytes(tmp, 0, b, off, len)
s = bytes.to_string(tmp, len)
bytes.free(tmp)
return s
}
// ============================================================================
// Writer — build a .zip entirely in memory (#2010 follow-up).
//
// The mirror of the reader: entries are appended one at a time, each emitted
// as a Local File Header + (stored or raw-deflated) data as it is added, and
// `writer_finish` appends the Central Directory and End-Of-Central-Directory
// record and hands back the finished bytes. Buffer in, buffer out — no path
// or fd, exactly as `open` takes a buffer. An extract-to-disk / directory
// layer belongs on top and is a separate concern.
//
// w = zip.writer_new()
// zip.writer_add(w, "a.txt", string.bytes(data_a), zip.METHOD_DEFLATE, 6)
// zip.writer_add(w, "b.bin", string.bytes(data_b), zip.METHOD_STORED, 0)
// out, outlen, err = zip.writer_finish(w) // `out` is a valid .zip
// zip.writer_free(w)
//
// ZIP64 is emitted automatically when a size, an offset, or the entry count
// exceeds its 32-bit field — the same records the reader already parses back.
const VERSION_NEEDED = 20 // 2.0: deflate + folder support
const VERSION_NEEDED_ZIP64 = 45 // 4.5: ZIP64 extensions
const FLAG_UTF8 = 0x0800 // general-purpose bit 11: name/comment are UTF-8
// One queued entry's central-directory facts. The data itself is already in
// the writer's buffer at `lfh_offset`; this is only what the CD needs later.
struct ZipWEntry {
name: ptr // owned AetherBytes holding the UTF-8 name
name_len: int
method: int
crc32: int // unsigned 32-bit CRC in an int slot
comp_size: long
uncomp_size: long
lfh_offset: long
}
// The output archive under construction: the growing buffer, the running
// write position (= buffer logical length), and the entry list for the CD.
struct ZipWriter {
buf: ptr // owned AetherBytes: LFHs + data so far, CD appended at finish
pos: int // next write offset == current logical length
entries: ptr // std.list of *ZipWEntry
}
fn alloc_wentry() -> *ZipWEntry {
e = malloc(sizeof(ZipWEntry)) as *ZipWEntry
e.name = null
e.name_len = 0
e.method = 0
e.crc32 = 0
e.comp_size = 0
e.uncomp_size = 0
e.lfh_offset = 0
return e
}
fn free_wentry(e: *ZipWEntry) {
if e.name != null { bytes.free(e.name) }
libc_free(e as ptr)
}
// Write `len` bytes of a string into the writer's buffer at the current
// position and advance. The buffer auto-grows.
fn w_put_str(w: *ZipWriter, s: string, len: int) {
if len > 0 {
bytes.copy_from_string(w.buf, w.pos, s, len)
w.pos = w.pos + len
}
}
fn w_put_slice(w: *ZipWriter, s: byte[]) {
if s.len > 0 {
bytes.copy_from_slice(w.buf, w.pos, s)
w.pos = w.pos + s.len
}
}
fn w_put_u16(w: *ZipWriter, v: int) {
bytes.set_le16(w.buf, w.pos, v & 0xFFFF)
w.pos = w.pos + 2
}
fn w_put_u32(w: *ZipWriter, v: int) {
bytes.set_le32(w.buf, w.pos, v)
w.pos = w.pos + 4
}
fn w_put_u32l(w: *ZipWriter, v: long) {
// Low 32 bits of a long into a 4-byte LE field. Narrow to an int slot
// first (a bare `v as int` does not truncate), so the high word is
// dropped exactly.
var lo: int = v & 0xFFFFFFFF
bytes.set_le32(w.buf, w.pos, lo)
w.pos = w.pos + 4
}
fn w_put_u64(w: *ZipWriter, v: long) {
bytes.set_le64(w.buf, w.pos, v)
w.pos = w.pos + 8
}
// Emit a Local File Header + the entry name. Sizes are known up front, so no
// data descriptor is used (general-purpose bit 3 stays clear). The caller
// writes the payload bytes immediately after.
fn w_put_local_header(w: *ZipWriter, method: int, crc: int,
comp_len: int, uncomp_len: int, name: string, name_len: int) {
w_put_u32(w, SIG_LFH)
w_put_u16(w, VERSION_NEEDED)
w_put_u16(w, FLAG_UTF8)
w_put_u16(w, method)
w_put_u16(w, 0) // mod time (0 = unset; readers tolerate it)
w_put_u16(w, 0) // mod date
w_put_u32(w, crc)
w_put_u32(w, comp_len)
w_put_u32(w, uncomp_len)
w_put_u16(w, name_len)
w_put_u16(w, 0) // extra field length
w_put_str(w, name, name_len)
}
// Start a fresh in-memory archive. Free it with writer_free.
writer_new() -> ptr {
w = malloc(sizeof(ZipWriter)) as *ZipWriter
w.buf = bytes.new(256)
w.pos = 0
w.entries = list.new()
return w as ptr
}
// Release a writer and every entry it holds. Safe on a null pointer.
writer_free(wp: @frees ptr) {
if wp == null { return }
w = wp as *ZipWriter
if w.entries != null {
n = list_size(w.entries)
i = 0
while i < n {
free_wentry(list.at(w.entries, i) as *ZipWEntry)
i = i + 1
}
list.free(w.entries)
}
if w.buf != null { bytes.free(w.buf) }
libc_free(w as ptr)
}
// Shared body of writer_add / writer_add_dir. `data` may be empty (a
// directory, or a zero-length file). `method` is METHOD_STORED or
// METHOD_DEFLATE; `level` (0..9, or -1) applies to deflate. Returns "" or an
// error. On error the writer is left unchanged (nothing was appended).
fn w_add_entry(w: *ZipWriter, name: string, name_len: int,
data: byte[], method: int, level: int) -> string {
if data.len < 0 { unbounded("writer_add") }
int data_len = data.len
if name_len < 0 { return "zip: negative length" }
// CRC-32 is over the UNCOMPRESSED bytes, read straight from the slice
// (#2301) — no scratch copy. Narrowing the unsigned 32-bit value into the
// `int` keeps exactly the bits the record stores.
var crc: int = 0
if data_len > 0 {
crc = hash.crc32(data)
}
// Compress if asked, but never let a "compressed" entry come out larger
// than stored — fall back to stored, as every real zip writer does. The
// whole entry is emitted inside the arm that owns the compressed string,
// so that string (`cc`) is released once, at the end of its own scope.
var use_method: int = METHOD_STORED
var comp_len: int = data_len
lfh_off = w.pos
if method == METHOD_DEFLATE && data_len > 0 {
cc, cl, derr = zlib.deflate_raw(data, level)
if string.equals(derr, "") != 1 {
// Static message (no interpolation): keeps this function's return
// a borrowed string literal, so callers' `err` slots stay non-heap
// and are not leaked on the success path. `derr` is one of a small
// fixed set from zlib.deflate_raw ("zlib unavailable" / "raw
// deflate failed"); losing it from the text is acceptable.
return "zip: deflate failed"
}
if cl < data_len {
use_method = METHOD_DEFLATE
comp_len = cl
w_put_local_header(w, use_method, crc, comp_len, data_len, name, name_len)
w_put_str(w, cc, comp_len)
} else {
// not smaller: keep stored, write the raw data
comp_len = data_len
w_put_local_header(w, use_method, crc, comp_len, data_len, name, name_len)
w_put_slice(w, data)
}
string.free(cc)
} else {
w_put_local_header(w, use_method, crc, comp_len, data_len, name, name_len)
w_put_slice(w, data)
}
// ---- record for the central directory ---------------------------------
e = alloc_wentry()
e.name = bytes.new(name_len)
if name_len > 0 {
bytes.set(e.name, name_len - 1, 0)
bytes.copy_from_string(e.name, 0, name, name_len)
}
e.name_len = name_len
e.method = use_method
e.crc32 = crc
e.comp_size = comp_len as long
e.uncomp_size = data_len as long
e.lfh_offset = lfh_off as long
list.add(w.entries, e as ptr)
return ""
}
// Add a file entry holding the bytes of `data` (#2301: pass a string as
// `string.bytes(s)`). `name` is the archive path (forward slashes). `method`
// is zip.METHOD_STORED or zip.METHOD_DEFLATE; `level` is 0..9 (or -1) and is
// ignored for stored. Returns "" on success, else an error. The bytes are
// copied into the archive, so `data` need not outlive the call.
writer_add(wp: ptr, name: string, data: byte[], method: int, level: int) -> string {
if wp == null { return "zip: null writer" }
w = wp as *ZipWriter
return w_add_entry(w, name, string_length(name), data, method, level)
}
// Add a directory entry (a name ending in "/", zero-length, stored). A "/"
// is appended if the caller left it off.
writer_add_dir(wp: ptr, name: string) -> string {
if wp == null { return "zip: null writer" }
w = wp as *ZipWriter
nlen = string_length(name)
var dname: string = name
var owns: int = 0
if nlen == 0 || string.char_at(name, nlen - 1) != 47 { // 47 == '/'
dname = string.concat(name, "/")
nlen = nlen + 1
owns = 1
}
err = w_add_entry(w, dname, nlen, string.bytes(""), METHOD_STORED, 0)
if owns == 1 { string.free(dname) }
return err
}
// Finish: append the Central Directory and EOCD, and return the archive as
// (bytes, length, ""). ZIP64 records are emitted when any field overflows 32
// bits. The writer's buffer still owns the bytes; free with writer_free after
// the returned string has been used (it is an independent copy).
//
// Inferred return type (`-> {`), not an explicit `(string, int, string)`: the
// archive bytes come from bytes.to_string, whose `@heap` classification only
// propagates to the caller's destructure site through an inferred tuple. An
// explicit tuple type cannot carry the per-position `@heap` flag, so the
// returned string would leak when passed on (e.g. through create).
writer_finish(wp: ptr) -> {
if wp == null { return "", 0, "zip: null writer" }
w = wp as *ZipWriter
n = list_size(w.entries)
cd_start = w.pos
i = 0
while i < n {
e = list.at(w.entries, i) as *ZipWEntry
// A field that overflows 32 bits is written as the 0xFFFFFFFF sentinel
// in the fixed record and carried in a ZIP64 extra block.
var need_zip64: int = 0
if e.comp_size >= U32_MAX { need_zip64 = 1 }
if e.uncomp_size >= U32_MAX { need_zip64 = 1 }
if e.lfh_offset >= U32_MAX { need_zip64 = 1 }
var extra_len: int = 0
if need_zip64 == 1 { extra_len = 28 } // 2+2 header + 3x8 fields
w_put_u32(w, SIG_CDH)
w_put_u16(w, VERSION_NEEDED_ZIP64) // version made by
if need_zip64 == 1 { w_put_u16(w, VERSION_NEEDED_ZIP64) }
else { w_put_u16(w, VERSION_NEEDED) } // version needed
w_put_u16(w, FLAG_UTF8)
w_put_u16(w, e.method)
w_put_u16(w, 0) // mod time
w_put_u16(w, 0) // mod date
w_put_u32(w, e.crc32)
if need_zip64 == 1 {
w_put_u32(w, -1) // 0xFFFFFFFF comp size sentinel
w_put_u32(w, -1) // 0xFFFFFFFF uncomp size sentinel
} else {
w_put_u32l(w, e.comp_size)
w_put_u32l(w, e.uncomp_size)
}
w_put_u16(w, e.name_len)
w_put_u16(w, extra_len)
w_put_u16(w, 0) // comment length
w_put_u16(w, 0) // disk number start
w_put_u16(w, 0) // internal attributes
w_put_u32(w, 0) // external attributes
if need_zip64 == 1 {
w_put_u32(w, -1) // 0xFFFFFFFF lfh offset sentinel
} else {
w_put_u32l(w, e.lfh_offset)
}
// name — copy the bytes buffer straight into the output, no string
if e.name_len > 0 {
bytes.copy_from_bytes(w.buf, w.pos, e.name, 0, e.name_len)
w.pos = w.pos + e.name_len
}
// ZIP64 extra block: tag 0x0001, then the fields present, order
// uncompressed / compressed / lfh offset (the reader reads them so).
if need_zip64 == 1 {
w_put_u16(w, 0x0001)
w_put_u16(w, 24) // 3 x 8-byte fields
w_put_u64(w, e.uncomp_size)
w_put_u64(w, e.comp_size)
w_put_u64(w, e.lfh_offset)
}
i = i + 1
}
cd_size = w.pos - cd_start
// Decide whether the archive as a whole needs the ZIP64 EOCD records.
var arch_zip64: int = 0
if n > 65534 { arch_zip64 = 1 }
if (cd_start as long) >= U32_MAX { arch_zip64 = 1 }
if (cd_size as long) >= U32_MAX { arch_zip64 = 1 }
if arch_zip64 == 1 {
z64_eocd_off = w.pos
// ---- ZIP64 EOCD record --------------------------------------------
w_put_u32(w, SIG_EOCD64)
w_put_u64(w, 44 as long) // size of remainder of this record
w_put_u16(w, VERSION_NEEDED_ZIP64) // version made by
w_put_u16(w, VERSION_NEEDED_ZIP64) // version needed
w_put_u32(w, 0) // this disk
w_put_u32(w, 0) // disk with CD start
w_put_u64(w, n as long) // entries on this disk
w_put_u64(w, n as long) // total entries
w_put_u64(w, cd_size as long)
w_put_u64(w, cd_start as long)
// ---- ZIP64 EOCD locator -------------------------------------------
w_put_u32(w, SIG_EOCD64_LOC)
w_put_u32(w, 0) // disk with ZIP64 EOCD
w_put_u64(w, z64_eocd_off as long)
w_put_u32(w, 1) // total disks
}
// ---- End Of Central Directory -----------------------------------------
w_put_u32(w, SIG_EOCD)
w_put_u16(w, 0) // this disk
w_put_u16(w, 0) // disk with CD start
var entries_here: int = n
if n > 65535 { entries_here = 65535 } // sentinel; real count in ZIP64
w_put_u16(w, entries_here)
w_put_u16(w, entries_here)
if arch_zip64 == 1 {
w_put_u32(w, -1) // CD size sentinel
w_put_u32(w, -1) // CD offset sentinel
} else {
w_put_u32(w, cd_size)
w_put_u32(w, cd_start)
}
w_put_u16(w, 0) // comment length
out = bytes.to_string(w.buf, w.pos)
return out, w.pos, ""
}
// One-shot convenience: build a single-entry archive. For multiple entries
// use writer_new / writer_add / writer_finish.
create(name: string, data: byte[], method: int, level: int) -> {
w = writer_new()
err = writer_add(w, name, data, method, level)
if string.equals(err, "") == 1 {
// Heap-returning arm first: writer_finish's `out` is an owned string,
// and pinning the first tuple slot to it here keeps the caller's slot
// heap-classified (a `return "", 0, err` seen first would pin it to a
// non-heap literal and the returned string would leak).
out, outlen, ferr = writer_finish(w)
writer_free(w)
return out, outlen, ferr
}
writer_free(w)
return "", 0, err
}
// ============================================================================
// Directory-tree writer — add a filesystem tree to an archive (#2010 follow-up)
//
// Walk `fs_root` and add every regular file under it to the writer, naming each
// entry by its path relative to `fs_root` with `arc_prefix` prepended. This is
// a convenience over writer_add; the archive is still finished and freed by the
// caller. Directories are represented implicitly by their files' paths (a zip
// needs no explicit directory entries, and readers create the dirs on extract),
// except an empty directory, which would otherwise vanish — those get an
// explicit trailing-slash entry.
//
// w = zip.writer_new()
// err = zip.add_dir_tree(w, "site", "", zip.METHOD_DEFLATE, 6)
// out, n, ferr = zip.writer_finish(w)
// zip.writer_free(w)
struct DirTreeCtx {
w: ptr // *ZipWriter
root: ptr // owned AetherBytes: fs_root + "/" (the prefix to strip)
root_len: int
prefix: ptr // owned AetherBytes: arc_prefix (may be empty)
prefix_len: int
method: int
level: int
err: ptr // owned AetherBytes holding the first error, or null
}
// Record the first error seen inside the walk callback (later ones are ignored;
// the callback returns WALK_STOP to end the walk on the first).
fn dtc_set_err(ctx: *DirTreeCtx, msg: string) {
if ctx.err != null { return }
mlen = string_length(msg)
ctx.err = bytes.new(mlen + 1)
bytes.set(ctx.err, mlen, 0)
if mlen > 0 { bytes.copy_from_string(ctx.err, 0, msg, mlen) }
}
// Add a filesystem tree to the writer. `arc_prefix` is prepended to every
// entry name (use "" for none; a trailing "/" is added if missing and prefix
// is non-empty). `method`/`level` apply to every file. Returns "" or the first
// error encountered.
add_dir_tree(wp: @keep ptr, fs_root: string, arc_prefix: string, method: int, level: int) -> string {
if wp == null { return "zip: null writer" }
root_len = string_length(fs_root)
// Build the strip prefix: fs_root plus a single "/" so relative names have
// no leading slash. If fs_root already ends in "/", don't double it.
var strip: string = fs_root
var strip_owned: int = 0
if root_len > 0 && string.char_at(fs_root, root_len - 1) != 47 {
strip = string.concat(fs_root, "/")
strip_owned = 1
}
strip_len = string_length(strip)
// Normalise arc_prefix: non-empty and not slash-terminated -> add "/".
plen0 = string_length(arc_prefix)
var pfx: string = arc_prefix
var pfx_owned: int = 0