jsunzip.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. * read_bits() patched by mike@imidio.com to allow
  174. * reading more then 8 bits (needed in some zlib streams)
  175. */
  176. "use strict";
  177. function TINF() {
  178. this.OK = 0;
  179. this.DATA_ERROR = (-3);
  180. this.WINDOW_SIZE = 32768;
  181. /* ------------------------------ *
  182. * -- internal data structures -- *
  183. * ------------------------------ */
  184. this.TREE = function() {
  185. this.table = new Array(16); /* table of code length counts */
  186. this.trans = new Array(288); /* code -> symbol translation table */
  187. };
  188. this.DATA = function(that) {
  189. this.source = '';
  190. this.sourceIndex = 0;
  191. this.tag = 0;
  192. this.bitcount = 0;
  193. this.dest = [];
  194. this.history = [];
  195. this.ltree = new that.TREE(); /* dynamic length/symbol tree */
  196. this.dtree = new that.TREE(); /* dynamic distance tree */
  197. };
  198. /* --------------------------------------------------- *
  199. * -- uninitialized global data (static structures) -- *
  200. * --------------------------------------------------- */
  201. this.sltree = new this.TREE(); /* fixed length/symbol tree */
  202. this.sdtree = new this.TREE(); /* fixed distance tree */
  203. /* extra bits and base tables for length codes */
  204. this.length_bits = new Array(30);
  205. this.length_base = new Array(30);
  206. /* extra bits and base tables for distance codes */
  207. this.dist_bits = new Array(30);
  208. this.dist_base = new Array(30);
  209. /* special ordering of code length codes */
  210. this.clcidx = [
  211. 16, 17, 18, 0, 8, 7, 9, 6,
  212. 10, 5, 11, 4, 12, 3, 13, 2,
  213. 14, 1, 15
  214. ];
  215. /* ----------------------- *
  216. * -- utility functions -- *
  217. * ----------------------- */
  218. /* build extra bits and base tables */
  219. this.build_bits_base = function(bits, base, delta, first)
  220. {
  221. var i, sum;
  222. /* build bits table */
  223. for (i = 0; i < delta; ++i) bits[i] = 0;
  224. for (i = 0; i < 30 - delta; ++i) bits[i + delta] = Math.floor(i / delta);
  225. /* build base table */
  226. for (sum = first, i = 0; i < 30; ++i)
  227. {
  228. base[i] = sum;
  229. sum += 1 << bits[i];
  230. }
  231. }
  232. /* build the fixed huffman trees */
  233. this.build_fixed_trees = function(lt, dt)
  234. {
  235. var i;
  236. /* build fixed length tree */
  237. for (i = 0; i < 7; ++i) lt.table[i] = 0;
  238. lt.table[7] = 24;
  239. lt.table[8] = 152;
  240. lt.table[9] = 112;
  241. for (i = 0; i < 24; ++i) lt.trans[i] = 256 + i;
  242. for (i = 0; i < 144; ++i) lt.trans[24 + i] = i;
  243. for (i = 0; i < 8; ++i) lt.trans[24 + 144 + i] = 280 + i;
  244. for (i = 0; i < 112; ++i) lt.trans[24 + 144 + 8 + i] = 144 + i;
  245. /* build fixed distance tree */
  246. for (i = 0; i < 5; ++i) dt.table[i] = 0;
  247. dt.table[5] = 32;
  248. for (i = 0; i < 32; ++i) dt.trans[i] = i;
  249. }
  250. /* given an array of code lengths, build a tree */
  251. this.build_tree = function(t, lengths, loffset, num)
  252. {
  253. var offs = new Array(16);
  254. var i, sum;
  255. /* clear code length count table */
  256. for (i = 0; i < 16; ++i) t.table[i] = 0;
  257. /* scan symbol lengths, and sum code length counts */
  258. for (i = 0; i < num; ++i) t.table[lengths[loffset + i]]++;
  259. t.table[0] = 0;
  260. /* compute offset table for distribution sort */
  261. for (sum = 0, i = 0; i < 16; ++i)
  262. {
  263. offs[i] = sum;
  264. sum += t.table[i];
  265. }
  266. /* create code->symbol translation table (symbols sorted by code) */
  267. for (i = 0; i < num; ++i)
  268. {
  269. if (lengths[loffset + i]) t.trans[offs[lengths[loffset + i]]++] = i;
  270. }
  271. }
  272. /* ---------------------- *
  273. * -- decode functions -- *
  274. * ---------------------- */
  275. /* get one bit from source stream */
  276. this.getbit = function(d)
  277. {
  278. var bit;
  279. /* check if tag is empty */
  280. if (!d.bitcount--)
  281. {
  282. /* load next tag */
  283. d.tag = d.source[d.sourceIndex++] & 0xff;
  284. d.bitcount = 7;
  285. }
  286. /* shift bit out of tag */
  287. bit = d.tag & 0x01;
  288. d.tag >>= 1;
  289. return bit;
  290. }
  291. /* read a num bit value from a stream and add base */
  292. function read_bits_direct(source, bitcount, tag, idx, num)
  293. {
  294. var val = 0;
  295. while (bitcount < 24) {
  296. tag = tag | (source[idx++] & 0xff) << bitcount;
  297. bitcount += 8;
  298. }
  299. val = tag & (0xffff >> (16 - num));
  300. tag >>= num;
  301. bitcount -= num;
  302. return [bitcount, tag, idx, val];
  303. }
  304. this.read_bits = function(d, num, base)
  305. {
  306. if (!num)
  307. return base;
  308. var ret = read_bits_direct(d.source, d.bitcount, d.tag, d.sourceIndex, num);
  309. d.bitcount = ret[0];
  310. d.tag = ret[1];
  311. d.sourceIndex = ret[2];
  312. return ret[3] + base;
  313. }
  314. /* given a data stream and a tree, decode a symbol */
  315. this.decode_symbol = function(d, t)
  316. {
  317. while (d.bitcount < 16) {
  318. d.tag = d.tag | (d.source[d.sourceIndex++] & 0xff) << d.bitcount;
  319. d.bitcount += 8;
  320. }
  321. var sum = 0, cur = 0, len = 0;
  322. do {
  323. cur = 2 * cur + ((d.tag & (1 << len)) >> len);
  324. ++len;
  325. sum += t.table[len];
  326. cur -= t.table[len];
  327. } while (cur >= 0);
  328. d.tag >>= len;
  329. d.bitcount -= len;
  330. return t.trans[sum + cur];
  331. }
  332. /* given a data stream, decode dynamic trees from it */
  333. this.decode_trees = function(d, lt, dt)
  334. {
  335. var code_tree = new this.TREE();
  336. var lengths = new Array(288+32);
  337. var hlit, hdist, hclen;
  338. var i, num, length;
  339. /* get 5 bits HLIT (257-286) */
  340. hlit = this.read_bits(d, 5, 257);
  341. /* get 5 bits HDIST (1-32) */
  342. hdist = this.read_bits(d, 5, 1);
  343. /* get 4 bits HCLEN (4-19) */
  344. hclen = this.read_bits(d, 4, 4);
  345. for (i = 0; i < 19; ++i) lengths[i] = 0;
  346. /* read code lengths for code length alphabet */
  347. for (i = 0; i < hclen; ++i)
  348. {
  349. /* get 3 bits code length (0-7) */
  350. var clen = this.read_bits(d, 3, 0);
  351. lengths[this.clcidx[i]] = clen;
  352. }
  353. /* build code length tree */
  354. this.build_tree(code_tree, lengths, 0, 19);
  355. /* decode code lengths for the dynamic trees */
  356. for (num = 0; num < hlit + hdist; )
  357. {
  358. var sym = this.decode_symbol(d, code_tree);
  359. switch (sym)
  360. {
  361. case 16:
  362. /* copy previous code length 3-6 times (read 2 bits) */
  363. {
  364. var prev = lengths[num - 1];
  365. for (length = this.read_bits(d, 2, 3); length; --length)
  366. {
  367. lengths[num++] = prev;
  368. }
  369. }
  370. break;
  371. case 17:
  372. /* repeat code length 0 for 3-10 times (read 3 bits) */
  373. for (length = this.read_bits(d, 3, 3); length; --length)
  374. {
  375. lengths[num++] = 0;
  376. }
  377. break;
  378. case 18:
  379. /* repeat code length 0 for 11-138 times (read 7 bits) */
  380. for (length = this.read_bits(d, 7, 11); length; --length)
  381. {
  382. lengths[num++] = 0;
  383. }
  384. break;
  385. default:
  386. /* values 0-15 represent the actual code lengths */
  387. lengths[num++] = sym;
  388. break;
  389. }
  390. }
  391. /* build dynamic trees */
  392. this.build_tree(lt, lengths, 0, hlit);
  393. this.build_tree(dt, lengths, hlit, hdist);
  394. }
  395. /* ----------------------------- *
  396. * -- block inflate functions -- *
  397. * ----------------------------- */
  398. /* given a stream and two trees, inflate a block of data */
  399. this.inflate_block_data = function(d, lt, dt)
  400. {
  401. // js optimization.
  402. var ddest = d.dest;
  403. var ddestlength = ddest.length;
  404. while (1)
  405. {
  406. var sym = this.decode_symbol(d, lt);
  407. /* check for end of block */
  408. if (sym == 256)
  409. {
  410. return this.OK;
  411. }
  412. if (sym < 256)
  413. {
  414. ddest[ddestlength++] = sym; // ? String.fromCharCode(sym);
  415. d.history.push(sym);
  416. } else {
  417. var length, dist, offs;
  418. var i;
  419. sym -= 257;
  420. /* possibly get more bits from length code */
  421. length = this.read_bits(d, this.length_bits[sym], this.length_base[sym]);
  422. dist = this.decode_symbol(d, dt);
  423. /* possibly get more bits from distance code */
  424. offs = d.history.length - this.read_bits(d, this.dist_bits[dist], this.dist_base[dist]);
  425. if (offs < 0)
  426. throw ("Invalid zlib offset " + offs);
  427. /* copy match */
  428. for (i = offs; i < offs + length; ++i) {
  429. //ddest[ddestlength++] = ddest[i];
  430. ddest[ddestlength++] = d.history[i];
  431. d.history.push(d.history[i]);
  432. }
  433. }
  434. }
  435. }
  436. /* inflate an uncompressed block of data */
  437. this.inflate_uncompressed_block = function(d)
  438. {
  439. var length, invlength;
  440. var i;
  441. if (d.bitcount > 7) {
  442. var overflow = Math.floor(d.bitcount / 8);
  443. d.sourceIndex -= overflow;
  444. d.bitcount = 0;
  445. d.tag = 0;
  446. }
  447. /* get length */
  448. length = d.source[d.sourceIndex+1];
  449. length = 256*length + d.source[d.sourceIndex];
  450. /* get one's complement of length */
  451. invlength = d.source[d.sourceIndex+3];
  452. invlength = 256*invlength + d.source[d.sourceIndex+2];
  453. /* check length */
  454. if (length != (~invlength & 0x0000ffff)) return this.DATA_ERROR;
  455. d.sourceIndex += 4;
  456. /* copy block */
  457. for (i = length; i; --i) {
  458. d.history.push(d.source[d.sourceIndex]);
  459. d.dest[d.dest.length] = d.source[d.sourceIndex++];
  460. }
  461. /* make sure we start next block on a byte boundary */
  462. d.bitcount = 0;
  463. return this.OK;
  464. }
  465. /* inflate a block of data compressed with fixed huffman trees */
  466. this.inflate_fixed_block = function(d)
  467. {
  468. /* decode block using fixed trees */
  469. return this.inflate_block_data(d, this.sltree, this.sdtree);
  470. }
  471. /* inflate a block of data compressed with dynamic huffman trees */
  472. this.inflate_dynamic_block = function(d)
  473. {
  474. /* decode trees from stream */
  475. this.decode_trees(d, d.ltree, d.dtree);
  476. /* decode block using decoded trees */
  477. return this.inflate_block_data(d, d.ltree, d.dtree);
  478. }
  479. /* ---------------------- *
  480. * -- public functions -- *
  481. * ---------------------- */
  482. /* initialize global (static) data */
  483. this.init = function()
  484. {
  485. /* build fixed huffman trees */
  486. this.build_fixed_trees(this.sltree, this.sdtree);
  487. /* build extra bits and base tables */
  488. this.build_bits_base(this.length_bits, this.length_base, 4, 3);
  489. this.build_bits_base(this.dist_bits, this.dist_base, 2, 1);
  490. /* fix a special case */
  491. this.length_bits[28] = 0;
  492. this.length_base[28] = 258;
  493. this.reset();
  494. }
  495. this.reset = function()
  496. {
  497. this.d = new this.DATA(this);
  498. delete this.header;
  499. }
  500. /* inflate stream from source to dest */
  501. this.uncompress = function(source, offset)
  502. {
  503. var d = this.d;
  504. var bfinal;
  505. /* initialise data */
  506. d.source = source;
  507. d.sourceIndex = offset;
  508. d.bitcount = 0;
  509. d.dest = [];
  510. // Skip zlib header at start of stream
  511. if (typeof this.header == 'undefined') {
  512. this.header = this.read_bits(d, 16, 0);
  513. /* byte 0: 0x78, 7 = 32k window size, 8 = deflate */
  514. /* byte 1: check bits for header and other flags */
  515. }
  516. var blocks = 0;
  517. do {
  518. var btype;
  519. var res;
  520. /* read final block flag */
  521. bfinal = this.getbit(d);
  522. /* read block type (2 bits) */
  523. btype = this.read_bits(d, 2, 0);
  524. /* decompress block */
  525. switch (btype)
  526. {
  527. case 0:
  528. /* decompress uncompressed block */
  529. res = this.inflate_uncompressed_block(d);
  530. break;
  531. case 1:
  532. /* decompress block with fixed huffman trees */
  533. res = this.inflate_fixed_block(d);
  534. break;
  535. case 2:
  536. /* decompress block with dynamic huffman trees */
  537. res = this.inflate_dynamic_block(d);
  538. break;
  539. default:
  540. return { 'status' : this.DATA_ERROR };
  541. }
  542. if (res != this.OK) return { 'status' : this.DATA_ERROR };
  543. blocks++;
  544. } while (!bfinal && d.sourceIndex < d.source.length);
  545. d.history = d.history.slice(-this.WINDOW_SIZE);
  546. return { 'status' : this.OK, 'data' : d.dest };
  547. }
  548. };