@preventive/archive 1.4.0 → 1.4.1

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.
package/src/tar/header.js CHANGED
@@ -1,8 +1,3 @@
1
- // The 512-byte ustar header block, as GNU tar 1.35 writes and reads it.
2
- // String fields come back as bytes cut at the first NUL, not text: GNU cuts
3
- // a long name at 100 bytes wherever the real name went, and that is not
4
- // always a whole character, so only the field that counts gets decoded.
5
-
6
1
  import { EMPTY } from '../bytes.js'
7
2
  import { ArchiveError } from '../error.js'
8
3
 
@@ -10,8 +5,6 @@ export const BLOCK = 512
10
5
 
11
6
  export const isDevice = (type) => type === 'character-device' || type === 'block-device'
12
7
 
13
- // Each entry type's type flag, and each extended header's: those GNU
14
- // writes, under the names unpack reads them by.
15
8
  export const TYPEFLAGS = {
16
9
  file: 0x30,
17
10
  hardlink: 0x31,
@@ -26,11 +19,9 @@ export const EXTENDED_TYPEFLAGS = { pax: 0x78, global: 0x67, longname: 0x4c, lon
26
19
 
27
20
  export const NAME_SIZE = 100
28
21
  export const PREFIX_SIZE = 155
29
- // 32 bytes, and GNU always ends them with a NUL, so 31 is the most.
30
- export const OWNER_SIZE = 32
22
+ export const OWNER_SIZE = 32 // GNU always ends one with a NUL, so 31 bytes at most
31
23
 
32
24
  const NAME = 0
33
- // The numbers from mode to mtime, [key, offset, size], in the block's order.
34
25
  const NUMBERS = [['mode', 100, 8], ['uid', 108, 8], ['gid', 116, 8], ['size', 124, 12], ['mtime', 136, 12]]
35
26
  const CHKSUM = 148
36
27
  const TYPEFLAG = 156
@@ -41,29 +32,22 @@ const GNAME = 297
41
32
  const DEVMAJOR = 329
42
33
  const DEVMINOR = 337
43
34
  const PREFIX = 345
44
- // Under the gnu magic: the old GNU sparse map, its isextended flag and the
45
- // file's real size. libarchive reads them whatever the type flag says --
46
- // taking the real size as the file's, and the map and any extension blocks
47
- // after the header as its layout -- where GNU tar and the rest read them for
48
- // a sparse entry alone.
35
+ // Under the gnu magic, the old sparse map and real size: libarchive reads them whatever the type flag
49
36
  const OLD_SPARSE = 386
50
37
  const OLD_SPARSE_END = 495
51
38
 
52
- const USTAR_MAGIC = 'ustar\u000000' // "ustar", NUL, "00": ustar and pax
39
+ const USTAR_MAGIC = 'ustar\u000000' // ustar and pax
53
40
  const GNU_MAGIC = 'ustar \0'
54
41
 
55
42
  const latin1 = (text) => Uint8Array.from(text, (c) => c.codePointAt(0))
56
43
  const ascii = (raw) => String.fromCodePoint(...raw)
57
- // Throws (RangeError) rather than overwriting the next field.
58
- const put = (block, offset, size, bytes) => block.subarray(offset, offset + size).set(bytes)
44
+ const put = (block, offset, size, bytes) => block.subarray(offset, offset + size).set(bytes) // throws rather than overflow
59
45
  const field = (block, offset, size) => untilNul(block.subarray(offset, offset + size))
60
46
 
61
47
  export const octalMax = (size) => 8 ** (size - 1) - 1
62
48
  export const fitsOctal = (value, size) => value >= 0 && value <= octalMax(size)
63
49
 
64
- // A number is size-1 octal digits and a NUL. GNU's format falls back to
65
- // 0x80 (0xff when negative) and the value in base 256, big-endian, two's
66
- // complement, over the rest of the field.
50
+ // Octal digits and a NUL, or for gnu, 0x80 (0xff if negative) and two's complement base 256 after it
67
51
  export function writeNumber(block, offset, size, value, gnu) {
68
52
  if (fitsOctal(value, size)) {
69
53
  put(block, offset, size, latin1(value.toString(8).padStart(size - 1, '0')))
@@ -78,12 +62,8 @@ export function writeNumber(block, offset, size, value, gnu) {
78
62
  }
79
63
  }
80
64
 
81
- // Older tars wrote leading spaces, and either spaces or NULs after; a field
82
- // left blank (npm's packer wrote uid and gid so for years) is 0, as GNU tar,
83
- // libarchive and the rest read it. A NUL ends the number wherever it sits, so
84
- // a field that opens with one is 0 however it goes on -- GNU stops there, and
85
- // reading the digits past it instead would give a size, and so an archive,
86
- // that only this package sees. Only a time may be negative.
65
+ // Spaces around the digits and a blank field (0) are read as GNU tar and libarchive do. A NUL ends
66
+ // the number wherever it sits, as in GNU tar, which reading past it would disagree with.
87
67
  export function readNumber(block, offset, size, what, at, signed = false) {
88
68
  const first = block[offset]
89
69
  if (first === 0x80 || first === 0xff) {
@@ -91,7 +71,7 @@ export function readNumber(block, offset, size, what, at, signed = false) {
91
71
  for (let i = offset + 1; i < offset + size; i++) v = (v << 8n) | BigInt(block[i])
92
72
  if (first === 0xff) v = BigInt.asIntN((size - 1) * 8, v)
93
73
  if (v < 0n && !signed) throw new ArchiveError(`the ${what} field is negative`, at)
94
- if (v > BigInt(Number.MAX_SAFE_INTEGER) || v < -BigInt(Number.MAX_SAFE_INTEGER)) throw new ArchiveError(`the ${what} field is too large`, at)
74
+ if (!Number.isSafeInteger(Number(v))) throw new ArchiveError(`the ${what} field is too large`, at)
95
75
  return Number(v)
96
76
  }
97
77
  const match = /^ *([0-7]*) *$/u.exec(ascii(field(block, offset, size)))
@@ -104,7 +84,7 @@ export function untilNul(raw) {
104
84
  return end === -1 ? raw : raw.subarray(0, end)
105
85
  }
106
86
 
107
- // Every byte, with the checksum field itself counted as spaces.
87
+ // The checksum field itself counts as spaces
108
88
  function checksum(block) {
109
89
  let sum = 8 * 0x20
110
90
  for (let i = 0; i < CHKSUM; i++) sum += block[i]
@@ -114,9 +94,7 @@ function checksum(block) {
114
94
 
115
95
  export const isZeroBlock = (block) => block.every((byte) => byte === 0)
116
96
 
117
- // String fields are bytes already cut to size; numbers already fit the
118
- // format. `devmajor` and `devminor` are null except for a device, since
119
- // GNU leaves those fields NUL for everything else.
97
+ // Strings are bytes already cut to size, numbers already fit; device numbers are null but for a device
120
98
  export function encodeHeader(f) {
121
99
  const block = new Uint8Array(BLOCK)
122
100
  put(block, NAME, NAME_SIZE, f.name)
@@ -129,15 +107,13 @@ export function encodeHeader(f) {
129
107
  if (f.devmajor !== null) writeNumber(block, DEVMAJOR, 8, f.devmajor, f.gnu)
130
108
  if (f.devminor !== null) writeNumber(block, DEVMINOR, 8, f.devminor, f.gnu)
131
109
  put(block, PREFIX, PREFIX_SIZE, f.prefix)
132
- // The one field written as digits, NUL, space.
133
110
  put(block, CHKSUM, 8, latin1(`${checksum(block).toString(8).padStart(6, '0')}\0 `))
134
111
  return block
135
112
  }
136
113
 
137
- // Whether a numeric field holds octal digits, as POSIX writes it, rather
138
- // than nothing or GNU's base 256, both of which readNumber reads.
139
114
  const isOctal = (block, offset, size) => /^ *[0-7]+ *$/u.test(ascii(field(block, offset, size)))
140
115
 
116
+ // Strings come back as bytes: GNU cuts a long name at 100 bytes, not always on a whole character
141
117
  export function decodeHeader(block, at) {
142
118
  if (checksum(block) !== readNumber(block, CHKSUM, 8, 'checksum', at)) throw new ArchiveError('header checksum does not match', at)
143
119
  const magic = ascii(block.subarray(MAGIC, MAGIC + 8))
@@ -146,19 +122,18 @@ export function decodeHeader(block, at) {
146
122
  if (gnu && !isZeroBlock(block.subarray(OLD_SPARSE, OLD_SPARSE_END))) throw new ArchiveError('header carries an old GNU sparse map or real size', at)
147
123
  const typeflag = block[TYPEFLAG]
148
124
  const device = typeflag === TYPEFLAGS['character-device'] || typeflag === TYPEFLAGS['block-device']
125
+ const numbers = [['checksum', CHKSUM, 8], ...NUMBERS, ...(device ? [['devmajor', DEVMAJOR, 8], ['devminor', DEVMINOR, 8]] : [])]
149
126
  return {
150
127
  gnu,
151
128
  typeflag,
152
129
  name: field(block, NAME, NAME_SIZE),
153
- // Under the gnu magic those bytes belong to the old GNU header instead.
154
- prefix: gnu ? EMPTY : field(block, PREFIX, PREFIX_SIZE),
130
+ prefix: gnu ? EMPTY : field(block, PREFIX, PREFIX_SIZE), // gnu has its own fields there
155
131
  linkname: field(block, LINKNAME, NAME_SIZE),
156
132
  uname: field(block, UNAME, OWNER_SIZE),
157
133
  gname: field(block, GNAME, OWNER_SIZE),
158
134
  ...Object.fromEntries(NUMBERS.map(([key, offset, size]) => [key, readNumber(block, offset, size, key, at, key === 'mtime')])),
159
135
  devmajor: device ? readNumber(block, DEVMAJOR, 8, 'devmajor', at) : 0,
160
136
  devminor: device ? readNumber(block, DEVMINOR, 8, 'devminor', at) : 0,
161
- octal: [['checksum', CHKSUM, 8], ...NUMBERS, ...device ? [['devmajor', DEVMAJOR, 8], ['devminor', DEVMINOR, 8]] : []]
162
- .every(([, offset, size]) => isOctal(block, offset, size)),
137
+ octal: numbers.every(([, offset, size]) => isOctal(block, offset, size)),
163
138
  }
164
139
  }
package/src/tar/pack.js CHANGED
@@ -1,15 +1,14 @@
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
-
1
+ import { utf8fromString } from '@exodus/bytes/utf8.js'
6
2
  import { EMPTY, concat, isAscii } from '../bytes.js'
7
3
  import { DEFAULT_MODE, checkEntry, wireName } from '../entry.js'
8
4
  import { ArchiveError } from '../error.js'
5
+ import { Names, cleanNames } from '../names.js'
6
+ import { checkString, hasUnsafe, quote } from '../text.js'
9
7
  import { BLOCK, EXTENDED_TYPEFLAGS, NAME_SIZE, OWNER_SIZE, PREFIX_SIZE, TYPEFLAGS, encodeHeader, fitsOctal, isDevice, octalMax } from './header.js'
10
- import { Names, cleanNames, levelsAbove } from '../names.js'
11
8
  import { encodePax } from './pax.js'
12
- import { checkString, encodeUtf8, hasUnsafe, quote } from '../text.js'
9
+
10
+ // What GNU tar 1.35 writes with `--owner=0 --group=0 --numeric-owner` (and for pax,
11
+ // `--pax-option=delete=atime,delete=ctime`), but refusing what GNU would cut or substitute
13
12
 
14
13
  const FORMATS = new Set(['gnu', 'ustar', 'pax'])
15
14
  const SLASH = 0x2f
@@ -25,9 +24,9 @@ function ownerName(value, what) {
25
24
  return value
26
25
  }
27
26
 
28
- function normalize(entry) {
27
+ function normalize(entry, above) {
29
28
  const checked = checkEntry(entry, TYPEFLAGS)
30
- const { name, type } = checked
29
+ const { name, type, linkname } = checked
31
30
  const devmajor = integer(entry.devmajor ?? 0, 'devmajor')
32
31
  const devminor = integer(entry.devminor ?? 0, 'devminor')
33
32
  if ((devmajor !== 0 || devminor !== 0) && !isDevice(type)) throw new ArchiveError(`a ${type} cannot have device numbers (${quote(name)})`)
@@ -43,27 +42,26 @@ function normalize(entry) {
43
42
  gname: ownerName(entry.gname ?? '', 'gname'),
44
43
  devmajor,
45
44
  devminor,
45
+ ...cleanNames(name, type, linkname, above),
46
46
  }
47
47
  }
48
48
 
49
- // A copy in whole blocks; `length` may reach past `raw` to count a NUL.
49
+ // A copy in whole blocks; `length` may reach past `raw` to count a NUL
50
50
  function padded(raw, length = raw.length) {
51
51
  const out = new Uint8Array(Math.ceil(length / BLOCK) * BLOCK)
52
52
  out.set(raw)
53
53
  return out
54
54
  }
55
55
 
56
- // GNU's start_private_header: 0644, owned by 0, no owner names.
56
+ // GNU's start_private_header
57
57
  const privateHeader = (name, size, mtime, typeflag, gnu) => encodeHeader({
58
- gnu, name: encodeUtf8(name, 'header name').subarray(0, NAME_SIZE), prefix: EMPTY, linkname: EMPTY, uname: EMPTY, gname: EMPTY,
58
+ gnu, name: utf8fromString(name).subarray(0, NAME_SIZE), prefix: EMPTY, linkname: EMPTY, uname: EMPTY, gname: EMPTY,
59
59
  typeflag, mode: 0o644, uid: 0, gid: 0, size, mtime, devmajor: null, devminor: null,
60
60
  })
61
61
 
62
- // The size counts the NUL after the name.
63
62
  const longLink = (raw, typeflag) => [privateHeader('././@LongLink', raw.length + 1, 0, typeflag, true), padded(raw, raw.length + 1)]
64
63
 
65
- // Named `%d/PaxHeaders/%f` after the entry, dated with the entry's mtime
66
- // clamped into the field.
64
+ // Named `%d/PaxHeaders/%f` after the entry, its mtime clamped into the field
67
65
  function paxHeader(e, records) {
68
66
  const body = encodePax(records)
69
67
  const slash = e.name.lastIndexOf('/')
@@ -71,32 +69,27 @@ function paxHeader(e, records) {
71
69
  return [privateHeader(label, body.length, Math.max(0, Math.min(e.mtime, octalMax(12))), EXTENDED_TYPEFLAGS.pax, false), padded(body)]
72
70
  }
73
71
 
74
- // GNU's split_long_name: the last slash within 155 bytes of prefix (a
75
- // trailing slash does not count), leaving 1 to 100 bytes of name.
72
+ // GNU's split_long_name: at the last slash within 155 bytes, a trailing one aside, leaving 1 to 100 bytes of name
76
73
  function splitName(raw, display) {
77
74
  const { length } = raw
78
75
  if (length > PREFIX_SIZE + NAME_SIZE + 1) throw new ArchiveError(`name ${quote(display)} is longer than 256 bytes, which ustar cannot hold`)
79
- let limit = length
80
- if (limit > PREFIX_SIZE + 1) limit = PREFIX_SIZE + 1
81
- else if (raw[limit - 1] === SLASH) limit--
82
- let i = limit - 1
83
- while (i > 0 && raw[i] !== SLASH) i--
76
+ const limit = length > PREFIX_SIZE + 1 ? PREFIX_SIZE + 1 : raw[length - 1] === SLASH ? length - 1 : length
77
+ const i = raw.lastIndexOf(SLASH, limit - 1)
84
78
  const rest = length - i - 1
85
- if (i === 0 || rest > NAME_SIZE || rest === 0) throw new ArchiveError(`name ${quote(display)} cannot be split into ustar's prefix and name fields`)
79
+ if (i <= 0 || rest > NAME_SIZE || rest === 0) throw new ArchiveError(`name ${quote(display)} cannot be split into ustar's prefix and name fields`)
86
80
  return { prefix: raw.subarray(0, i), name: raw.subarray(i + 1) }
87
81
  }
88
82
 
89
- // The chunks of one entry: long-name blocks or a pax header, the header,
90
- // the data and its padding. Pax records go in the order GNU stores them:
91
- // linkpath, path, uid, gid, size, mtime, devmajor, devminor, uname, gname.
83
+ // Long-name blocks or a pax header, the header, the data and its padding.
84
+ // Pax records go in GNU's order: linkpath, path, uid, gid, size, mtime, devmajor, devminor, uname, gname.
92
85
  function encodeEntry(e, format) {
93
86
  const gnu = format === 'gnu'
94
87
  const pax = []
95
88
  const chunks = []
96
89
  const wire = wireName(e)
97
- let name = encodeUtf8(wire, 'entry name')
90
+ let name = utf8fromString(wire)
98
91
  let prefix = EMPTY
99
- let link = encodeUtf8(e.linkname, `link target of ${quote(e.name)}`)
92
+ let link = utf8fromString(e.linkname)
100
93
  if (link.length > NAME_SIZE) {
101
94
  if (gnu) chunks.push(...longLink(link, EXTENDED_TYPEFLAGS.longlink))
102
95
  else if (format === 'pax') pax.push(['linkpath', e.linkname])
@@ -111,16 +104,13 @@ function encodeEntry(e, format) {
111
104
  }
112
105
  const number = (what, value, size) => {
113
106
  if (gnu || fitsOctal(value, size)) return value
114
- if (format === 'pax') {
115
- pax.push([what, String(value)])
116
- return 0
117
- }
118
- throw new ArchiveError(`${what} ${value} of ${quote(e.name)} does not fit the ustar format`)
107
+ if (format !== 'pax') throw new ArchiveError(`${what} ${value} of ${quote(e.name)} does not fit the ustar format`)
108
+ pax.push([what, String(value)])
109
+ return 0
119
110
  }
120
- // GNU writes the pax record only past 32 bytes and cuts a 32-byte name to
121
- // 31 without one; that loss is the one place this does not follow it.
111
+ // GNU cuts a 32-byte owner name to 31 with no pax record; this refuses instead
122
112
  const owner = (what, text) => {
123
- const raw = encodeUtf8(text, what)
113
+ const raw = utf8fromString(text)
124
114
  if (raw.length < OWNER_SIZE && (format !== 'pax' || isAscii(raw))) return raw
125
115
  if (format !== 'pax') throw new ArchiveError(`${what} of ${quote(e.name)} is longer than 31 bytes, which the ${format} format cannot hold`)
126
116
  pax.push([what, text])
@@ -140,33 +130,28 @@ function encodeEntry(e, format) {
140
130
  }
141
131
  if (pax.length) chunks.push(...paxHeader(e, pax))
142
132
  chunks.push(encodeHeader(fields))
143
- const rest = e.data.length % BLOCK
144
133
  if (e.data.length) chunks.push(e.data)
145
- if (rest) chunks.push(new Uint8Array(BLOCK - rest))
134
+ if (e.data.length % BLOCK) chunks.push(new Uint8Array(BLOCK - (e.data.length % BLOCK)))
146
135
  return chunks
147
136
  }
148
137
 
149
- // `keep` holds entries for a repeat to be compared with, which only the
150
- // in-memory call can afford.
151
138
  function packer({ format = 'gnu', blocking = 20, symlinksAbove } = {}, keep = false) {
152
139
  if (!FORMATS.has(format)) throw new ArchiveError(`format ${quote(String(format))} is not gnu, ustar or pax`)
153
140
  if (!Number.isSafeInteger(blocking) || blocking < 1) throw new ArchiveError('blocking is not a positive integer')
154
- const names = new Names(keep, levelsAbove(symlinksAbove))
141
+ const names = new Names(keep, symlinksAbove)
155
142
  let total = 0
156
143
  return {
157
144
  add(entry) {
158
- const e = normalize(entry)
159
- const cleaned = { ...e, ...cleanNames(e.name, e.type, e.linkname, names.above) }
160
- names.add(cleaned)
161
- const chunks = encodeEntry(cleaned, format)
145
+ const e = normalize(entry, names.above)
146
+ names.add(e)
147
+ const chunks = encodeEntry(e, format)
162
148
  for (const chunk of chunks) total += chunk.length
163
149
  return chunks
164
150
  },
165
- // Two zero blocks, then zeros to a multiple of the record size.
151
+ // Two zero blocks, then zeros to a whole record
166
152
  end() {
167
153
  const record = blocking * BLOCK
168
- const rest = (total + 2 * BLOCK) % record
169
- return [new Uint8Array(2 * BLOCK + (rest ? record - rest : 0))]
154
+ return [new Uint8Array(Math.ceil((total + 2 * BLOCK) / record) * record - total)]
170
155
  },
171
156
  }
172
157
  }
package/src/tar/pax.js CHANGED
@@ -1,23 +1,19 @@
1
- // pax extended header records: `<length> <keyword>=<value>\n`, the length
2
- // in decimal counting the whole line, its own digits included.
3
-
4
1
  import { utf8fromString } from '@exodus/bytes/utf8.js'
5
2
  import { concat } from '../bytes.js'
6
3
  import { ArchiveError } from '../error.js'
7
4
  import { decodeUtf8, hasUnsafe, quote } from '../text.js'
8
5
 
6
+ // `<length> <keyword>=<value>\n`, the length counting the whole record, its own digits included
9
7
  function record(keyword, value) {
10
8
  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])
9
+ let length = body.length + 1
10
+ while (body.length + String(length).length !== length) length++
11
+ return concat([utf8fromString(String(length)), body])
15
12
  }
16
13
 
17
14
  export const encodePax = (records) => concat(records.map(([keyword, value]) => record(keyword, value)))
18
15
 
19
- // Records as an entry hands them out: a Map that nothing can change, since
20
- // every entry under the same global header shares that header's.
16
+ // Read-only, as entries under one global header share its records
21
17
  const READ_ONLY = 'pax records cannot be changed'
22
18
  export class Records extends Map {
23
19
  set() {
@@ -32,7 +28,6 @@ export class Records extends Map {
32
28
  throw new TypeError(READ_ONLY)
33
29
  }
34
30
  }
35
- const put = (records, keyword, value) => Map.prototype.set.call(records, keyword, value)
36
31
 
37
32
  export function decodePax(bytes, at) {
38
33
  const records = new Records()
@@ -48,7 +43,7 @@ export function decodePax(bytes, at) {
48
43
  const keyword = decodeUtf8(bytes.subarray(i + 1, equals), 'a pax record', at)
49
44
  if (keyword === '' || hasUnsafe(keyword, false) || keyword.includes(' ')) throw new ArchiveError(`pax keyword ${quote(keyword)} is malformed`, at)
50
45
  if (records.has(keyword)) throw new ArchiveError(`pax keyword ${keyword} repeats`, at)
51
- put(records, keyword, decodeUtf8(bytes.subarray(equals + 1, end - 1), 'a pax record', at))
46
+ Map.prototype.set.call(records, keyword, decodeUtf8(bytes.subarray(equals + 1, end - 1), 'a pax record', at))
52
47
  pos = end
53
48
  }
54
49
  return records