parse.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. 'use strict'
  2. // this[BUFFER] is the remainder of a chunk if we're waiting for
  3. // the full 512 bytes of a header to come in. We will Buffer.concat()
  4. // it to the next write(), which is a mem copy, but a small one.
  5. //
  6. // this[QUEUE] is a Yallist of entries that haven't been emitted
  7. // yet this can only get filled up if the user keeps write()ing after
  8. // a write() returns false, or does a write() with more than one entry
  9. //
  10. // We don't buffer chunks, we always parse them and either create an
  11. // entry, or push it into the active entry. The ReadEntry class knows
  12. // to throw data away if .ignore=true
  13. //
  14. // Shift entry off the buffer when it emits 'end', and emit 'entry' for
  15. // the next one in the list.
  16. //
  17. // At any time, we're pushing body chunks into the entry at WRITEENTRY,
  18. // and waiting for 'end' on the entry at READENTRY
  19. //
  20. // ignored entries get .resume() called on them straight away
  21. const warner = require('./warn-mixin.js')
  22. const Header = require('./header.js')
  23. const EE = require('events')
  24. const Yallist = require('yallist')
  25. const maxMetaEntrySize = 1024 * 1024
  26. const Entry = require('./read-entry.js')
  27. const Pax = require('./pax.js')
  28. const zlib = require('minizlib')
  29. const gzipHeader = Buffer.from([0x1f, 0x8b])
  30. const STATE = Symbol('state')
  31. const WRITEENTRY = Symbol('writeEntry')
  32. const READENTRY = Symbol('readEntry')
  33. const NEXTENTRY = Symbol('nextEntry')
  34. const PROCESSENTRY = Symbol('processEntry')
  35. const EX = Symbol('extendedHeader')
  36. const GEX = Symbol('globalExtendedHeader')
  37. const META = Symbol('meta')
  38. const EMITMETA = Symbol('emitMeta')
  39. const BUFFER = Symbol('buffer')
  40. const QUEUE = Symbol('queue')
  41. const ENDED = Symbol('ended')
  42. const EMITTEDEND = Symbol('emittedEnd')
  43. const EMIT = Symbol('emit')
  44. const UNZIP = Symbol('unzip')
  45. const CONSUMECHUNK = Symbol('consumeChunk')
  46. const CONSUMECHUNKSUB = Symbol('consumeChunkSub')
  47. const CONSUMEBODY = Symbol('consumeBody')
  48. const CONSUMEMETA = Symbol('consumeMeta')
  49. const CONSUMEHEADER = Symbol('consumeHeader')
  50. const CONSUMING = Symbol('consuming')
  51. const BUFFERCONCAT = Symbol('bufferConcat')
  52. const MAYBEEND = Symbol('maybeEnd')
  53. const WRITING = Symbol('writing')
  54. const ABORTED = Symbol('aborted')
  55. const DONE = Symbol('onDone')
  56. const SAW_VALID_ENTRY = Symbol('sawValidEntry')
  57. const SAW_NULL_BLOCK = Symbol('sawNullBlock')
  58. const SAW_EOF = Symbol('sawEOF')
  59. const noop = _ => true
  60. module.exports = warner(class Parser extends EE {
  61. constructor (opt) {
  62. opt = opt || {}
  63. super(opt)
  64. this.file = opt.file || ''
  65. // set to boolean false when an entry starts. 1024 bytes of \0
  66. // is technically a valid tarball, albeit a boring one.
  67. this[SAW_VALID_ENTRY] = null
  68. // these BADARCHIVE errors can't be detected early. listen on DONE.
  69. this.on(DONE, _ => {
  70. if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) {
  71. // either less than 1 block of data, or all entries were invalid.
  72. // Either way, probably not even a tarball.
  73. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format')
  74. }
  75. })
  76. if (opt.ondone)
  77. this.on(DONE, opt.ondone)
  78. else {
  79. this.on(DONE, _ => {
  80. this.emit('prefinish')
  81. this.emit('finish')
  82. this.emit('end')
  83. this.emit('close')
  84. })
  85. }
  86. this.strict = !!opt.strict
  87. this.maxMetaEntrySize = opt.maxMetaEntrySize || maxMetaEntrySize
  88. this.filter = typeof opt.filter === 'function' ? opt.filter : noop
  89. // have to set this so that streams are ok piping into it
  90. this.writable = true
  91. this.readable = false
  92. this[QUEUE] = new Yallist()
  93. this[BUFFER] = null
  94. this[READENTRY] = null
  95. this[WRITEENTRY] = null
  96. this[STATE] = 'begin'
  97. this[META] = ''
  98. this[EX] = null
  99. this[GEX] = null
  100. this[ENDED] = false
  101. this[UNZIP] = null
  102. this[ABORTED] = false
  103. this[SAW_NULL_BLOCK] = false
  104. this[SAW_EOF] = false
  105. if (typeof opt.onwarn === 'function')
  106. this.on('warn', opt.onwarn)
  107. if (typeof opt.onentry === 'function')
  108. this.on('entry', opt.onentry)
  109. }
  110. [CONSUMEHEADER] (chunk, position) {
  111. if (this[SAW_VALID_ENTRY] === null)
  112. this[SAW_VALID_ENTRY] = false
  113. let header
  114. try {
  115. header = new Header(chunk, position, this[EX], this[GEX])
  116. } catch (er) {
  117. return this.warn('TAR_ENTRY_INVALID', er)
  118. }
  119. if (header.nullBlock) {
  120. if (this[SAW_NULL_BLOCK]) {
  121. this[SAW_EOF] = true
  122. // ending an archive with no entries. pointless, but legal.
  123. if (this[STATE] === 'begin')
  124. this[STATE] = 'header'
  125. this[EMIT]('eof')
  126. } else {
  127. this[SAW_NULL_BLOCK] = true
  128. this[EMIT]('nullBlock')
  129. }
  130. } else {
  131. this[SAW_NULL_BLOCK] = false
  132. if (!header.cksumValid)
  133. this.warn('TAR_ENTRY_INVALID', 'checksum failure', {header})
  134. else if (!header.path)
  135. this.warn('TAR_ENTRY_INVALID', 'path is required', {header})
  136. else {
  137. const type = header.type
  138. if (/^(Symbolic)?Link$/.test(type) && !header.linkpath)
  139. this.warn('TAR_ENTRY_INVALID', 'linkpath required', {header})
  140. else if (!/^(Symbolic)?Link$/.test(type) && header.linkpath)
  141. this.warn('TAR_ENTRY_INVALID', 'linkpath forbidden', {header})
  142. else {
  143. const entry = this[WRITEENTRY] = new Entry(header, this[EX], this[GEX])
  144. // we do this for meta & ignored entries as well, because they
  145. // are still valid tar, or else we wouldn't know to ignore them
  146. if (!this[SAW_VALID_ENTRY]) {
  147. if (entry.remain) {
  148. // this might be the one!
  149. const onend = () => {
  150. if (!entry.invalid)
  151. this[SAW_VALID_ENTRY] = true
  152. }
  153. entry.on('end', onend)
  154. } else
  155. this[SAW_VALID_ENTRY] = true
  156. }
  157. if (entry.meta) {
  158. if (entry.size > this.maxMetaEntrySize) {
  159. entry.ignore = true
  160. this[EMIT]('ignoredEntry', entry)
  161. this[STATE] = 'ignore'
  162. entry.resume()
  163. } else if (entry.size > 0) {
  164. this[META] = ''
  165. entry.on('data', c => this[META] += c)
  166. this[STATE] = 'meta'
  167. }
  168. } else {
  169. this[EX] = null
  170. entry.ignore = entry.ignore || !this.filter(entry.path, entry)
  171. if (entry.ignore) {
  172. // probably valid, just not something we care about
  173. this[EMIT]('ignoredEntry', entry)
  174. this[STATE] = entry.remain ? 'ignore' : 'header'
  175. entry.resume()
  176. } else {
  177. if (entry.remain)
  178. this[STATE] = 'body'
  179. else {
  180. this[STATE] = 'header'
  181. entry.end()
  182. }
  183. if (!this[READENTRY]) {
  184. this[QUEUE].push(entry)
  185. this[NEXTENTRY]()
  186. } else
  187. this[QUEUE].push(entry)
  188. }
  189. }
  190. }
  191. }
  192. }
  193. }
  194. [PROCESSENTRY] (entry) {
  195. let go = true
  196. if (!entry) {
  197. this[READENTRY] = null
  198. go = false
  199. } else if (Array.isArray(entry))
  200. this.emit.apply(this, entry)
  201. else {
  202. this[READENTRY] = entry
  203. this.emit('entry', entry)
  204. if (!entry.emittedEnd) {
  205. entry.on('end', _ => this[NEXTENTRY]())
  206. go = false
  207. }
  208. }
  209. return go
  210. }
  211. [NEXTENTRY] () {
  212. do {} while (this[PROCESSENTRY](this[QUEUE].shift()))
  213. if (!this[QUEUE].length) {
  214. // At this point, there's nothing in the queue, but we may have an
  215. // entry which is being consumed (readEntry).
  216. // If we don't, then we definitely can handle more data.
  217. // If we do, and either it's flowing, or it has never had any data
  218. // written to it, then it needs more.
  219. // The only other possibility is that it has returned false from a
  220. // write() call, so we wait for the next drain to continue.
  221. const re = this[READENTRY]
  222. const drainNow = !re || re.flowing || re.size === re.remain
  223. if (drainNow) {
  224. if (!this[WRITING])
  225. this.emit('drain')
  226. } else
  227. re.once('drain', _ => this.emit('drain'))
  228. }
  229. }
  230. [CONSUMEBODY] (chunk, position) {
  231. // write up to but no more than writeEntry.blockRemain
  232. const entry = this[WRITEENTRY]
  233. const br = entry.blockRemain
  234. const c = (br >= chunk.length && position === 0) ? chunk
  235. : chunk.slice(position, position + br)
  236. entry.write(c)
  237. if (!entry.blockRemain) {
  238. this[STATE] = 'header'
  239. this[WRITEENTRY] = null
  240. entry.end()
  241. }
  242. return c.length
  243. }
  244. [CONSUMEMETA] (chunk, position) {
  245. const entry = this[WRITEENTRY]
  246. const ret = this[CONSUMEBODY](chunk, position)
  247. // if we finished, then the entry is reset
  248. if (!this[WRITEENTRY])
  249. this[EMITMETA](entry)
  250. return ret
  251. }
  252. [EMIT] (ev, data, extra) {
  253. if (!this[QUEUE].length && !this[READENTRY])
  254. this.emit(ev, data, extra)
  255. else
  256. this[QUEUE].push([ev, data, extra])
  257. }
  258. [EMITMETA] (entry) {
  259. this[EMIT]('meta', this[META])
  260. switch (entry.type) {
  261. case 'ExtendedHeader':
  262. case 'OldExtendedHeader':
  263. this[EX] = Pax.parse(this[META], this[EX], false)
  264. break
  265. case 'GlobalExtendedHeader':
  266. this[GEX] = Pax.parse(this[META], this[GEX], true)
  267. break
  268. case 'NextFileHasLongPath':
  269. case 'OldGnuLongPath':
  270. this[EX] = this[EX] || Object.create(null)
  271. this[EX].path = this[META].replace(/\0.*/, '')
  272. break
  273. case 'NextFileHasLongLinkpath':
  274. this[EX] = this[EX] || Object.create(null)
  275. this[EX].linkpath = this[META].replace(/\0.*/, '')
  276. break
  277. /* istanbul ignore next */
  278. default: throw new Error('unknown meta: ' + entry.type)
  279. }
  280. }
  281. abort (error) {
  282. this[ABORTED] = true
  283. this.emit('abort', error)
  284. // always throws, even in non-strict mode
  285. this.warn('TAR_ABORT', error, { recoverable: false })
  286. }
  287. write (chunk) {
  288. if (this[ABORTED])
  289. return
  290. // first write, might be gzipped
  291. if (this[UNZIP] === null && chunk) {
  292. if (this[BUFFER]) {
  293. chunk = Buffer.concat([this[BUFFER], chunk])
  294. this[BUFFER] = null
  295. }
  296. if (chunk.length < gzipHeader.length) {
  297. this[BUFFER] = chunk
  298. return true
  299. }
  300. for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) {
  301. if (chunk[i] !== gzipHeader[i])
  302. this[UNZIP] = false
  303. }
  304. if (this[UNZIP] === null) {
  305. const ended = this[ENDED]
  306. this[ENDED] = false
  307. this[UNZIP] = new zlib.Unzip()
  308. this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk))
  309. this[UNZIP].on('error', er => this.abort(er))
  310. this[UNZIP].on('end', _ => {
  311. this[ENDED] = true
  312. this[CONSUMECHUNK]()
  313. })
  314. this[WRITING] = true
  315. const ret = this[UNZIP][ended ? 'end' : 'write'](chunk)
  316. this[WRITING] = false
  317. return ret
  318. }
  319. }
  320. this[WRITING] = true
  321. if (this[UNZIP])
  322. this[UNZIP].write(chunk)
  323. else
  324. this[CONSUMECHUNK](chunk)
  325. this[WRITING] = false
  326. // return false if there's a queue, or if the current entry isn't flowing
  327. const ret =
  328. this[QUEUE].length ? false :
  329. this[READENTRY] ? this[READENTRY].flowing :
  330. true
  331. // if we have no queue, then that means a clogged READENTRY
  332. if (!ret && !this[QUEUE].length)
  333. this[READENTRY].once('drain', _ => this.emit('drain'))
  334. return ret
  335. }
  336. [BUFFERCONCAT] (c) {
  337. if (c && !this[ABORTED])
  338. this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c
  339. }
  340. [MAYBEEND] () {
  341. if (this[ENDED] &&
  342. !this[EMITTEDEND] &&
  343. !this[ABORTED] &&
  344. !this[CONSUMING]) {
  345. this[EMITTEDEND] = true
  346. const entry = this[WRITEENTRY]
  347. if (entry && entry.blockRemain) {
  348. // truncated, likely a damaged file
  349. const have = this[BUFFER] ? this[BUFFER].length : 0
  350. this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${
  351. entry.blockRemain} more bytes, only ${have} available)`, {entry})
  352. if (this[BUFFER])
  353. entry.write(this[BUFFER])
  354. entry.end()
  355. }
  356. this[EMIT](DONE)
  357. }
  358. }
  359. [CONSUMECHUNK] (chunk) {
  360. if (this[CONSUMING])
  361. this[BUFFERCONCAT](chunk)
  362. else if (!chunk && !this[BUFFER])
  363. this[MAYBEEND]()
  364. else {
  365. this[CONSUMING] = true
  366. if (this[BUFFER]) {
  367. this[BUFFERCONCAT](chunk)
  368. const c = this[BUFFER]
  369. this[BUFFER] = null
  370. this[CONSUMECHUNKSUB](c)
  371. } else
  372. this[CONSUMECHUNKSUB](chunk)
  373. while (this[BUFFER] &&
  374. this[BUFFER].length >= 512 &&
  375. !this[ABORTED] &&
  376. !this[SAW_EOF]) {
  377. const c = this[BUFFER]
  378. this[BUFFER] = null
  379. this[CONSUMECHUNKSUB](c)
  380. }
  381. this[CONSUMING] = false
  382. }
  383. if (!this[BUFFER] || this[ENDED])
  384. this[MAYBEEND]()
  385. }
  386. [CONSUMECHUNKSUB] (chunk) {
  387. // we know that we are in CONSUMING mode, so anything written goes into
  388. // the buffer. Advance the position and put any remainder in the buffer.
  389. let position = 0
  390. const length = chunk.length
  391. while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) {
  392. switch (this[STATE]) {
  393. case 'begin':
  394. case 'header':
  395. this[CONSUMEHEADER](chunk, position)
  396. position += 512
  397. break
  398. case 'ignore':
  399. case 'body':
  400. position += this[CONSUMEBODY](chunk, position)
  401. break
  402. case 'meta':
  403. position += this[CONSUMEMETA](chunk, position)
  404. break
  405. /* istanbul ignore next */
  406. default:
  407. throw new Error('invalid state: ' + this[STATE])
  408. }
  409. }
  410. if (position < length) {
  411. if (this[BUFFER])
  412. this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]])
  413. else
  414. this[BUFFER] = chunk.slice(position)
  415. }
  416. }
  417. end (chunk) {
  418. if (!this[ABORTED]) {
  419. if (this[UNZIP])
  420. this[UNZIP].end(chunk)
  421. else {
  422. this[ENDED] = true
  423. this.write(chunk)
  424. }
  425. }
  426. }
  427. })