node_stream_zip.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. /**
  2. * @license node-stream-zip | (c) 2015 Antelle | https://github.com/antelle/node-stream-zip/blob/master/LICENSE
  3. * Portions copyright https://github.com/cthackers/adm-zip | https://raw.githubusercontent.com/cthackers/adm-zip/master/LICENSE
  4. */
  5. // region Deps
  6. var
  7. util = require('util'),
  8. fs = require('fs'),
  9. path = require('path'),
  10. events = require('events'),
  11. zlib = require('zlib'),
  12. stream = require('stream');
  13. // endregion
  14. // region Constants
  15. var consts = {
  16. /* The local file header */
  17. LOCHDR : 30, // LOC header size
  18. LOCSIG : 0x04034b50, // "PK\003\004"
  19. LOCVER : 4, // version needed to extract
  20. LOCFLG : 6, // general purpose bit flag
  21. LOCHOW : 8, // compression method
  22. LOCTIM : 10, // modification time (2 bytes time, 2 bytes date)
  23. LOCCRC : 14, // uncompressed file crc-32 value
  24. LOCSIZ : 18, // compressed size
  25. LOCLEN : 22, // uncompressed size
  26. LOCNAM : 26, // filename length
  27. LOCEXT : 28, // extra field length
  28. /* The Data descriptor */
  29. EXTSIG : 0x08074b50, // "PK\007\008"
  30. EXTHDR : 16, // EXT header size
  31. EXTCRC : 4, // uncompressed file crc-32 value
  32. EXTSIZ : 8, // compressed size
  33. EXTLEN : 12, // uncompressed size
  34. /* The central directory file header */
  35. CENHDR : 46, // CEN header size
  36. CENSIG : 0x02014b50, // "PK\001\002"
  37. CENVEM : 4, // version made by
  38. CENVER : 6, // version needed to extract
  39. CENFLG : 8, // encrypt, decrypt flags
  40. CENHOW : 10, // compression method
  41. CENTIM : 12, // modification time (2 bytes time, 2 bytes date)
  42. CENCRC : 16, // uncompressed file crc-32 value
  43. CENSIZ : 20, // compressed size
  44. CENLEN : 24, // uncompressed size
  45. CENNAM : 28, // filename length
  46. CENEXT : 30, // extra field length
  47. CENCOM : 32, // file comment length
  48. CENDSK : 34, // volume number start
  49. CENATT : 36, // internal file attributes
  50. CENATX : 38, // external file attributes (host system dependent)
  51. CENOFF : 42, // LOC header offset
  52. /* The entries in the end of central directory */
  53. ENDHDR : 22, // END header size
  54. ENDSIG : 0x06054b50, // "PK\005\006"
  55. ENDSIGFIRST : 0x50,
  56. ENDSUB : 8, // number of entries on this disk
  57. ENDTOT : 10, // total number of entries
  58. ENDSIZ : 12, // central directory size in bytes
  59. ENDOFF : 16, // offset of first CEN header
  60. ENDCOM : 20, // zip file comment length
  61. MAXFILECOMMENT : 0xFFFF,
  62. /* The entries in the end of ZIP64 central directory locator */
  63. ENDL64HDR : 20, // ZIP64 end of central directory locator header size
  64. ENDL64SIG : 0x07064b50, // ZIP64 end of central directory locator signature
  65. ENDL64SIGFIRST : 0x50,
  66. ENDL64OFS : 8, // ZIP64 end of central directory offset
  67. /* The entries in the end of ZIP64 central directory */
  68. END64HDR : 56, // ZIP64 end of central directory header size
  69. END64SIG : 0x06064b50, // ZIP64 end of central directory signature
  70. END64SIGFIRST : 0x50,
  71. END64SUB : 24, // number of entries on this disk
  72. END64TOT : 32, // total number of entries
  73. END64SIZ : 40,
  74. END64OFF : 48,
  75. /* Compression methods */
  76. STORED : 0, // no compression
  77. SHRUNK : 1, // shrunk
  78. REDUCED1 : 2, // reduced with compression factor 1
  79. REDUCED2 : 3, // reduced with compression factor 2
  80. REDUCED3 : 4, // reduced with compression factor 3
  81. REDUCED4 : 5, // reduced with compression factor 4
  82. IMPLODED : 6, // imploded
  83. // 7 reserved
  84. DEFLATED : 8, // deflated
  85. ENHANCED_DEFLATED: 9, // enhanced deflated
  86. PKWARE : 10,// PKWare DCL imploded
  87. // 11 reserved
  88. BZIP2 : 12, // compressed using BZIP2
  89. // 13 reserved
  90. LZMA : 14, // LZMA
  91. // 15-17 reserved
  92. IBM_TERSE : 18, // compressed using IBM TERSE
  93. IBM_LZ77 : 19, //IBM LZ77 z
  94. /* General purpose bit flag */
  95. FLG_ENC : 0, // encrypted file
  96. FLG_COMP1 : 1, // compression option
  97. FLG_COMP2 : 2, // compression option
  98. FLG_DESC : 4, // data descriptor
  99. FLG_ENH : 8, // enhanced deflation
  100. FLG_STR : 16, // strong encryption
  101. FLG_LNG : 1024, // language encoding
  102. FLG_MSK : 4096, // mask header values
  103. FLG_ENTRY_ENC : 1,
  104. /* 4.5 Extensible data fields */
  105. EF_ID : 0,
  106. EF_SIZE : 2,
  107. /* Header IDs */
  108. ID_ZIP64 : 0x0001,
  109. ID_AVINFO : 0x0007,
  110. ID_PFS : 0x0008,
  111. ID_OS2 : 0x0009,
  112. ID_NTFS : 0x000a,
  113. ID_OPENVMS : 0x000c,
  114. ID_UNIX : 0x000d,
  115. ID_FORK : 0x000e,
  116. ID_PATCH : 0x000f,
  117. ID_X509_PKCS7 : 0x0014,
  118. ID_X509_CERTID_F : 0x0015,
  119. ID_X509_CERTID_C : 0x0016,
  120. ID_STRONGENC : 0x0017,
  121. ID_RECORD_MGT : 0x0018,
  122. ID_X509_PKCS7_RL : 0x0019,
  123. ID_IBM1 : 0x0065,
  124. ID_IBM2 : 0x0066,
  125. ID_POSZIP : 0x4690,
  126. EF_ZIP64_OR_32 : 0xffffffff,
  127. EF_ZIP64_OR_16 : 0xffff
  128. };
  129. // endregion
  130. // region StreamZip
  131. var StreamZip = function(config) {
  132. var
  133. fd,
  134. fileSize,
  135. chunkSize,
  136. ready = false,
  137. that = this,
  138. op,
  139. centralDirectory,
  140. closed,
  141. entries = config.storeEntries !== false ? {} : null,
  142. fileName = config.file;
  143. open();
  144. function open() {
  145. fs.open(fileName, 'r', function(err, f) {
  146. if (err)
  147. return that.emit('error', err);
  148. fd = f;
  149. fs.fstat(fd, function(err, stat) {
  150. if (err)
  151. return that.emit('error', err);
  152. fileSize = stat.size;
  153. chunkSize = config.chunkSize || Math.round(fileSize / 1000);
  154. chunkSize = Math.max(Math.min(chunkSize, Math.min(128*1024, fileSize)), Math.min(1024, fileSize));
  155. readCentralDirectory();
  156. });
  157. });
  158. }
  159. function readUntilFoundCallback(err, bytesRead) {
  160. if (err || !bytesRead)
  161. return that.emit('error', err || 'Archive read error');
  162. var
  163. buffer = op.win.buffer,
  164. pos = op.lastPos,
  165. bufferPosition = pos - op.win.position,
  166. minPos = op.minPos;
  167. while (--pos >= minPos && --bufferPosition >= 0) {
  168. if (buffer.length - bufferPosition >= 4 &&
  169. buffer[bufferPosition] === op.firstByte) { // quick check first signature byte
  170. if (buffer.readUInt32LE(bufferPosition) === op.sig) {
  171. op.lastBufferPosition = bufferPosition;
  172. op.lastBytesRead = bytesRead;
  173. op.complete();
  174. return;
  175. }
  176. }
  177. }
  178. if (pos === minPos) {
  179. return that.emit('error', 'Bad archive');
  180. }
  181. op.lastPos = pos + 1;
  182. op.chunkSize *= 2;
  183. if (pos <= minPos)
  184. return that.emit('error', 'Bad archive');
  185. var expandLength = Math.min(op.chunkSize, pos - minPos);
  186. op.win.expandLeft(expandLength, readUntilFoundCallback);
  187. }
  188. function readCentralDirectory() {
  189. var totalReadLength = Math.min(consts.ENDHDR + consts.MAXFILECOMMENT, fileSize);
  190. op = {
  191. win: new FileWindowBuffer(fd),
  192. totalReadLength: totalReadLength,
  193. minPos: fileSize - totalReadLength,
  194. lastPos: fileSize,
  195. chunkSize: Math.min(1024, chunkSize),
  196. firstByte: consts.ENDSIGFIRST,
  197. sig: consts.ENDSIG,
  198. complete: readCentralDirectoryComplete
  199. };
  200. op.win.read(fileSize - op.chunkSize, op.chunkSize, readUntilFoundCallback);
  201. }
  202. function readCentralDirectoryComplete() {
  203. var buffer = op.win.buffer;
  204. var pos = op.lastBufferPosition;
  205. try {
  206. centralDirectory = new CentralDirectoryHeader();
  207. centralDirectory.read(buffer.slice(pos, pos + consts.ENDHDR));
  208. centralDirectory.headerOffset = op.win.position + pos;
  209. if (centralDirectory.commentLength)
  210. that.comment = buffer.slice(pos + consts.ENDHDR,
  211. pos + consts.ENDHDR + centralDirectory.commentLength).toString();
  212. else
  213. that.comment = null;
  214. that.entriesCount = centralDirectory.volumeEntries;
  215. that.centralDirectory = centralDirectory;
  216. if (centralDirectory.volumeEntries === consts.EF_ZIP64_OR_16 && centralDirectory.totalEntries === consts.EF_ZIP64_OR_16
  217. || centralDirectory.size === consts.EF_ZIP64_OR_32 || centralDirectory.offset === consts.EF_ZIP64_OR_32) {
  218. readZip64CentralDirectoryLocator();
  219. } else {
  220. op = {};
  221. readEntries();
  222. }
  223. } catch (err) {
  224. that.emit('error', err);
  225. }
  226. }
  227. function readZip64CentralDirectoryLocator() {
  228. var length = consts.ENDL64HDR;
  229. if (op.lastBufferPosition > length) {
  230. op.lastBufferPosition -= length;
  231. readZip64CentralDirectoryLocatorComplete();
  232. } else {
  233. op = {
  234. win: op.win,
  235. totalReadLength: length,
  236. minPos: op.win.position - length,
  237. lastPos: op.win.position,
  238. chunkSize: op.chunkSize,
  239. firstByte: consts.ENDL64SIGFIRST,
  240. sig: consts.ENDL64SIG,
  241. complete: readZip64CentralDirectoryLocatorComplete
  242. };
  243. op.win.read(op.lastPos - op.chunkSize, op.chunkSize, readUntilFoundCallback);
  244. }
  245. }
  246. function readZip64CentralDirectoryLocatorComplete() {
  247. var buffer = op.win.buffer;
  248. var locHeader = new CentralDirectoryLoc64Header();
  249. locHeader.read(buffer.slice(op.lastBufferPosition, op.lastBufferPosition + consts.ENDL64HDR));
  250. var readLength = fileSize - locHeader.headerOffset;
  251. op = {
  252. win: op.win,
  253. totalReadLength: readLength,
  254. minPos: locHeader.headerOffset,
  255. lastPos: op.lastPos,
  256. chunkSize: op.chunkSize,
  257. firstByte: consts.END64SIGFIRST,
  258. sig: consts.END64SIG,
  259. complete: readZip64CentralDirectoryComplete
  260. };
  261. op.win.read(fileSize - op.chunkSize, op.chunkSize, readUntilFoundCallback);
  262. }
  263. function readZip64CentralDirectoryComplete() {
  264. var buffer = op.win.buffer;
  265. var zip64cd = new CentralDirectoryZip64Header();
  266. zip64cd.read(buffer.slice(op.lastBufferPosition, op.lastBufferPosition + consts.END64HDR));
  267. that.centralDirectory.volumeEntries = zip64cd.volumeEntries;
  268. that.centralDirectory.totalEntries = zip64cd.totalEntries;
  269. that.centralDirectory.size = zip64cd.size;
  270. that.centralDirectory.offset = zip64cd.offset;
  271. that.entriesCount = zip64cd.volumeEntries;
  272. op = {};
  273. readEntries();
  274. }
  275. function readEntries() {
  276. op = {
  277. win: new FileWindowBuffer(fd),
  278. pos: centralDirectory.offset,
  279. chunkSize: chunkSize,
  280. entriesLeft: centralDirectory.volumeEntries
  281. };
  282. op.win.read(op.pos, Math.min(chunkSize, fileSize - op.pos), readEntriesCallback);
  283. }
  284. function readEntriesCallback(err, bytesRead) {
  285. if (err || !bytesRead)
  286. return that.emit('error', err || 'Entries read error');
  287. var
  288. buffer = op.win.buffer,
  289. bufferPos = op.pos - op.win.position,
  290. bufferLength = buffer.length,
  291. entry = op.entry;
  292. try {
  293. while (op.entriesLeft > 0) {
  294. if (!entry) {
  295. entry = new ZipEntry();
  296. entry.readHeader(buffer, bufferPos);
  297. entry.headerOffset = op.win.position + bufferPos;
  298. op.entry = entry;
  299. op.pos += consts.CENHDR;
  300. bufferPos += consts.CENHDR;
  301. }
  302. var entryHeaderSize = entry.fnameLen + entry.extraLen + entry.comLen;
  303. var advanceBytes = entryHeaderSize + (op.entriesLeft > 1 ? consts.CENHDR : 0);
  304. if (bufferLength - bufferPos < advanceBytes) {
  305. op.win.moveRight(chunkSize, readEntriesCallback, bufferPos);
  306. op.move = true;
  307. return;
  308. }
  309. entry.read(buffer, bufferPos);
  310. if (!config.skipEntryNameValidation) {
  311. entry.validateName();
  312. }
  313. if (entries)
  314. entries[entry.name] = entry;
  315. that.emit('entry', entry);
  316. op.entry = entry = null;
  317. op.entriesLeft--;
  318. op.pos += entryHeaderSize;
  319. bufferPos += entryHeaderSize;
  320. }
  321. that.emit('ready');
  322. } catch (err) {
  323. that.emit('error', err);
  324. }
  325. }
  326. function checkEntriesExist() {
  327. if (!entries)
  328. throw new Error('storeEntries disabled');
  329. }
  330. Object.defineProperty(this, 'ready', { get: function() { return ready; } });
  331. this.entry = function(name) {
  332. checkEntriesExist();
  333. return entries[name];
  334. };
  335. this.entries = function() {
  336. checkEntriesExist();
  337. return entries;
  338. };
  339. this.stream = function(entry, callback) {
  340. return this.openEntry(entry, function(err, entry) {
  341. if (err)
  342. return callback(err);
  343. var offset = dataOffset(entry);
  344. var entryStream = new EntryDataReaderStream(fd, offset, entry.compressedSize);
  345. if (entry.method === consts.STORED) {
  346. } else if (entry.method === consts.DEFLATED || entry.method === consts.ENHANCED_DEFLATED) {
  347. entryStream = entryStream.pipe(zlib.createInflateRaw());
  348. } else {
  349. return callback('Unknown compression method: ' + entry.method);
  350. }
  351. if (canVerifyCrc(entry))
  352. entryStream = entryStream.pipe(new EntryVerifyStream(entryStream, entry.crc, entry.size));
  353. callback(null, entryStream);
  354. }, false);
  355. };
  356. this.entryDataSync = function(entry) {
  357. var err = null;
  358. this.openEntry(entry, function(e, en) {
  359. err = e;
  360. entry = en;
  361. }, true);
  362. if (err)
  363. throw err;
  364. var
  365. data = Buffer.alloc(entry.compressedSize),
  366. bytesRead;
  367. new FsRead(fd, data, 0, entry.compressedSize, dataOffset(entry), function(e, br) {
  368. err = e;
  369. bytesRead = br;
  370. }).read(true);
  371. if (err)
  372. throw err;
  373. if (entry.method === consts.STORED) {
  374. } else if (entry.method === consts.DEFLATED || entry.method === consts.ENHANCED_DEFLATED) {
  375. data = zlib.inflateRawSync(data);
  376. } else {
  377. throw new Error('Unknown compression method: ' + entry.method);
  378. }
  379. if (data.length !== entry.size)
  380. throw new Error('Invalid size');
  381. if (canVerifyCrc(entry)) {
  382. var verify = new CrcVerify(entry.crc, entry.size);
  383. verify.data(data);
  384. }
  385. return data;
  386. };
  387. this.openEntry = function(entry, callback, sync) {
  388. if (typeof entry === 'string') {
  389. checkEntriesExist();
  390. entry = entries[entry];
  391. if (!entry)
  392. return callback('Entry not found');
  393. }
  394. if (!entry.isFile)
  395. return callback('Entry is not file');
  396. if (!fd)
  397. return callback('Archive closed');
  398. var buffer = Buffer.alloc(consts.LOCHDR);
  399. new FsRead(fd, buffer, 0, buffer.length, entry.offset, function(err) {
  400. if (err)
  401. return callback(err);
  402. var readEx;
  403. try {
  404. entry.readDataHeader(buffer);
  405. if (entry.encrypted) {
  406. readEx = 'Entry encrypted';
  407. }
  408. } catch (ex) {
  409. readEx = ex
  410. }
  411. callback(readEx, entry);
  412. }).read(sync);
  413. };
  414. function dataOffset(entry) {
  415. return entry.offset + consts.LOCHDR + entry.fnameLen + entry.extraLen;
  416. }
  417. function canVerifyCrc(entry) {
  418. // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written
  419. return (entry.flags & 0x8) != 0x8;
  420. }
  421. function extract(entry, outPath, callback) {
  422. that.stream(entry, function (err, stm) {
  423. if (err) {
  424. callback(err);
  425. } else {
  426. var fsStm, errThrown;
  427. stm.on('error', function(err) {
  428. errThrown = err;
  429. if (fsStm) {
  430. stm.unpipe(fsStm);
  431. fsStm.close(function () {
  432. callback(err);
  433. });
  434. }
  435. });
  436. fs.open(outPath, 'w', function(err, fdFile) {
  437. if (err)
  438. return callback(err || errThrown);
  439. if (errThrown) {
  440. fs.close(fd, function() {
  441. callback(errThrown);
  442. });
  443. return;
  444. }
  445. fsStm = fs.createWriteStream(outPath, { fd: fdFile });
  446. fsStm.on('finish', function() {
  447. that.emit('extract', entry, outPath);
  448. if (!errThrown)
  449. callback();
  450. });
  451. stm.pipe(fsStm);
  452. });
  453. }
  454. });
  455. }
  456. function createDirectories(baseDir, dirs, callback) {
  457. if (!dirs.length)
  458. return callback();
  459. var dir = dirs.shift();
  460. dir = path.join(baseDir, path.join.apply(path, dir));
  461. fs.mkdir(dir, function(err) {
  462. if (err && err.code !== 'EEXIST')
  463. return callback(err);
  464. createDirectories(baseDir, dirs, callback);
  465. });
  466. }
  467. function extractFiles(baseDir, baseRelPath, files, callback, extractedCount) {
  468. if (!files.length)
  469. return callback(null, extractedCount);
  470. var file = files.shift();
  471. var targetPath = path.join(baseDir, file.name.replace(baseRelPath, ''));
  472. extract(file, targetPath, function (err) {
  473. if (err)
  474. return callback(err, extractedCount);
  475. extractFiles(baseDir, baseRelPath, files, callback, extractedCount + 1);
  476. });
  477. }
  478. this.extract = function(entry, outPath, callback) {
  479. var entryName = entry || '';
  480. if (typeof entry === 'string') {
  481. entry = this.entry(entry);
  482. if (entry) {
  483. entryName = entry.name;
  484. } else {
  485. if (entryName.length && entryName[entryName.length - 1] !== '/')
  486. entryName += '/';
  487. }
  488. }
  489. if (!entry || entry.isDirectory) {
  490. var files = [], dirs = [], allDirs = {};
  491. for (var e in entries) {
  492. if (Object.prototype.hasOwnProperty.call(entries, e) && e.lastIndexOf(entryName, 0) === 0) {
  493. var relPath = e.replace(entryName, '');
  494. var childEntry = entries[e];
  495. if (childEntry.isFile) {
  496. files.push(childEntry);
  497. relPath = path.dirname(relPath);
  498. }
  499. if (relPath && !allDirs[relPath] && relPath !== '.') {
  500. allDirs[relPath] = true;
  501. var parts = relPath.split('/').filter(function (f) { return f; });
  502. if (parts.length)
  503. dirs.push(parts);
  504. while (parts.length > 1) {
  505. parts = parts.slice(0, parts.length - 1);
  506. var partsPath = parts.join('/');
  507. if (allDirs[partsPath] || partsPath === '.') {
  508. break;
  509. }
  510. allDirs[partsPath] = true;
  511. dirs.push(parts);
  512. }
  513. }
  514. }
  515. }
  516. dirs.sort(function(x, y) { return x.length - y.length; });
  517. if (dirs.length) {
  518. createDirectories(outPath, dirs, function (err) {
  519. if (err)
  520. callback(err);
  521. else
  522. extractFiles(outPath, entryName, files, callback, 0);
  523. });
  524. } else {
  525. extractFiles(outPath, entryName, files, callback, 0);
  526. }
  527. } else {
  528. fs.stat(outPath, function(err, stat) {
  529. if (stat && stat.isDirectory())
  530. extract(entry, path.join(outPath, path.basename(entry.name)), callback);
  531. else
  532. extract(entry, outPath, callback);
  533. });
  534. }
  535. };
  536. this.close = function(callback) {
  537. if (closed) {
  538. if (callback)
  539. callback();
  540. } else {
  541. closed = true;
  542. fs.close(fd, function(err) {
  543. fd = null;
  544. if (callback)
  545. callback(err);
  546. });
  547. }
  548. };
  549. var originalEmit = events.EventEmitter.prototype.emit;
  550. this.emit = function() {
  551. if (!closed) {
  552. return originalEmit.apply(this, arguments);
  553. }
  554. };
  555. };
  556. StreamZip.setFs = function(customFs) {
  557. fs = customFs;
  558. };
  559. util.inherits(StreamZip, events.EventEmitter);
  560. // endregion
  561. // region CentralDirectoryHeader
  562. var CentralDirectoryHeader = function() {
  563. };
  564. CentralDirectoryHeader.prototype.read = function(data) {
  565. if (data.length != consts.ENDHDR || data.readUInt32LE(0) != consts.ENDSIG)
  566. throw new Error('Invalid central directory');
  567. // number of entries on this volume
  568. this.volumeEntries = data.readUInt16LE(consts.ENDSUB);
  569. // total number of entries
  570. this.totalEntries = data.readUInt16LE(consts.ENDTOT);
  571. // central directory size in bytes
  572. this.size = data.readUInt32LE(consts.ENDSIZ);
  573. // offset of first CEN header
  574. this.offset = data.readUInt32LE(consts.ENDOFF);
  575. // zip file comment length
  576. this.commentLength = data.readUInt16LE(consts.ENDCOM);
  577. };
  578. // endregion
  579. // region CentralDirectoryLoc64Header
  580. var CentralDirectoryLoc64Header = function() {
  581. };
  582. CentralDirectoryLoc64Header.prototype.read = function(data) {
  583. if (data.length != consts.ENDL64HDR || data.readUInt32LE(0) != consts.ENDL64SIG)
  584. throw new Error('Invalid zip64 central directory locator');
  585. // ZIP64 EOCD header offset
  586. this.headerOffset = Util.readUInt64LE(data, consts.ENDSUB);
  587. };
  588. // endregion
  589. // region CentralDirectoryZip64Header
  590. var CentralDirectoryZip64Header = function() {
  591. };
  592. CentralDirectoryZip64Header.prototype.read = function(data) {
  593. if (data.length != consts.END64HDR || data.readUInt32LE(0) != consts.END64SIG)
  594. throw new Error('Invalid central directory');
  595. // number of entries on this volume
  596. this.volumeEntries = Util.readUInt64LE(data, consts.END64SUB);
  597. // total number of entries
  598. this.totalEntries = Util.readUInt64LE(data, consts.END64TOT);
  599. // central directory size in bytes
  600. this.size = Util.readUInt64LE(data, consts.END64SIZ);
  601. // offset of first CEN header
  602. this.offset = Util.readUInt64LE(data, consts.END64OFF);
  603. };
  604. // endregion
  605. // region ZipEntry
  606. var ZipEntry = function() {
  607. };
  608. function toBits(dec, size) {
  609. var b = (dec >>> 0).toString(2);
  610. while (b.length < size)
  611. b = '0' + b;
  612. return b.split('');
  613. }
  614. function parseZipTime(timebytes, datebytes) {
  615. var timebits = toBits(timebytes, 16);
  616. var datebits = toBits(datebytes, 16);
  617. var mt = {
  618. h: parseInt(timebits.slice(0,5).join(''), 2),
  619. m: parseInt(timebits.slice(5,11).join(''), 2),
  620. s: parseInt(timebits.slice(11,16).join(''), 2) * 2,
  621. Y: parseInt(datebits.slice(0,7).join(''), 2) + 1980,
  622. M: parseInt(datebits.slice(7,11).join(''), 2),
  623. D: parseInt(datebits.slice(11,16).join(''), 2),
  624. };
  625. var dt_str = [mt.Y, mt.M, mt.D].join('-') + ' ' + [mt.h, mt.m, mt.s].join(':') + ' GMT+0';
  626. return new Date(dt_str).getTime();
  627. }
  628. ZipEntry.prototype.readHeader = function(data, offset) {
  629. // data should be 46 bytes and start with "PK 01 02"
  630. if (data.length < offset + consts.CENHDR || data.readUInt32LE(offset) != consts.CENSIG) {
  631. throw new Error('Invalid entry header');
  632. }
  633. // version made by
  634. this.verMade = data.readUInt16LE(offset + consts.CENVEM);
  635. // version needed to extract
  636. this.version = data.readUInt16LE(offset + consts.CENVER);
  637. // encrypt, decrypt flags
  638. this.flags = data.readUInt16LE(offset + consts.CENFLG);
  639. // compression method
  640. this.method = data.readUInt16LE(offset + consts.CENHOW);
  641. // modification time (2 bytes time, 2 bytes date)
  642. var timebytes = data.readUInt16LE(offset + consts.CENTIM);
  643. var datebytes = data.readUInt16LE(offset + consts.CENTIM + 2);
  644. this.time = parseZipTime(timebytes, datebytes);
  645. // uncompressed file crc-32 value
  646. this.crc = data.readUInt32LE(offset + consts.CENCRC);
  647. // compressed size
  648. this.compressedSize = data.readUInt32LE(offset + consts.CENSIZ);
  649. // uncompressed size
  650. this.size = data.readUInt32LE(offset + consts.CENLEN);
  651. // filename length
  652. this.fnameLen = data.readUInt16LE(offset + consts.CENNAM);
  653. // extra field length
  654. this.extraLen = data.readUInt16LE(offset + consts.CENEXT);
  655. // file comment length
  656. this.comLen = data.readUInt16LE(offset + consts.CENCOM);
  657. // volume number start
  658. this.diskStart = data.readUInt16LE(offset + consts.CENDSK);
  659. // internal file attributes
  660. this.inattr = data.readUInt16LE(offset + consts.CENATT);
  661. // external file attributes
  662. this.attr = data.readUInt32LE(offset + consts.CENATX);
  663. // LOC header offset
  664. this.offset = data.readUInt32LE(offset + consts.CENOFF);
  665. };
  666. ZipEntry.prototype.readDataHeader = function(data) {
  667. // 30 bytes and should start with "PK\003\004"
  668. if (data.readUInt32LE(0) != consts.LOCSIG) {
  669. throw new Error('Invalid local header');
  670. }
  671. // version needed to extract
  672. this.version = data.readUInt16LE(consts.LOCVER);
  673. // general purpose bit flag
  674. this.flags = data.readUInt16LE(consts.LOCFLG);
  675. // compression method
  676. this.method = data.readUInt16LE(consts.LOCHOW);
  677. // modification time (2 bytes time ; 2 bytes date)
  678. var timebytes = data.readUInt16LE(consts.LOCTIM);
  679. var datebytes = data.readUInt16LE(consts.LOCTIM + 2);
  680. this.time = parseZipTime(timebytes, datebytes);
  681. // uncompressed file crc-32 value
  682. this.crc = data.readUInt32LE(consts.LOCCRC) || this.crc;
  683. // compressed size
  684. var compressedSize = data.readUInt32LE(consts.LOCSIZ);
  685. if (compressedSize && compressedSize !== consts.EF_ZIP64_OR_32) {
  686. this.compressedSize = compressedSize;
  687. }
  688. // uncompressed size
  689. var size = data.readUInt32LE(consts.LOCLEN);
  690. if (size && size !== consts.EF_ZIP64_OR_32) {
  691. this.size = size;
  692. }
  693. // filename length
  694. this.fnameLen = data.readUInt16LE(consts.LOCNAM);
  695. // extra field length
  696. this.extraLen = data.readUInt16LE(consts.LOCEXT);
  697. };
  698. ZipEntry.prototype.read = function(data, offset) {
  699. this.nameRaw = data.slice(offset, offset += this.fnameLen);
  700. this.name = this.nameRaw.toString();
  701. var lastChar = data[offset - 1];
  702. this.isDirectory = (lastChar == 47) || (lastChar == 92);
  703. if (this.extraLen) {
  704. this.readExtra(data, offset);
  705. offset += this.extraLen;
  706. }
  707. this.comment = this.comLen ? data.slice(offset, offset + this.comLen).toString() : null;
  708. };
  709. ZipEntry.prototype.validateName = function() {
  710. if (/\\|^\w+:|^\/|(^|\/)\.\.(\/|$)/.test(this.name)) {
  711. throw new Error('Malicious entry: ' + this.name);
  712. }
  713. };
  714. ZipEntry.prototype.readExtra = function(data, offset) {
  715. var signature, size, maxPos = offset + this.extraLen;
  716. while (offset < maxPos) {
  717. signature = data.readUInt16LE(offset);
  718. offset += 2;
  719. size = data.readUInt16LE(offset);
  720. offset += 2;
  721. if (consts.ID_ZIP64 === signature) {
  722. this.parseZip64Extra(data, offset, size);
  723. }
  724. offset += size;
  725. }
  726. };
  727. ZipEntry.prototype.parseZip64Extra = function(data, offset, length) {
  728. if (length >= 8 && this.size === consts.EF_ZIP64_OR_32) {
  729. this.size = Util.readUInt64LE(data, offset);
  730. offset += 8; length -= 8;
  731. }
  732. if (length >= 8 && this.compressedSize === consts.EF_ZIP64_OR_32) {
  733. this.compressedSize = Util.readUInt64LE(data, offset);
  734. offset += 8; length -= 8;
  735. }
  736. if (length >= 8 && this.offset === consts.EF_ZIP64_OR_32) {
  737. this.offset = Util.readUInt64LE(data, offset);
  738. offset += 8; length -= 8;
  739. }
  740. if (length >= 4 && this.diskStart === consts.EF_ZIP64_OR_16) {
  741. this.diskStart = data.readUInt32LE(offset);
  742. // offset += 4; length -= 4;
  743. }
  744. };
  745. Object.defineProperty(ZipEntry.prototype, 'encrypted', {
  746. get: function() { return (this.flags & consts.FLG_ENTRY_ENC) == consts.FLG_ENTRY_ENC; }
  747. });
  748. Object.defineProperty(ZipEntry.prototype, 'isFile', {
  749. get: function() { return !this.isDirectory; }
  750. });
  751. // endregion
  752. // region FsRead
  753. var FsRead = function(fd, buffer, offset, length, position, callback) {
  754. this.fd = fd;
  755. this.buffer = buffer;
  756. this.offset = offset;
  757. this.length = length;
  758. this.position = position;
  759. this.callback = callback;
  760. this.bytesRead = 0;
  761. this.waiting = false;
  762. };
  763. FsRead.prototype.read = function(sync) {
  764. if (StreamZip.debug) {
  765. console.log('read', this.position, this.bytesRead, this.length, this.offset);
  766. }
  767. this.waiting = true;
  768. var err;
  769. if (sync) {
  770. try {
  771. var bytesRead = fs.readSync(this.fd, this.buffer, this.offset + this.bytesRead,
  772. this.length - this.bytesRead, this.position + this.bytesRead);
  773. } catch (e) {
  774. err = e;
  775. }
  776. this.readCallback(sync, err, err ? bytesRead : null);
  777. } else {
  778. fs.read(this.fd, this.buffer, this.offset + this.bytesRead,
  779. this.length - this.bytesRead, this.position + this.bytesRead,
  780. this.readCallback.bind(this, sync));
  781. }
  782. };
  783. FsRead.prototype.readCallback = function(sync, err, bytesRead) {
  784. if (typeof bytesRead === 'number')
  785. this.bytesRead += bytesRead;
  786. if (err || !bytesRead || this.bytesRead === this.length) {
  787. this.waiting = false;
  788. return this.callback(err, this.bytesRead);
  789. } else {
  790. this.read(sync);
  791. }
  792. };
  793. // endregion
  794. // region FileWindowBuffer
  795. var FileWindowBuffer = function(fd) {
  796. this.position = 0;
  797. this.buffer = Buffer.alloc(0);
  798. var fsOp = null;
  799. this.checkOp = function() {
  800. if (fsOp && fsOp.waiting)
  801. throw new Error('Operation in progress');
  802. };
  803. this.read = function(pos, length, callback) {
  804. this.checkOp();
  805. if (this.buffer.length < length)
  806. this.buffer = Buffer.alloc(length);
  807. this.position = pos;
  808. fsOp = new FsRead(fd, this.buffer, 0, length, this.position, callback).read();
  809. };
  810. this.expandLeft = function(length, callback) {
  811. this.checkOp();
  812. this.buffer = Buffer.concat([Buffer.alloc(length), this.buffer]);
  813. this.position -= length;
  814. if (this.position < 0)
  815. this.position = 0;
  816. fsOp = new FsRead(fd, this.buffer, 0, length, this.position, callback).read();
  817. };
  818. this.expandRight = function(length, callback) {
  819. this.checkOp();
  820. var offset = this.buffer.length;
  821. this.buffer = Buffer.concat([this.buffer, Buffer.alloc(length)]);
  822. fsOp = new FsRead(fd, this.buffer, offset, length, this.position + offset, callback).read();
  823. };
  824. this.moveRight = function(length, callback, shift) {
  825. this.checkOp();
  826. if (shift) {
  827. this.buffer.copy(this.buffer, 0, shift);
  828. } else {
  829. shift = 0;
  830. }
  831. this.position += shift;
  832. fsOp = new FsRead(fd, this.buffer, this.buffer.length - shift, shift, this.position + this.buffer.length - shift, callback).read();
  833. };
  834. };
  835. // endregion
  836. // region EntryDataReaderStream
  837. var EntryDataReaderStream = function(fd, offset, length) {
  838. stream.Readable.prototype.constructor.call(this);
  839. this.fd = fd;
  840. this.offset = offset;
  841. this.length = length;
  842. this.pos = 0;
  843. this.readCallback = this.readCallback.bind(this);
  844. };
  845. util.inherits(EntryDataReaderStream, stream.Readable);
  846. EntryDataReaderStream.prototype._read = function(n) {
  847. var buffer = Buffer.alloc(Math.min(n, this.length - this.pos));
  848. if (buffer.length) {
  849. fs.read(this.fd, buffer, 0, buffer.length, this.offset + this.pos, this.readCallback);
  850. } else {
  851. this.push(null);
  852. }
  853. };
  854. EntryDataReaderStream.prototype.readCallback = function(err, bytesRead, buffer) {
  855. this.pos += bytesRead;
  856. if (err) {
  857. this.emit('error', err);
  858. this.push(null);
  859. } else if (!bytesRead) {
  860. this.push(null);
  861. } else {
  862. if (bytesRead !== buffer.length)
  863. buffer = buffer.slice(0, bytesRead);
  864. this.push(buffer);
  865. }
  866. };
  867. // endregion
  868. // region EntryVerifyStream
  869. var EntryVerifyStream = function(baseStm, crc, size) {
  870. stream.Transform.prototype.constructor.call(this);
  871. this.verify = new CrcVerify(crc, size);
  872. var that = this;
  873. baseStm.on('error', function(e) {
  874. that.emit('error', e);
  875. });
  876. };
  877. util.inherits(EntryVerifyStream, stream.Transform);
  878. EntryVerifyStream.prototype._transform = function(data, encoding, callback) {
  879. var err;
  880. try {
  881. this.verify.data(data);
  882. } catch (e) {
  883. err = e;
  884. }
  885. callback(err, data);
  886. };
  887. // endregion
  888. // region CrcVerify
  889. var CrcVerify = function(crc, size) {
  890. this.crc = crc;
  891. this.size = size;
  892. this.state = {
  893. crc: ~0,
  894. size: 0
  895. };
  896. };
  897. CrcVerify.prototype.data = function(data) {
  898. var crcTable = CrcVerify.getCrcTable();
  899. var crc = this.state.crc, off = 0, len = data.length;
  900. while (--len >= 0)
  901. crc = crcTable[(crc ^ data[off++]) & 0xff] ^ (crc >>> 8);
  902. this.state.crc = crc;
  903. this.state.size += data.length;
  904. if (this.state.size >= this.size) {
  905. var buf = Buffer.alloc(4);
  906. buf.writeInt32LE(~this.state.crc & 0xffffffff, 0);
  907. crc = buf.readUInt32LE(0);
  908. if (crc !== this.crc)
  909. throw new Error('Invalid CRC');
  910. if (this.state.size !== this.size)
  911. throw new Error('Invalid size');
  912. }
  913. };
  914. CrcVerify.getCrcTable = function() {
  915. var crcTable = CrcVerify.crcTable;
  916. if (!crcTable) {
  917. CrcVerify.crcTable = crcTable = [];
  918. var b = Buffer.alloc(4);
  919. for (var n = 0; n < 256; n++) {
  920. var c = n;
  921. for (var k = 8; --k >= 0; )
  922. if ((c & 1) != 0) { c = 0xedb88320 ^ (c >>> 1); } else { c = c >>> 1; }
  923. if (c < 0) {
  924. b.writeInt32LE(c, 0);
  925. c = b.readUInt32LE(0);
  926. }
  927. crcTable[n] = c;
  928. }
  929. }
  930. return crcTable;
  931. };
  932. // endregion
  933. // region Util
  934. var Util = {
  935. readUInt64LE: function(buffer, offset) {
  936. return (buffer.readUInt32LE(offset + 4) * 0x0000000100000000) + buffer.readUInt32LE(offset);
  937. }
  938. };
  939. // endregion
  940. // region exports
  941. module.exports = StreamZip;
  942. // endregion