@preventive/archive 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ // Writes what GNU tar 1.35 writes for the same entries under `--owner=0
2
+ // --group=0 --numeric-owner` and, for pax, `--pax-option=delete=atime,
3
+ // delete=ctime`. Where GNU would cut or substitute — a name too long for
4
+ // ustar, a number out of range — this refuses instead.
5
+
6
+ import { EMPTY, concat, isAscii } from '../bytes.js'
7
+ import { DEFAULT_MODE, checkEntry, wireName } from '../entry.js'
8
+ import { ArchiveError } from '../error.js'
9
+ import { BLOCK, NAME_SIZE, OWNER_SIZE, PREFIX_SIZE, encodeHeader, fitsOctal, isDevice, octalMax } from './header.js'
10
+ import { Names, cleanNames } from '../names.js'
11
+ import { encodePax } from './pax.js'
12
+ import { checkString, encodeUtf8, hasUnsafe, quote } from '../text.js'
13
+
14
+ const TYPEFLAG = {
15
+ file: 0x30,
16
+ link: 0x31,
17
+ symlink: 0x32,
18
+ 'character-device': 0x33,
19
+ 'block-device': 0x34,
20
+ directory: 0x35,
21
+ fifo: 0x36,
22
+ 'contiguous-file': 0x37,
23
+ }
24
+ const LONGNAME = 0x4c
25
+ const LONGLINK = 0x4b
26
+ const PAX = 0x78
27
+
28
+ const FORMATS = new Set(['gnu', 'ustar', 'pax'])
29
+ const SLASH = 0x2f
30
+
31
+ function integer(value, what, signed = false) {
32
+ if (!Number.isSafeInteger(value) || (!signed && value < 0)) throw new ArchiveError(`${what} ${String(value)} is not ${signed ? 'an integer' : 'a non-negative integer'}`)
33
+ return value
34
+ }
35
+
36
+ function ownerName(value, what) {
37
+ checkString(value, what)
38
+ if (hasUnsafe(value, false)) throw new ArchiveError(`${what} ${quote(value)} holds a control or formatting character`)
39
+ return value
40
+ }
41
+
42
+ function normalize(entry) {
43
+ const checked = checkEntry(entry, TYPEFLAG)
44
+ const { name, type } = checked
45
+ const devmajor = integer(entry.devmajor ?? 0, 'devmajor')
46
+ const devminor = integer(entry.devminor ?? 0, 'devminor')
47
+ if ((devmajor !== 0 || devminor !== 0) && !isDevice(type)) throw new ArchiveError(`a ${type} cannot have device numbers (${quote(name)})`)
48
+ const mode = integer(entry.mode ?? DEFAULT_MODE[type] ?? 0o644, 'mode')
49
+ if (mode > 0o7777) throw new ArchiveError(`mode ${mode.toString(8)} has bits beyond the permission bits`)
50
+ return {
51
+ ...checked,
52
+ mode,
53
+ uid: integer(entry.uid ?? 0, 'uid'),
54
+ gid: integer(entry.gid ?? 0, 'gid'),
55
+ mtime: integer(entry.mtime ?? 0, 'mtime', true),
56
+ uname: ownerName(entry.uname ?? '', 'uname'),
57
+ gname: ownerName(entry.gname ?? '', 'gname'),
58
+ devmajor,
59
+ devminor,
60
+ }
61
+ }
62
+
63
+ // A copy in whole blocks; `length` may reach past `raw` to count a NUL.
64
+ function padded(raw, length = raw.length) {
65
+ const out = new Uint8Array(Math.ceil(length / BLOCK) * BLOCK)
66
+ out.set(raw)
67
+ return out
68
+ }
69
+
70
+ // GNU's start_private_header: 0644, owned by 0, no owner names.
71
+ const privateHeader = (name, size, mtime, typeflag, gnu) => encodeHeader({
72
+ gnu, name: encodeUtf8(name, 'header name').subarray(0, NAME_SIZE), prefix: EMPTY, linkname: EMPTY, uname: EMPTY, gname: EMPTY,
73
+ typeflag, mode: 0o644, uid: 0, gid: 0, size, mtime, devmajor: null, devminor: null,
74
+ })
75
+
76
+ // The size counts the NUL after the name.
77
+ const longLink = (raw, typeflag) => [privateHeader('././@LongLink', raw.length + 1, 0, typeflag, true), padded(raw, raw.length + 1)]
78
+
79
+ // Named `%d/PaxHeaders/%f` after the entry, dated with the entry's mtime
80
+ // clamped into the field.
81
+ function paxHeader(e, records) {
82
+ const body = encodePax(records)
83
+ const slash = e.name.lastIndexOf('/')
84
+ const label = slash === -1 ? `./PaxHeaders/${e.name}` : `${e.name.slice(0, slash)}/PaxHeaders/${e.name.slice(slash + 1)}`
85
+ return [privateHeader(label, body.length, Math.max(0, Math.min(e.mtime, octalMax(12))), PAX, false), padded(body)]
86
+ }
87
+
88
+ // GNU's split_long_name: the last slash within 155 bytes of prefix (a
89
+ // trailing slash does not count), leaving 1 to 100 bytes of name.
90
+ function splitName(raw, display) {
91
+ const { length } = raw
92
+ if (length > PREFIX_SIZE + NAME_SIZE + 1) throw new ArchiveError(`name ${quote(display)} is longer than 256 bytes, which ustar cannot hold`)
93
+ let limit = length
94
+ if (limit > PREFIX_SIZE + 1) limit = PREFIX_SIZE + 1
95
+ else if (raw[limit - 1] === SLASH) limit--
96
+ let i = limit - 1
97
+ while (i > 0 && raw[i] !== SLASH) i--
98
+ const rest = length - i - 1
99
+ if (i === 0 || rest > NAME_SIZE || rest === 0) throw new ArchiveError(`name ${quote(display)} cannot be split into ustar's prefix and name fields`)
100
+ return { prefix: raw.subarray(0, i), name: raw.subarray(i + 1) }
101
+ }
102
+
103
+ // The chunks of one entry: long-name blocks or a pax header, the header,
104
+ // the data and its padding. Pax records go in the order GNU stores them:
105
+ // linkpath, path, uid, gid, size, mtime, devmajor, devminor, uname, gname.
106
+ function encodeEntry(e, format) {
107
+ const gnu = format === 'gnu'
108
+ const pax = []
109
+ const chunks = []
110
+ const wire = wireName(e)
111
+ let name = encodeUtf8(wire, 'entry name')
112
+ let prefix = EMPTY
113
+ let link = encodeUtf8(e.linkname, `link target of ${quote(e.name)}`)
114
+ if (link.length > NAME_SIZE) {
115
+ if (gnu) chunks.push(...longLink(link, LONGLINK))
116
+ else if (format === 'pax') pax.push(['linkpath', e.linkname])
117
+ else throw new ArchiveError(`link target of ${quote(e.name)} is longer than 100 bytes, which ustar cannot hold`)
118
+ link = link.subarray(0, NAME_SIZE)
119
+ }
120
+ if (format === 'pax' && (name.length > NAME_SIZE || !isAscii(name))) pax.push(['path', wire])
121
+ if (name.length > NAME_SIZE) {
122
+ if (gnu) chunks.push(...longLink(name, LONGNAME))
123
+ else if (format === 'ustar') ({ prefix, name } = splitName(name, e.name))
124
+ if (name.length > NAME_SIZE) name = name.subarray(0, NAME_SIZE)
125
+ }
126
+ const number = (what, value, size) => {
127
+ if (gnu || fitsOctal(value, size)) return value
128
+ if (format === 'pax') {
129
+ pax.push([what, String(value)])
130
+ return 0
131
+ }
132
+ throw new ArchiveError(`${what} ${value} of ${quote(e.name)} does not fit the ustar format`)
133
+ }
134
+ // GNU writes the pax record only past 32 bytes and cuts a 32-byte name to
135
+ // 31 without one; that loss is the one place this does not follow it.
136
+ const owner = (what, text) => {
137
+ const raw = encodeUtf8(text, what)
138
+ if (raw.length < OWNER_SIZE && (format !== 'pax' || isAscii(raw))) return raw
139
+ if (format !== 'pax') throw new ArchiveError(`${what} of ${quote(e.name)} is longer than 31 bytes, which the ${format} format cannot hold`)
140
+ pax.push([what, text])
141
+ return raw.subarray(0, OWNER_SIZE - 1)
142
+ }
143
+ const device = isDevice(e.type)
144
+ const fields = {
145
+ gnu, name, prefix, linkname: link, typeflag: TYPEFLAG[e.type], mode: e.mode,
146
+ uid: number('uid', e.uid, 8),
147
+ gid: number('gid', e.gid, 8),
148
+ size: number('size', e.data.length, 12),
149
+ mtime: number('mtime', e.mtime, 12),
150
+ devmajor: device ? number('devmajor', e.devmajor, 8) : null,
151
+ devminor: device ? number('devminor', e.devminor, 8) : null,
152
+ uname: owner('uname', e.uname),
153
+ gname: owner('gname', e.gname),
154
+ }
155
+ if (pax.length) chunks.push(...paxHeader(e, pax))
156
+ chunks.push(encodeHeader(fields))
157
+ const rest = e.data.length % BLOCK
158
+ if (e.data.length) chunks.push(e.data)
159
+ if (rest) chunks.push(new Uint8Array(BLOCK - rest))
160
+ return chunks
161
+ }
162
+
163
+ // `keep` holds entries for a repeat to be compared with, which only the
164
+ // in-memory call can afford.
165
+ function packer({ format = 'gnu', blocking = 20 } = {}, keep = false) {
166
+ if (!FORMATS.has(format)) throw new ArchiveError(`format ${quote(String(format))} is not gnu, ustar or pax`)
167
+ if (!Number.isSafeInteger(blocking) || blocking < 1) throw new ArchiveError('blocking is not a positive integer')
168
+ const names = new Names(keep)
169
+ let total = 0
170
+ return {
171
+ add(entry) {
172
+ const e = normalize(entry)
173
+ const cleaned = { ...e, ...cleanNames(e.name, e.type, e.linkname) }
174
+ names.add(cleaned)
175
+ const chunks = encodeEntry(cleaned, format)
176
+ for (const chunk of chunks) total += chunk.length
177
+ return chunks
178
+ },
179
+ // Two zero blocks, then zeros to a multiple of the record size.
180
+ end() {
181
+ const record = blocking * BLOCK
182
+ const rest = (total + 2 * BLOCK) % record
183
+ return [new Uint8Array(2 * BLOCK + (rest ? record - rest : 0))]
184
+ },
185
+ }
186
+ }
187
+
188
+ export async function* packStream(entries, options) {
189
+ const p = packer(options)
190
+ for await (const entry of entries) yield* p.add(entry)
191
+ yield* p.end()
192
+ }
193
+
194
+ export function pack(entries, options) {
195
+ const p = packer(options, true)
196
+ const chunks = []
197
+ for (const entry of entries) chunks.push(...p.add(entry))
198
+ return concat([...chunks, ...p.end()])
199
+ }
package/src/tar/pax.js ADDED
@@ -0,0 +1,37 @@
1
+ // pax extended header records: `<length> <keyword>=<value>\n`, the length
2
+ // in decimal counting the whole line, its own digits included.
3
+
4
+ import { utf8fromString } from '@exodus/bytes/utf8.js'
5
+ import { concat } from '../bytes.js'
6
+ import { ArchiveError } from '../error.js'
7
+ import { decodeUtf8, hasUnsafe, quote } from '../text.js'
8
+
9
+ function record(keyword, value) {
10
+ const body = utf8fromString(` ${keyword}=${value}\n`)
11
+ // The total counts its own digits, which may be one more than the body's.
12
+ const digits = String(body.length).length
13
+ const total = body.length + digits + (String(body.length + digits).length > digits ? 1 : 0)
14
+ return concat([utf8fromString(String(total)), body])
15
+ }
16
+
17
+ export const encodePax = (records) => concat(records.map(([keyword, value]) => record(keyword, value)))
18
+
19
+ export function decodePax(bytes, at) {
20
+ const records = new Map()
21
+ for (let pos = 0; pos < bytes.length;) {
22
+ let i = pos
23
+ let length = 0
24
+ for (; i < bytes.length && bytes[i] >= 0x30 && bytes[i] <= 0x39; i++) length = length * 10 + (bytes[i] - 0x30)
25
+ if (i === pos || bytes[pos] === 0x30 || bytes[i] !== 0x20) throw new ArchiveError('a pax record does not begin with its length', at)
26
+ const end = pos + length
27
+ if (end > bytes.length || bytes[end - 1] !== 0x0a) throw new ArchiveError('a pax record is not as long as it says', at)
28
+ const equals = bytes.indexOf(0x3d, i + 1)
29
+ if (equals === -1 || equals >= end - 1) throw new ArchiveError('a pax record has no keyword=value', at)
30
+ const keyword = decodeUtf8(bytes.subarray(i + 1, equals), 'a pax record', at)
31
+ if (keyword === '' || hasUnsafe(keyword, false) || keyword.includes(' ')) throw new ArchiveError(`pax keyword ${quote(keyword)} is malformed`, at)
32
+ if (records.has(keyword)) throw new ArchiveError(`pax keyword ${keyword} repeats`, at)
33
+ records.set(keyword, decodeUtf8(bytes.subarray(equals + 1, end - 1), 'a pax record', at))
34
+ pos = end
35
+ }
36
+ return records
37
+ }
@@ -0,0 +1,248 @@
1
+ // A push parser: chunks go in, entries come out as each completes, so the
2
+ // in-memory call and the streams share one reader. Extended headers are
3
+ // the kinds GNU writes: pax `x` and `g`, and the `L`/`K` long-name blocks.
4
+ // An entry's data views the chunk it arrived in where one chunk held it
5
+ // whole, and is a copy otherwise.
6
+
7
+ import { EMPTY } from '../bytes.js'
8
+ import { isFile } from '../entry.js'
9
+ import { ArchiveError, located } from '../error.js'
10
+ import { BLOCK, decodeHeader, isDevice, isZeroBlock, untilNul } from './header.js'
11
+ import { Names, cleanNames } from '../names.js'
12
+ import { decodePax } from './pax.js'
13
+ import { decodeUtf8, hasUnsafe, quote } from '../text.js'
14
+
15
+ // NUL is the pre-POSIX regular file.
16
+ const TYPES = new Map([
17
+ [0x30, 'file'], [0, 'file'], [0x31, 'link'], [0x32, 'symlink'], [0x33, 'character-device'],
18
+ [0x34, 'block-device'], [0x35, 'directory'], [0x36, 'fifo'], [0x37, 'contiguous-file'],
19
+ ])
20
+ const EXTENDED = new Map([[0x78, 'pax'], [0x67, 'global'], [0x4c, 'longname'], [0x4b, 'longlink']])
21
+ const MAX_EXTENDED = 1 << 20
22
+
23
+ // A sparse file is stored as a map and a body that is not the file, so
24
+ // handing back that body under the file's name and size would be a lie.
25
+ // libarchive reads one from star's real size and Solaris' map of holes as
26
+ // it does from GNU's keys, so those are refused alike.
27
+ const SPARSE_KEYS = new Set(['SCHILY.realsize', 'SUN.holesdata'])
28
+
29
+ function sparse(keys, at) {
30
+ for (const key of keys) {
31
+ if (key.startsWith('GNU.sparse.') || SPARSE_KEYS.has(key)) throw new ArchiveError('sparse entries are not supported', at)
32
+ }
33
+ }
34
+
35
+ function paxNumber(value, what, at) {
36
+ if (!/^(?:0|[1-9][0-9]*)$/u.test(value) || !Number.isSafeInteger(Number(value))) throw new ArchiveError(`pax ${what}=${quote(value)} is not a whole number this package can hold`, at)
37
+ return Number(value)
38
+ }
39
+
40
+ // Whole seconds, a fraction floored as GNU does for a format without one.
41
+ // Read from the digits, not through a double: near today a double steps by
42
+ // a quarter of a microsecond, so .9999999 of a second would round up to the
43
+ // next one before any floor saw it. Flooring moves a negative time with any
44
+ // fraction a second earlier, and nothing else.
45
+ function paxTime(value, what, at) {
46
+ const match = /^(-?)([0-9]+)(?:\.([0-9]+))?$/u.exec(value)
47
+ if (!match) throw new ArchiveError(`pax ${what}=${quote(value)} is not a time`, at)
48
+ const [, sign, whole, fraction = ''] = match
49
+ const seconds = Number(sign + whole) - (sign && /[1-9]/u.test(fraction) ? 1 : 0)
50
+ if (!Number.isSafeInteger(seconds)) throw new ArchiveError(`pax ${what}=${quote(value)} is out of range`, at)
51
+ return seconds
52
+ }
53
+
54
+ // The extended headers waiting on the entry they describe: none, to start
55
+ // with and once each entry has taken them.
56
+ const nonePending = () => ({ pax: null, longname: null, longlink: null })
57
+
58
+ class Unpacker {
59
+ #chunks = []
60
+ #offset = 0
61
+ #buffered = 0
62
+ #position = 0
63
+ #names
64
+ #pending = nonePending()
65
+ #global = null
66
+ // The header whose body is due: { extended, size, at, entry }.
67
+ #awaiting = null
68
+ #zeros = 0
69
+ #done = false
70
+
71
+ // `keep` holds entries for a repeat to be compared with, which only the
72
+ // in-memory call can afford.
73
+ constructor(keep = false) {
74
+ this.#names = new Names(keep)
75
+ }
76
+
77
+ push(chunk) {
78
+ if (!(chunk instanceof Uint8Array)) throw new ArchiveError('a chunk is not a Uint8Array')
79
+ if (this.#done) {
80
+ this.#trailing(chunk, this.#position)
81
+ this.#position += chunk.length
82
+ return []
83
+ }
84
+ if (chunk.length) {
85
+ this.#chunks.push(chunk)
86
+ this.#buffered += chunk.length
87
+ }
88
+ const out = []
89
+ let more = true
90
+ while (more && !this.#done) more = this.#awaiting === null ? this.#header() : this.#body(out)
91
+ return out
92
+ }
93
+
94
+ end() {
95
+ if (this.#done) return
96
+ if (this.#position === 0 && this.#buffered === 0) throw new ArchiveError('the archive is empty')
97
+ if (this.#awaiting === null && this.#buffered === 0) throw new ArchiveError(this.#zeros ? 'the archive ends with a lone zero block' : 'the archive has no end marker', this.#position)
98
+ throw new ArchiveError('the archive is truncated', this.#position)
99
+ }
100
+
101
+ // The next `size` bytes, or null until they have all arrived: a view
102
+ // when one chunk holds them, else a copy of just that span out of the
103
+ // chunks it crosses, however much more those chunks hold.
104
+ #take(size) {
105
+ if (this.#buffered < size) return null
106
+ if (size === 0) return EMPTY
107
+ let out
108
+ if (this.#offset + size <= this.#chunks[0].length) {
109
+ out = this.#chunks[0].subarray(this.#offset, this.#offset + size)
110
+ this.#offset += size
111
+ } else {
112
+ out = new Uint8Array(size)
113
+ let i = 0
114
+ for (let at = 0, from = this.#offset; at < size; i++, from = 0) {
115
+ const piece = this.#chunks[i].subarray(from, from + size - at)
116
+ out.set(piece, at)
117
+ at += piece.length
118
+ this.#offset = from + piece.length
119
+ }
120
+ this.#chunks = this.#chunks.slice(i - 1)
121
+ }
122
+ if (this.#offset === this.#chunks[0].length) {
123
+ this.#chunks.shift()
124
+ this.#offset = 0
125
+ }
126
+ this.#buffered -= size
127
+ this.#position += size
128
+ return out
129
+ }
130
+
131
+ #trailing(bytes, at) {
132
+ if (!isZeroBlock(bytes)) throw new ArchiveError('data after the end of the archive', at)
133
+ }
134
+
135
+ // False when more bytes are needed.
136
+ #header() {
137
+ const block = this.#take(BLOCK)
138
+ if (block === null) return false
139
+ const at = this.#position - BLOCK
140
+ if (isZeroBlock(block)) {
141
+ if (Object.values(this.#pending).some((value) => value !== null)) throw new ArchiveError('an extended header is not followed by an entry', at)
142
+ if (++this.#zeros === 2) {
143
+ this.#done = true
144
+ const after = this.#position
145
+ this.#trailing(this.#take(this.#buffered), after)
146
+ }
147
+ return true
148
+ }
149
+ if (this.#zeros) throw new ArchiveError('a lone zero block where a header should be', at)
150
+ const header = decodeHeader(block, at)
151
+ const extended = EXTENDED.get(header.typeflag)
152
+ if (extended === undefined) {
153
+ this.#awaiting = { extended: null, at, ...this.#resolve(header, at) }
154
+ } else {
155
+ if (header.size > MAX_EXTENDED) throw new ArchiveError(`a ${extended} header of ${header.size} bytes is longer than any tar writes`, at)
156
+ this.#awaiting = { extended, size: header.size, at, entry: null }
157
+ }
158
+ return true
159
+ }
160
+
161
+ #body(out) {
162
+ const { extended, size, at, entry } = this.#awaiting
163
+ const whole = Math.ceil(size / BLOCK) * BLOCK
164
+ const body = this.#take(whole)
165
+ if (body === null) return false
166
+ if (!isZeroBlock(body.subarray(size))) throw new ArchiveError('the padding after an entry is not zero', at)
167
+ this.#awaiting = null
168
+ const raw = body.subarray(0, size)
169
+ if (extended === null) {
170
+ entry.data = raw
171
+ located(() => this.#names.add(entry), at)
172
+ out.push(entry)
173
+ } else if (extended === 'global') {
174
+ this.#global = decodePax(raw, at)
175
+ for (const key of ['path', 'linkpath', 'size']) {
176
+ if (this.#global.has(key)) throw new ArchiveError(`a global header sets ${key}`, at)
177
+ }
178
+ // Once, here: a global header stands until another replaces it, and
179
+ // re-reading its keys under every entry is work an archive can ask for.
180
+ sparse(this.#global.keys(), at)
181
+ } else {
182
+ if (this.#pending[extended] !== null) throw new ArchiveError(`two ${extended} headers ahead of one entry`, at)
183
+ this.#pending[extended] = extended === 'pax' ? decodePax(raw, at) : decodeUtf8(untilNul(raw), `a ${extended} header`, at)
184
+ }
185
+ return true
186
+ }
187
+
188
+ // The entry a header stands for, with the extended headers ahead of it
189
+ // applied: a pax record wins over the field it stands in for.
190
+ #resolve(header, at) {
191
+ const type = TYPES.get(header.typeflag)
192
+ if (type === undefined) throw new ArchiveError(`entry type ${quote(String.fromCodePoint(header.typeflag))} is not one this package reads`, at)
193
+ const { pax, longname, longlink } = this.#pending
194
+ this.#pending = nonePending()
195
+ const record = (key) => pax?.get(key) ?? this.#global?.get(key)
196
+ if (pax !== null) sparse(pax.keys(), at)
197
+ if (longname !== null && record('path') !== undefined) throw new ArchiveError('both a long name header and a pax path name one entry', at)
198
+ if (longlink !== null && record('linkpath') !== undefined) throw new ArchiveError('both a long link header and a pax linkpath name one entry', at)
199
+ const rawName = longname ?? record('path') ?? this.#headerName(header, at)
200
+ const rawTarget = longlink ?? record('linkpath') ?? decodeUtf8(header.linkname, 'link target', at)
201
+ const { name, linkname } = located(() => cleanNames(rawName, type, rawTarget), at)
202
+ const number = (key, parse = paxNumber) => {
203
+ const value = record(key)
204
+ return value === undefined ? header[key] : parse(value, key, at)
205
+ }
206
+ const size = number('size')
207
+ if (size !== 0 && !isFile(type)) throw new ArchiveError(`a ${type} entry has a size`, at)
208
+ if (linkname !== '' && type !== 'link' && type !== 'symlink') throw new ArchiveError(`a ${type} entry has a link target`, at)
209
+ const owner = (key) => {
210
+ const value = record(key) ?? decodeUtf8(header[key], key, at)
211
+ if (hasUnsafe(value, false)) throw new ArchiveError(`${key} ${quote(value)} holds a control or formatting character`, at)
212
+ return value
213
+ }
214
+ const entry = {
215
+ name,
216
+ type,
217
+ mode: header.mode & 0o7777,
218
+ uid: number('uid'),
219
+ gid: number('gid'),
220
+ mtime: number('mtime', paxTime),
221
+ uname: owner('uname'),
222
+ gname: owner('gname'),
223
+ linkname,
224
+ devmajor: isDevice(type) ? number('devmajor') : 0,
225
+ devminor: isDevice(type) ? number('devminor') : 0,
226
+ data: EMPTY,
227
+ }
228
+ return { entry, size }
229
+ }
230
+
231
+ #headerName(header, at) {
232
+ const name = decodeUtf8(header.name, 'entry name', at)
233
+ return header.prefix.length ? `${decodeUtf8(header.prefix, 'name prefix', at)}/${name}` : name
234
+ }
235
+ }
236
+
237
+ export function unpack(bytes) {
238
+ const unpacker = new Unpacker(true)
239
+ const entries = unpacker.push(bytes)
240
+ unpacker.end()
241
+ return entries
242
+ }
243
+
244
+ export async function* unpackStream(chunks) {
245
+ const unpacker = new Unpacker()
246
+ for await (const chunk of chunks) yield* unpacker.push(chunk)
247
+ unpacker.end()
248
+ }
package/src/text.js ADDED
@@ -0,0 +1,52 @@
1
+ import { utf8fromString, utf8toString } from '@exodus/bytes/utf8.js'
2
+ import { ArchiveError } from './error.js'
3
+
4
+ // Escaped, so a name in a message cannot carry a terminal sequence, and cut
5
+ // short of a surrogate pair, so a long one cannot flood it.
6
+ export function quote(text) {
7
+ if (text.length <= 200) return JSON.stringify(text)
8
+ return JSON.stringify(`${text.slice(0, text.codePointAt(199) > 0xffff ? 199 : 200)}…`)
9
+ }
10
+
11
+ // A C0, DEL or C1 control (Cc is those three and nothing else); a line or
12
+ // paragraph separator (Zl, Zp: one each); and every bidirectional control
13
+ // Unicode names — embeddings, overrides and isolates, and the three marks
14
+ // that shift neutral characters about them unseen — since each breaks or
15
+ // reorders a name as shown. A backslash too, if asked.
16
+ const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}]/u
17
+ const UNSAFE_OR_BACKSLASH = /[\p{Cc}\p{Zl}\p{Zp}\p{Bidi_Control}\\]/u
18
+
19
+ export const hasUnsafe = (text, backslash) => (backslash ? UNSAFE_OR_BACKSLASH : UNSAFE).test(text)
20
+
21
+ // Every string taken from a caller goes through here first: a lone
22
+ // surrogate has no UTF-8, and so no length or bytes for any later check
23
+ // to look at, and JSON.stringify would only hide it.
24
+ export function checkString(value, what) {
25
+ if (typeof value !== 'string') throw new ArchiveError(`${what} is not a string`)
26
+ if (!value.isWellFormed()) throw new ArchiveError(`${what} is not well-formed Unicode`)
27
+ }
28
+
29
+ export function utf8Length(text) {
30
+ let length = 0
31
+ for (const char of text) {
32
+ const code = char.codePointAt(0)
33
+ length += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
34
+ }
35
+ return length
36
+ }
37
+
38
+ export function encodeUtf8(text, what) {
39
+ try {
40
+ return utf8fromString(text)
41
+ } catch {
42
+ throw new ArchiveError(`${what} is not well-formed Unicode`)
43
+ }
44
+ }
45
+
46
+ export function decodeUtf8(raw, what, at) {
47
+ try {
48
+ return utf8toString(raw)
49
+ } catch {
50
+ throw new ArchiveError(`${what} is not valid UTF-8`, at)
51
+ }
52
+ }
@@ -0,0 +1,80 @@
1
+ // What the zip half shares: the record signatures and mode bits, little-
2
+ // endian fields, DOS time, and raw deflate under zip's own words.
3
+
4
+ import { compress, decompressInto } from '../compression.js'
5
+ import { ArchiveError } from '../error.js'
6
+
7
+ export const LOCAL = 0x04034b50
8
+ export const CENTRAL = 0x02014b50
9
+ export const END = 0x06054b50
10
+
11
+ // The Unix file type bits, which the external attributes carry.
12
+ export const TYPE_MASK = 0o170000
13
+ export const TYPE_BITS = { file: 0o100000, directory: 0o40000, symlink: 0o120000 }
14
+
15
+ export const view = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
16
+
17
+ // A record laid out as [width, value] pairs, widths 1, 2 or 4. A value
18
+ // that does not fit its width is a bug upstream, not a field to truncate.
19
+ export function record(fields) {
20
+ const out = new Uint8Array(fields.reduce((total, [width]) => total + width, 0))
21
+ const data = view(out)
22
+ let at = 0
23
+ for (const [width, value] of fields) {
24
+ if (!Number.isInteger(value) || value < 0 || value >= 2 ** (8 * width)) throw new RangeError(`${value} does not fit ${width} bytes`)
25
+ if (width === 1) data.setUint8(at, value)
26
+ else if (width === 2) data.setUint16(at, value, true)
27
+ else data.setUint32(at, value, true)
28
+ at += width
29
+ }
30
+ return out
31
+ }
32
+
33
+ export const deflate = (bytes) => compress(bytes, 'deflate-raw')
34
+
35
+ // Deflate spends at least two bits on a match, and a match is at most 258
36
+ // bytes, so no data inflates to more than 1032 times its own size: zlib's
37
+ // best, on zeros, is 1028.8.
38
+ const MAX_RATIO = 1032
39
+
40
+ // Exactly the declared size, made in place, with output past it refused
41
+ // where it is. Room for all of it is made first, so a size the data could
42
+ // not inflate to is refused before that: past it, a few bytes of archive
43
+ // would have room made for gigabytes no valid one of their size holds.
44
+ export async function inflate(bytes, size, at) {
45
+ if (size > bytes.length * MAX_RATIO) throw new ArchiveError('an entry declares more than its data can inflate to', at)
46
+ let out
47
+ try {
48
+ out = await decompressInto(bytes, 'deflate-raw', new Uint8Array(size))
49
+ } catch (error) {
50
+ throw new ArchiveError(error.limited ? 'an entry inflates to more than its declared size' : 'an entry does not inflate', at)
51
+ }
52
+ if (out.length !== size) throw new ArchiveError('an entry inflates to less than its declared size', at)
53
+ return out
54
+ }
55
+
56
+ // DOS time is two seconds and a year from 1980, in the maker's local time —
57
+ // read and written here as UTC.
58
+ function dos(seconds) {
59
+ const date = new Date(seconds * 1000)
60
+ const year = date.getUTCFullYear()
61
+ if (year < 1980 || year > 2107) return null
62
+ return {
63
+ time: (date.getUTCHours() << 11) | (date.getUTCMinutes() << 5) | (date.getUTCSeconds() >> 1),
64
+ date: ((year - 1980) << 9) | ((date.getUTCMonth() + 1) << 5) | date.getUTCDate(),
65
+ }
66
+ }
67
+
68
+ export function toDos(mtime) {
69
+ const fields = dos(mtime)
70
+ if (fields === null) throw new ArchiveError(`mtime ${mtime} is outside DOS time, 1980 to 2107`)
71
+ return fields
72
+ }
73
+
74
+ // Fields that do not come back as themselves named no date at all.
75
+ export function fromDos(date, time, at) {
76
+ const seconds = Date.UTC(1980 + (date >> 9), ((date >> 5) & 15) - 1, date & 31, time >> 11, (time >> 5) & 63, (time & 31) * 2) / 1000
77
+ const fields = dos(seconds)
78
+ if (fields === null || fields.time !== time || fields.date !== date) throw new ArchiveError('an entry has an invalid DOS time', at)
79
+ return seconds
80
+ }