jsunzip.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /*
  2. * JSUnzip
  3. *
  4. * Copyright (c) 2011 by Erik Moller
  5. * All Rights Reserved
  6. *
  7. * This software is provided 'as-is', without any express
  8. * or implied warranty. In no event will the authors be
  9. * held liable for any damages arising from the use of
  10. * this software.
  11. *
  12. * Permission is granted to anyone to use this software
  13. * for any purpose, including commercial applications,
  14. * and to alter it and redistribute it freely, subject to
  15. * the following restrictions:
  16. *
  17. * 1. The origin of this software must not be
  18. * misrepresented; you must not claim that you
  19. * wrote the original software. If you use this
  20. * software in a product, an acknowledgment in
  21. * the product documentation would be appreciated
  22. * but is not required.
  23. *
  24. * 2. Altered source versions must be plainly marked
  25. * as such, and must not be misrepresented as
  26. * being the original software.
  27. *
  28. * 3. This notice may not be removed or altered from
  29. * any source distribution.
  30. */
  31. var tinf;
  32. function JSUnzip() {
  33. this.getInt = function(offset, size) {
  34. switch (size) {
  35. case 4:
  36. return (this.data.charCodeAt(offset + 3) & 0xff) << 24 |
  37. (this.data.charCodeAt(offset + 2) & 0xff) << 16 |
  38. (this.data.charCodeAt(offset + 1) & 0xff) << 8 |
  39. (this.data.charCodeAt(offset + 0) & 0xff);
  40. break;
  41. case 2:
  42. return (this.data.charCodeAt(offset + 1) & 0xff) << 8 |
  43. (this.data.charCodeAt(offset + 0) & 0xff);
  44. break;
  45. default:
  46. return this.data.charCodeAt(offset) & 0xff;
  47. break;
  48. }
  49. };
  50. this.getDOSDate = function(dosdate, dostime) {
  51. var day = dosdate & 0x1f;
  52. var month = ((dosdate >> 5) & 0xf) - 1;
  53. var year = 1980 + ((dosdate >> 9) & 0x7f)
  54. var second = (dostime & 0x1f) * 2;
  55. var minute = (dostime >> 5) & 0x3f;
  56. hour = (dostime >> 11) & 0x1f;
  57. return new Date(year, month, day, hour, minute, second);
  58. }
  59. this.open = function(data) {
  60. this.data = data;
  61. this.files = [];
  62. if (this.data.length < 22)
  63. return { 'status' : false, 'error' : 'Invalid data' };
  64. var endOfCentralDirectory = this.data.length - 22;
  65. while (endOfCentralDirectory >= 0 && this.getInt(endOfCentralDirectory, 4) != 0x06054b50)
  66. --endOfCentralDirectory;
  67. if (endOfCentralDirectory < 0)
  68. return { 'status' : false, 'error' : 'Invalid data' };
  69. if (this.getInt(endOfCentralDirectory + 4, 2) != 0 || this.getInt(endOfCentralDirectory + 6, 2) != 0)
  70. return { 'status' : false, 'error' : 'No multidisk support' };
  71. var entriesInThisDisk = this.getInt(endOfCentralDirectory + 8, 2);
  72. var centralDirectoryOffset = this.getInt(endOfCentralDirectory + 16, 4);
  73. var globalCommentLength = this.getInt(endOfCentralDirectory + 20, 2);
  74. this.comment = this.data.slice(endOfCentralDirectory + 22, endOfCentralDirectory + 22 + globalCommentLength);
  75. var fileOffset = centralDirectoryOffset;
  76. for (var i = 0; i < entriesInThisDisk; ++i) {
  77. if (this.getInt(fileOffset + 0, 4) != 0x02014b50)
  78. return { 'status' : false, 'error' : 'Invalid data' };
  79. if (this.getInt(fileOffset + 6, 2) > 20)
  80. return { 'status' : false, 'error' : 'Unsupported version' };
  81. if (this.getInt(fileOffset + 8, 2) & 1)
  82. return { 'status' : false, 'error' : 'Encryption not implemented' };
  83. var compressionMethod = this.getInt(fileOffset + 10, 2);
  84. if (compressionMethod != 0 && compressionMethod != 8)
  85. return { 'status' : false, 'error' : 'Unsupported compression method' };
  86. var lastModFileTime = this.getInt(fileOffset + 12, 2);
  87. var lastModFileDate = this.getInt(fileOffset + 14, 2);
  88. var lastModifiedDate = this.getDOSDate(lastModFileDate, lastModFileTime);
  89. var crc = this.getInt(fileOffset + 16, 4);
  90. // TODO: crc
  91. var compressedSize = this.getInt(fileOffset + 20, 4);
  92. var uncompressedSize = this.getInt(fileOffset + 24, 4);
  93. var fileNameLength = this.getInt(fileOffset + 28, 2);
  94. var extraFieldLength = this.getInt(fileOffset + 30, 2);
  95. var fileCommentLength = this.getInt(fileOffset + 32, 2);
  96. var relativeOffsetOfLocalHeader = this.getInt(fileOffset + 42, 4);
  97. var fileName = this.data.slice(fileOffset + 46, fileOffset + 46 + fileNameLength);
  98. var fileComment = this.data.slice(fileOffset + 46 + fileNameLength + extraFieldLength, fileOffset + 46 + fileNameLength + extraFieldLength + fileCommentLength);
  99. if (this.getInt(relativeOffsetOfLocalHeader + 0, 4) != 0x04034b50)
  100. return { 'status' : false, 'error' : 'Invalid data' };
  101. var localFileNameLength = this.getInt(relativeOffsetOfLocalHeader + 26, 2);
  102. var localExtraFieldLength = this.getInt(relativeOffsetOfLocalHeader + 28, 2);
  103. var localFileContent = relativeOffsetOfLocalHeader + 30 + localFileNameLength + localExtraFieldLength;
  104. this.files[fileName] =
  105. {
  106. 'fileComment' : fileComment,
  107. 'compressionMethod' : compressionMethod,
  108. 'compressedSize' : compressedSize,
  109. 'uncompressedSize' : uncompressedSize,
  110. 'localFileContent' : localFileContent,
  111. 'lastModifiedDate' : lastModifiedDate
  112. };
  113. fileOffset += 46 + fileNameLength + extraFieldLength + fileCommentLength;
  114. }
  115. return { 'status' : true }
  116. };
  117. this.read = function(fileName) {
  118. var fileInfo = this.files[fileName];
  119. if (fileInfo) {
  120. if (fileInfo.compressionMethod == 8) {
  121. if (!tinf) {
  122. tinf = new TINF();
  123. tinf.init();
  124. }
  125. var result = tinf.uncompress(this.data, fileInfo.localFileContent);
  126. if (result.status == tinf.OK)
  127. return { 'status' : true, 'data' : result.data };
  128. else
  129. return { 'status' : false, 'error' : result.error };
  130. } else {
  131. return { 'status' : true, 'data' : this.data.slice(fileInfo.localFileContent, fileInfo.localFileContent + fileInfo.uncompressedSize) };
  132. }
  133. }
  134. return { 'status' : false, 'error' : "File '" + fileName + "' doesn't exist in zip" };
  135. };
  136. };
  137. /*
  138. * tinflate - tiny inflate
  139. *
  140. * Copyright (c) 2003 by Joergen Ibsen / Jibz
  141. * All Rights Reserved
  142. *
  143. * http://www.ibsensoftware.com/
  144. *
  145. * This software is provided 'as-is', without any express
  146. * or implied warranty. In no event will the authors be
  147. * held liable for any damages arising from the use of
  148. * this software.
  149. *
  150. * Permission is granted to anyone to use this software
  151. * for any purpose, including commercial applications,
  152. * and to alter it and redistribute it freely, subject to
  153. * the following restrictions:
  154. *
  155. * 1. The origin of this software must not be
  156. * misrepresented; you must not claim that you
  157. * wrote the original software. If you use this
  158. * software in a product, an acknowledgment in
  159. * the product documentation would be appreciated
  160. * but is not required.
  161. *
  162. * 2. Altered source versions must be plainly marked
  163. * as such, and must not be misrepresented as
  164. * being the original software.
  165. *
  166. * 3. This notice may not be removed or altered from
  167. * any source distribution.
  168. */
  169. /*
  170. * tinflate javascript port by Erik Moller in May 2011.
  171. * emoller@opera.com
  172. */
  173. "use strict";
  174. function TINF() {
  175. this.OK = 0;
  176. this.DATA_ERROR = (-3);
  177. this.WINDOW_SIZE = 32768;
  178. /* ------------------------------ *
  179. * -- internal data structures -- *
  180. * ------------------------------ */
  181. this.TREE = function() {
  182. this.table = new Array(16); /* table of code length counts */
  183. this.trans = new Array(288); /* code -> symbol translation table */
  184. };
  185. this.DATA = function(that) {
  186. this.source = '';
  187. this.sourceIndex = 0;
  188. this.tag = 0;
  189. this.bitcount = 0;
  190. this.dest = [];
  191. this.history = [];
  192. this.ltree = new that.TREE(); /* dynamic length/symbol tree */
  193. this.dtree = new that.TREE(); /* dynamic distance tree */
  194. };
  195. /* --------------------------------------------------- *
  196. * -- uninitialized global data (static structures) -- *
  197. * --------------------------------------------------- */
  198. this.sltree = new this.TREE(); /* fixed length/symbol tree */
  199. this.sdtree = new this.TREE(); /* fixed distance tree */
  200. /* extra bits and base tables for length codes */
  201. this.length_bits = new Array(30);
  202. this.length_base = new Array(30);
  203. /* extra bits and base tables for distance codes */
  204. this.dist_bits = new Array(30);
  205. this.dist_base = new Array(30);
  206. /* special ordering of code length codes */
  207. this.clcidx = [
  208. 16, 17, 18, 0, 8, 7, 9, 6,
  209. 10, 5, 11, 4, 12, 3, 13, 2,
  210. 14, 1, 15
  211. ];
  212. /* ----------------------- *
  213. * -- utility functions -- *
  214. * ----------------------- */
  215. /* build extra bits and base tables */
  216. this.build_bits_base = function(bits, base, delta, first)
  217. {
  218. var i, sum;
  219. /* build bits table */
  220. for (i = 0; i < delta; ++i) bits[i] = 0;
  221. for (i = 0; i < 30 - delta; ++i) bits[i + delta] = Math.floor(i / delta);
  222. /* build base table */
  223. for (sum = first, i = 0; i < 30; ++i)
  224. {
  225. base[i] = sum;
  226. sum += 1 << bits[i];
  227. }
  228. }
  229. /* build the fixed huffman trees */
  230. this.build_fixed_trees = function(lt, dt)
  231. {
  232. var i;
  233. /* build fixed length tree */
  234. for (i = 0; i < 7; ++i) lt.table[i] = 0;
  235. lt.table[7] = 24;
  236. lt.table[8] = 152;
  237. lt.table[9] = 112;
  238. for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i;
  239. for (i = 0; i < 144; ++i) lt.trans[24 + i] = i;
  240. for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i;
  241. for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i;
  242. /* build fixed distance tree */
  243. for (i = 0; i < 5; ++i) dt.table[i] = 0;
  244. dt.table[5] = 32;
  245. for (i = 0; i < 32; ++i) dt.trans[i] = i;
  246. }
  247. /* given an array of code lengths, build a tree */
  248. this.build_tree = function(t, lengths, loffset, num)
  249. {
  250. var offs = new Array(16);
  251. var i, sum;
  252. /* clear code length count table */
  253. for (i = 0; i < 16; ++i) t.table[i] = 0;
  254. /* scan symbol lengths, and sum code length counts */
  255. for (i = 0; i < num; ++i) t.table[lengths[loffset + i]]++;
  256. t.table[0] = 0;
  257. /* compute offset table for distribution sort */
  258. for (sum = 0, i = 0; i < 16; ++i)
  259. {
  260. offs[i] = sum;
  261. sum += t.table[i];
  262. }
  263. /* create code->symbol translation table (symbols sorted by code) */
  264. for (i = 0; i < num; ++i)
  265. {
  266. if (lengths[loffset + i]) t.trans[offs[lengths[loffset + i]]++] = i;
  267. }
  268. }
  269. /* ---------------------- *
  270. * -- decode functions -- *
  271. * ---------------------- */
  272. /* get one bit from source stream */
  273. this.getbit = function(d)
  274. {
  275. var bit;
  276. /* check if tag is empty */
  277. if (!d.bitcount--)
  278. {
  279. /* load next tag */
  280. d.tag = d.source.charCodeAt(d.sourceIndex++) & 0xff;
  281. d.bitcount = 7;
  282. }
  283. /* shift bit out of tag */
  284. bit = d.tag & 0x01;
  285. d.tag >>= 1;
  286. return bit;
  287. }
  288. /* read a num bit value from a stream and add base */
  289. this.read_bits = function(d, num, base)
  290. {
  291. if (!num)
  292. return base;
  293. var val = 0;
  294. while (d.bitcount < 24) {
  295. d.tag = d.tag | (d.source.charCodeAt(d.sourceIndex++) & 0xff) << d.bitcount;
  296. d.bitcount += 8;
  297. }
  298. val = d.tag & (0xff >> (8 - num));
  299. d.tag >>= num;
  300. d.bitcount -= num;
  301. return val + base;
  302. }
  303. /* given a data stream and a tree, decode a symbol */
  304. this.decode_symbol = function(d, t)
  305. {
  306. while (d.bitcount < 24) {
  307. d.tag = d.tag | (d.source.charCodeAt(d.sourceIndex++) & 0xff) << d.bitcount;
  308. d.bitcount += 8;
  309. }
  310. var sum = 0, cur = 0, len = 0;
  311. do {
  312. cur = 2 * cur + ((d.tag & (1 << len)) >> len);
  313. ++len;
  314. sum += t.table[len];
  315. cur -= t.table[len];
  316. } while (cur >= 0);
  317. d.tag >>= len;
  318. d.bitcount -= len;
  319. return t.trans[sum + cur];
  320. }
  321. /* given a data stream, decode dynamic trees from it */
  322. this.decode_trees = function(d, lt, dt)
  323. {
  324. var code_tree = new this.TREE();
  325. var lengths = new Array(288+32);
  326. var hlit, hdist, hclen;
  327. var i, num, length;
  328. /* get 5 bits HLIT (257-286) */
  329. hlit = this.read_bits(d, 5, 257);
  330. /* get 5 bits HDIST (1-32) */
  331. hdist = this.read_bits(d, 5, 1);
  332. /* get 4 bits HCLEN (4-19) */
  333. hclen = this.read_bits(d, 4, 4);
  334. for (i = 0; i < 19; ++i) lengths[i] = 0;
  335. /* read code lengths for code length alphabet */
  336. for (i = 0; i < hclen; ++i)
  337. {
  338. /* get 3 bits code length (0-7) */
  339. var clen = this.read_bits(d, 3, 0);
  340. lengths[this.clcidx[i]] = clen;
  341. }
  342. /* build code length tree */
  343. this.build_tree(code_tree, lengths, 0, 19);
  344. /* decode code lengths for the dynamic trees */
  345. for (num = 0; num < hlit + hdist; )
  346. {
  347. var sym = this.decode_symbol(d, code_tree);
  348. switch (sym)
  349. {
  350. case 16:
  351. /* copy previous code length 3-6 times (read 2 bits) */
  352. {
  353. var prev = lengths[num - 1];
  354. for (length = this.read_bits(d, 2, 3); length; --length)
  355. {
  356. lengths[num++] = prev;
  357. }
  358. }
  359. break;
  360. case 17:
  361. /* repeat code length 0 for 3-10 times (read 3 bits) */
  362. for (length = this.read_bits(d, 3, 3); length; --length)
  363. {
  364. lengths[num++] = 0;
  365. }
  366. break;
  367. case 18:
  368. /* repeat code length 0 for 11-138 times (read 7 bits) */
  369. for (length = this.read_bits(d, 7, 11); length; --length)
  370. {
  371. lengths[num++] = 0;
  372. }
  373. break;
  374. default:
  375. /* values 0-15 represent the actual code lengths */
  376. lengths[num++] = sym;
  377. break;
  378. }
  379. }
  380. /* build dynamic trees */
  381. this.build_tree(lt, lengths, 0, hlit);
  382. this.build_tree(dt, lengths, hlit, hdist);
  383. }
  384. /* ----------------------------- *
  385. * -- block inflate functions -- *
  386. * ----------------------------- */
  387. /* given a stream and two trees, inflate a block of data */
  388. this.inflate_block_data = function(d, lt, dt)
  389. {
  390. // js optimization.
  391. var ddest = d.dest;
  392. var ddestlength = ddest.length;
  393. while (1)
  394. {
  395. var sym = this.decode_symbol(d, lt);
  396. /* check for end of block */
  397. if (sym == 256)
  398. {
  399. return this.OK;
  400. }
  401. if (sym < 256)
  402. {
  403. ddest[ddestlength++] = sym; // ? String.fromCharCode(sym);
  404. } else {
  405. var length, dist, offs;
  406. var i;
  407. sym -= 257;
  408. /* possibly get more bits from length code */
  409. length = this.read_bits(d, this.length_bits[sym], this.length_base[sym]);
  410. dist = this.decode_symbol(d, dt);
  411. /* possibly get more bits from distance code */
  412. offs = ddestlength - this.read_bits(d, this.dist_bits[dist], this.dist_base[dist]);
  413. /* copy match */
  414. for (i = offs; i < offs + length; ++i) {
  415. if (i < 0)
  416. ddest[ddestlength++] = d.history[d.history.length + i];
  417. else
  418. ddest[ddestlength++] = ddest[i];
  419. }
  420. }
  421. }
  422. }
  423. /* inflate an uncompressed block of data */
  424. this.inflate_uncompressed_block = function(d)
  425. {
  426. var length, invlength;
  427. var i;
  428. if (d.bitcount > 7) {
  429. var overflow = Math.floor(d.bitcount / 8);
  430. d.sourceIndex -= overflow;
  431. d.bitcount = 0;
  432. d.tag = 0;
  433. }
  434. /* get length */
  435. length = d.source[d.sourceIndex+1];
  436. length = 256*length + d.source[d.sourceIndex];
  437. /* get one's complement of length */
  438. invlength = d.source[d.sourceIndex+3];
  439. invlength = 256*invlength + d.source[d.sourceIndex+2];
  440. /* check length */
  441. if (length != (~invlength & 0x0000ffff)) return this.DATA_ERROR;
  442. d.sourceIndex += 4;
  443. /* copy block */
  444. for (i = length; i; --i)
  445. d.dest[d.dest.length] = d.source[d.sourceIndex++];
  446. /* make sure we start next block on a byte boundary */
  447. d.bitcount = 0;
  448. return this.OK;
  449. }
  450. /* inflate a block of data compressed with fixed huffman trees */
  451. this.inflate_fixed_block = function(d)
  452. {
  453. /* decode block using fixed trees */
  454. return this.inflate_block_data(d, this.sltree, this.sdtree);
  455. }
  456. /* inflate a block of data compressed with dynamic huffman trees */
  457. this.inflate_dynamic_block = function(d)
  458. {
  459. /* decode trees from stream */
  460. this.decode_trees(d, d.ltree, d.dtree);
  461. /* decode block using decoded trees */
  462. return this.inflate_block_data(d, d.ltree, d.dtree);
  463. }
  464. /* ---------------------- *
  465. * -- public functions -- *
  466. * ---------------------- */
  467. /* initialize global (static) data */
  468. this.init = function()
  469. {
  470. /* build fixed huffman trees */
  471. this.build_fixed_trees(this.sltree, this.sdtree);
  472. /* build extra bits and base tables */
  473. this.build_bits_base(this.length_bits, this.length_base, 4, 3);
  474. this.build_bits_base(this.dist_bits, this.dist_base, 2, 1);
  475. /* fix a special case */
  476. this.length_bits[28] = 0;
  477. this.length_base[28] = 258;
  478. this.reset();
  479. }
  480. this.reset = function()
  481. {
  482. this.d = new this.DATA(this);
  483. delete this.header;
  484. }
  485. /* inflate stream from source to dest */
  486. this.uncompress = function(source, offset)
  487. {
  488. var d = this.d;
  489. var bfinal;
  490. if (Object.prototype.toString.call(source) === '[object Array]') {
  491. source.charCodeAt = function(id) { return this[id]; }
  492. }
  493. /* initialise data */
  494. d.source = source;
  495. d.sourceIndex = offset;
  496. d.bitcount = 0;
  497. d.dest = [];
  498. // Skip zlib header at start of stream
  499. if (typeof this.header == 'undefined') {
  500. this.header = this.read_bits(d, 16, 0);
  501. /* byte 0: 0x78, 7 = 32k window size, 8 = deflate */
  502. /* byte 1: check bits for header and other flags */
  503. }
  504. var blocks = 0;
  505. do {
  506. var btype;
  507. var res;
  508. /* read final block flag */
  509. bfinal = this.getbit(d);
  510. /* read block type (2 bits) */
  511. btype = this.read_bits(d, 2, 0);
  512. /* decompress block */
  513. switch (btype)
  514. {
  515. case 0:
  516. /* decompress uncompressed block */
  517. res = this.inflate_uncompressed_block(d);
  518. break;
  519. case 1:
  520. /* decompress block with fixed huffman trees */
  521. res = this.inflate_fixed_block(d);
  522. break;
  523. case 2:
  524. /* decompress block with dynamic huffman trees */
  525. res = this.inflate_dynamic_block(d);
  526. break;
  527. default:
  528. return { 'status' : this.DATA_ERROR };
  529. }
  530. if (res != this.OK) return { 'status' : this.DATA_ERROR };
  531. blocks++;
  532. } while (!bfinal && d.sourceIndex < d.source.length);
  533. if (blocks != 2) throw ("Unexpected number of blocks");
  534. if (Object.prototype.toString.call(source) !== '[object Array]') {
  535. d.dest = d.dest.join('');
  536. }
  537. else {
  538. d.history.push.apply(d.history, d.dest);
  539. d.history = d.history.slice(-this.WINDOW_SIZE);
  540. }
  541. return { 'status' : this.OK, 'data' : d.dest };
  542. }
  543. };