parse.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 path = require('path')
  23. const Header = require('./header.js')
  24. const EE = require('events')
  25. const Yallist = require('yallist')
  26. const maxMetaEntrySize = 1024 * 1024
  27. const Entry = require('./read-entry.js')
  28. const Pax = require('./pax.js')
  29. const zlib = require('minizlib')
  30. const gzipHeader = Buffer.from([0x1f, 0x8b])
  31. const STATE = Symbol('state')
  32. const WRITEENTRY = Symbol('writeEntry')
  33. const READENTRY = Symbol('readEntry')
  34. const NEXTENTRY = Symbol('nextEntry')
  35. const PROCESSENTRY = Symbol('processEntry')
  36. const EX = Symbol('extendedHeader')
  37. const GEX = Symbol('globalExtendedHeader')
  38. const META = Symbol('meta')
  39. const EMITMETA = Symbol('emitMeta')
  40. const BUFFER = Symbol('buffer')
  41. const QUEUE = Symbol('queue')
  42. const ENDED = Symbol('ended')
  43. const EMITTEDEND = Symbol('emittedEnd')
  44. const EMIT = Symbol('emit')
  45. const UNZIP = Symbol('unzip')
  46. const CONSUMECHUNK = Symbol('consumeChunk')
  47. const CONSUMECHUNKSUB = Symbol('consumeChunkSub')
  48. const CONSUMEBODY = Symbol('consumeBody')
  49. const CONSUMEMETA = Symbol('consumeMeta')
  50. const CONSUMEHEADER = Symbol('consumeHeader')
  51. const CONSUMING = Symbol('consuming')
  52. const BUFFERCONCAT = Symbol('bufferConcat')
  53. const MAYBEEND = Symbol('maybeEnd')
  54. const WRITING = Symbol('writing')
  55. const ABORTED = Symbol('aborted')
  56. const DONE = Symbol('onDone')
  57. const SAW_VALID_ENTRY = Symbol('sawValidEntry')
  58. const SAW_NULL_BLOCK = Symbol('sawNullBlock')
  59. const SAW_EOF = Symbol('sawEOF')
  60. const noop = _ => true
  61. module.exports = warner(class Parser extends EE {
  62. constructor (opt) {
  63. opt = opt || {}
  64. super(opt)
  65. this.file = opt.file || ''
  66. // set to boolean false when an entry starts. 1024 bytes of \0
  67. // is technically a valid tarball, albeit a boring one.
  68. this[SAW_VALID_ENTRY] = null
  69. // these BADARCHIVE errors can't be detected early. listen on DONE.
  70. this.on(DONE, _ => {
  71. if (this[STATE] === 'begin' || this[SAW_VALID_ENTRY] === false) {
  72. // either less than 1 block of data, or all entries were invalid.
  73. // Either way, probably not even a tarball.
  74. this.warn('TAR_BAD_ARCHIVE', 'Unrecognized archive format')
  75. }
  76. })
  77. if (opt.ondone)
  78. this.on(DONE, opt.ondone)
  79. else
  80. this.on(DONE, _ => {
  81. this.emit('prefinish')
  82. this.emit('finish')
  83. this.emit('end')
  84. this.emit('close')
  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. }
  158. if (entry.meta) {
  159. if (entry.size > this.maxMetaEntrySize) {
  160. entry.ignore = true
  161. this[EMIT]('ignoredEntry', entry)
  162. this[STATE] = 'ignore'
  163. entry.resume()
  164. } else if (entry.size > 0) {
  165. this[META] = ''
  166. entry.on('data', c => this[META] += c)
  167. this[STATE] = 'meta'
  168. }
  169. } else {
  170. this[EX] = null
  171. entry.ignore = entry.ignore || !this.filter(entry.path, entry)
  172. if (entry.ignore) {
  173. // probably valid, just not something we care about
  174. this[EMIT]('ignoredEntry', entry)
  175. this[STATE] = entry.remain ? 'ignore' : 'header'
  176. entry.resume()
  177. } else {
  178. if (entry.remain)
  179. this[STATE] = 'body'
  180. else {
  181. this[STATE] = 'header'
  182. entry.end()
  183. }
  184. if (!this[READENTRY]) {
  185. this[QUEUE].push(entry)
  186. this[NEXTENTRY]()
  187. } else
  188. this[QUEUE].push(entry)
  189. }
  190. }
  191. }
  192. }
  193. }
  194. }
  195. [PROCESSENTRY] (entry) {
  196. let go = true
  197. if (!entry) {
  198. this[READENTRY] = null
  199. go = false
  200. } else if (Array.isArray(entry))
  201. this.emit.apply(this, entry)
  202. else {
  203. this[READENTRY] = entry
  204. this.emit('entry', entry)
  205. if (!entry.emittedEnd) {
  206. entry.on('end', _ => this[NEXTENTRY]())
  207. go = false
  208. }
  209. }
  210. return go
  211. }
  212. [NEXTENTRY] () {
  213. do {} while (this[PROCESSENTRY](this[QUEUE].shift()))
  214. if (!this[QUEUE].length) {
  215. // At this point, there's nothing in the queue, but we may have an
  216. // entry which is being consumed (readEntry).
  217. // If we don't, then we definitely can handle more data.
  218. // If we do, and either it's flowing, or it has never had any data
  219. // written to it, then it needs more.
  220. // The only other possibility is that it has returned false from a
  221. // write() call, so we wait for the next drain to continue.
  222. const re = this[READENTRY]
  223. const drainNow = !re || re.flowing || re.size === re.remain
  224. if (drainNow) {
  225. if (!this[WRITING])
  226. this.emit('drain')
  227. } else
  228. re.once('drain', _ => this.emit('drain'))
  229. }
  230. }
  231. [CONSUMEBODY] (chunk, position) {
  232. // write up to but no more than writeEntry.blockRemain
  233. const entry = this[WRITEENTRY]
  234. const br = entry.blockRemain
  235. const c = (br >= chunk.length && position === 0) ? chunk
  236. : chunk.slice(position, position + br)
  237. entry.write(c)
  238. if (!entry.blockRemain) {
  239. this[STATE] = 'header'
  240. this[WRITEENTRY] = null
  241. entry.end()
  242. }
  243. return c.length
  244. }
  245. [CONSUMEMETA] (chunk, position) {
  246. const entry = this[WRITEENTRY]
  247. const ret = this[CONSUMEBODY](chunk, position)
  248. // if we finished, then the entry is reset
  249. if (!this[WRITEENTRY])
  250. this[EMITMETA](entry)
  251. return ret
  252. }
  253. [EMIT] (ev, data, extra) {
  254. if (!this[QUEUE].length && !this[READENTRY])
  255. this.emit(ev, data, extra)
  256. else
  257. this[QUEUE].push([ev, data, extra])
  258. }
  259. [EMITMETA] (entry) {
  260. this[EMIT]('meta', this[META])
  261. switch (entry.type) {
  262. case 'ExtendedHeader':
  263. case 'OldExtendedHeader':
  264. this[EX] = Pax.parse(this[META], this[EX], false)
  265. break
  266. case 'GlobalExtendedHeader':
  267. this[GEX] = Pax.parse(this[META], this[GEX], true)
  268. break
  269. case 'NextFileHasLongPath':
  270. case 'OldGnuLongPath':
  271. this[EX] = this[EX] || Object.create(null)
  272. this[EX].path = this[META].replace(/\0.*/, '')
  273. break
  274. case 'NextFileHasLongLinkpath':
  275. this[EX] = this[EX] || Object.create(null)
  276. this[EX].linkpath = this[META].replace(/\0.*/, '')
  277. break
  278. /* istanbul ignore next */
  279. default: throw new Error('unknown meta: ' + entry.type)
  280. }
  281. }
  282. abort (error) {
  283. this[ABORTED] = true
  284. this.emit('abort', error)
  285. // always throws, even in non-strict mode
  286. this.warn('TAR_ABORT', error, { recoverable: false })
  287. }
  288. write (chunk) {
  289. if (this[ABORTED])
  290. return
  291. // first write, might be gzipped
  292. if (this[UNZIP] === null && chunk) {
  293. if (this[BUFFER]) {
  294. chunk = Buffer.concat([this[BUFFER], chunk])
  295. this[BUFFER] = null
  296. }
  297. if (chunk.length < gzipHeader.length) {
  298. this[BUFFER] = chunk
  299. return true
  300. }
  301. for (let i = 0; this[UNZIP] === null && i < gzipHeader.length; i++) {
  302. if (chunk[i] !== gzipHeader[i])
  303. this[UNZIP] = false
  304. }
  305. if (this[UNZIP] === null) {
  306. const ended = this[ENDED]
  307. this[ENDED] = false
  308. this[UNZIP] = new zlib.Unzip()
  309. this[UNZIP].on('data', chunk => this[CONSUMECHUNK](chunk))
  310. this[UNZIP].on('error', er => this.abort(er))
  311. this[UNZIP].on('end', _ => {
  312. this[ENDED] = true
  313. this[CONSUMECHUNK]()
  314. })
  315. this[WRITING] = true
  316. const ret = this[UNZIP][ended ? 'end' : 'write' ](chunk)
  317. this[WRITING] = false
  318. return ret
  319. }
  320. }
  321. this[WRITING] = true
  322. if (this[UNZIP])
  323. this[UNZIP].write(chunk)
  324. else
  325. this[CONSUMECHUNK](chunk)
  326. this[WRITING] = false
  327. // return false if there's a queue, or if the current entry isn't flowing
  328. const ret =
  329. this[QUEUE].length ? false :
  330. this[READENTRY] ? this[READENTRY].flowing :
  331. true
  332. // if we have no queue, then that means a clogged READENTRY
  333. if (!ret && !this[QUEUE].length)
  334. this[READENTRY].once('drain', _ => this.emit('drain'))
  335. return ret
  336. }
  337. [BUFFERCONCAT] (c) {
  338. if (c && !this[ABORTED])
  339. this[BUFFER] = this[BUFFER] ? Buffer.concat([this[BUFFER], c]) : c
  340. }
  341. [MAYBEEND] () {
  342. if (this[ENDED] &&
  343. !this[EMITTEDEND] &&
  344. !this[ABORTED] &&
  345. !this[CONSUMING]) {
  346. this[EMITTEDEND] = true
  347. const entry = this[WRITEENTRY]
  348. if (entry && entry.blockRemain) {
  349. // truncated, likely a damaged file
  350. const have = this[BUFFER] ? this[BUFFER].length : 0
  351. this.warn('TAR_BAD_ARCHIVE', `Truncated input (needed ${
  352. entry.blockRemain} more bytes, only ${have} available)`, {entry})
  353. if (this[BUFFER])
  354. entry.write(this[BUFFER])
  355. entry.end()
  356. }
  357. this[EMIT](DONE)
  358. }
  359. }
  360. [CONSUMECHUNK] (chunk) {
  361. if (this[CONSUMING])
  362. this[BUFFERCONCAT](chunk)
  363. else if (!chunk && !this[BUFFER])
  364. this[MAYBEEND]()
  365. else {
  366. this[CONSUMING] = true
  367. if (this[BUFFER]) {
  368. this[BUFFERCONCAT](chunk)
  369. const c = this[BUFFER]
  370. this[BUFFER] = null
  371. this[CONSUMECHUNKSUB](c)
  372. } else {
  373. this[CONSUMECHUNKSUB](chunk)
  374. }
  375. while (this[BUFFER] &&
  376. this[BUFFER].length >= 512 &&
  377. !this[ABORTED] &&
  378. !this[SAW_EOF]) {
  379. const c = this[BUFFER]
  380. this[BUFFER] = null
  381. this[CONSUMECHUNKSUB](c)
  382. }
  383. this[CONSUMING] = false
  384. }
  385. if (!this[BUFFER] || this[ENDED])
  386. this[MAYBEEND]()
  387. }
  388. [CONSUMECHUNKSUB] (chunk) {
  389. // we know that we are in CONSUMING mode, so anything written goes into
  390. // the buffer. Advance the position and put any remainder in the buffer.
  391. let position = 0
  392. let length = chunk.length
  393. while (position + 512 <= length && !this[ABORTED] && !this[SAW_EOF]) {
  394. switch (this[STATE]) {
  395. case 'begin':
  396. case 'header':
  397. this[CONSUMEHEADER](chunk, position)
  398. position += 512
  399. break
  400. case 'ignore':
  401. case 'body':
  402. position += this[CONSUMEBODY](chunk, position)
  403. break
  404. case 'meta':
  405. position += this[CONSUMEMETA](chunk, position)
  406. break
  407. /* istanbul ignore next */
  408. default:
  409. throw new Error('invalid state: ' + this[STATE])
  410. }
  411. }
  412. if (position < length) {
  413. if (this[BUFFER])
  414. this[BUFFER] = Buffer.concat([chunk.slice(position), this[BUFFER]])
  415. else
  416. this[BUFFER] = chunk.slice(position)
  417. }
  418. }
  419. end (chunk) {
  420. if (!this[ABORTED]) {
  421. if (this[UNZIP])
  422. this[UNZIP].end(chunk)
  423. else {
  424. this[ENDED] = true
  425. this.write(chunk)
  426. }
  427. }
  428. }
  429. })