ZipUtils.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2016 Chukong Technologies Inc.
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. http://www.cocos2d-x.org
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. THE SOFTWARE.
  21. ****************************************************************************/
  22. #include "base/ZipUtils.h"
  23. #ifdef MINIZIP_FROM_SYSTEM
  24. #include <minizip/unzip.h>
  25. #else // from our embedded sources
  26. #include "unzip.h"
  27. #endif
  28. #include "ioapi_mem.h"
  29. #include <memory>
  30. #include <zlib.h>
  31. #include <assert.h>
  32. #include <stdlib.h>
  33. #include <set>
  34. #include "base/CCData.h"
  35. #include "base/ccMacros.h"
  36. #include "platform/CCFileUtils.h"
  37. #include <map>
  38. // minizip 1.2.0 is same with other platforms
  39. #define unzGoToFirstFile64(A,B,C,D) unzGoToFirstFile2(A,B,C,D, NULL, 0, NULL, 0)
  40. #define unzGoToNextFile64(A,B,C,D) unzGoToNextFile2(A,B,C,D, NULL, 0, NULL, 0)
  41. NS_CC_BEGIN
  42. unsigned int ZipUtils::s_uEncryptedPvrKeyParts[4] = {0,0,0,0};
  43. unsigned int ZipUtils::s_uEncryptionKey[1024];
  44. bool ZipUtils::s_bEncryptionKeyIsValid = false;
  45. // --------------------- ZipUtils ---------------------
  46. inline void ZipUtils::decodeEncodedPvr(unsigned int *data, ssize_t len)
  47. {
  48. const int enclen = 1024;
  49. const int securelen = 512;
  50. const int distance = 64;
  51. // check if key was set
  52. // make sure to call caw_setkey_part() for all 4 key parts
  53. CCASSERT(s_uEncryptedPvrKeyParts[0] != 0, "Cocos2D: CCZ file is encrypted but key part 0 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
  54. CCASSERT(s_uEncryptedPvrKeyParts[1] != 0, "Cocos2D: CCZ file is encrypted but key part 1 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
  55. CCASSERT(s_uEncryptedPvrKeyParts[2] != 0, "Cocos2D: CCZ file is encrypted but key part 2 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
  56. CCASSERT(s_uEncryptedPvrKeyParts[3] != 0, "Cocos2D: CCZ file is encrypted but key part 3 is not set. Did you call ZipUtils::setPvrEncryptionKeyPart(...)?");
  57. // create long key
  58. if(!s_bEncryptionKeyIsValid)
  59. {
  60. unsigned int y, p, e;
  61. unsigned int rounds = 6;
  62. unsigned int sum = 0;
  63. unsigned int z = s_uEncryptionKey[enclen-1];
  64. do
  65. {
  66. #define DELTA 0x9e3779b9
  67. #define MX (((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (s_uEncryptedPvrKeyParts[(p&3)^e] ^ z)))
  68. sum += DELTA;
  69. e = (sum >> 2) & 3;
  70. for (p = 0; p < enclen - 1; p++)
  71. {
  72. y = s_uEncryptionKey[p + 1];
  73. z = s_uEncryptionKey[p] += MX;
  74. }
  75. y = s_uEncryptionKey[0];
  76. z = s_uEncryptionKey[enclen - 1] += MX;
  77. } while (--rounds);
  78. s_bEncryptionKeyIsValid = true;
  79. }
  80. int b = 0;
  81. int i = 0;
  82. // encrypt first part completely
  83. for(; i < len && i < securelen; i++)
  84. {
  85. data[i] ^= s_uEncryptionKey[b++];
  86. if(b >= enclen)
  87. {
  88. b = 0;
  89. }
  90. }
  91. // encrypt second section partially
  92. for(; i < len; i += distance)
  93. {
  94. data[i] ^= s_uEncryptionKey[b++];
  95. if(b >= enclen)
  96. {
  97. b = 0;
  98. }
  99. }
  100. }
  101. inline unsigned int ZipUtils::checksumPvr(const unsigned int *data, ssize_t len)
  102. {
  103. unsigned int cs = 0;
  104. const int cslen = 128;
  105. len = (len < cslen) ? len : cslen;
  106. for(int i = 0; i < len; i++)
  107. {
  108. cs = cs ^ data[i];
  109. }
  110. return cs;
  111. }
  112. // memory in iPhone is precious
  113. // Should buffer factor be 1.5 instead of 2 ?
  114. #define BUFFER_INC_FACTOR (2)
  115. int ZipUtils::inflateMemoryWithHint(unsigned char *in, ssize_t inLength, unsigned char **out, ssize_t *outLength, ssize_t outLengthHint)
  116. {
  117. /* ret value */
  118. int err = Z_OK;
  119. ssize_t bufferSize = outLengthHint;
  120. *out = (unsigned char*)malloc(bufferSize);
  121. z_stream d_stream; /* decompression stream */
  122. d_stream.zalloc = (alloc_func)0;
  123. d_stream.zfree = (free_func)0;
  124. d_stream.opaque = (voidpf)0;
  125. d_stream.next_in = in;
  126. d_stream.avail_in = static_cast<unsigned int>(inLength);
  127. d_stream.next_out = *out;
  128. d_stream.avail_out = static_cast<unsigned int>(bufferSize);
  129. /* window size to hold 256k */
  130. if( (err = inflateInit2(&d_stream, 15 + 32)) != Z_OK )
  131. return err;
  132. for (;;)
  133. {
  134. err = inflate(&d_stream, Z_NO_FLUSH);
  135. if (err == Z_STREAM_END)
  136. {
  137. break;
  138. }
  139. switch (err)
  140. {
  141. case Z_NEED_DICT:
  142. err = Z_DATA_ERROR;
  143. case Z_DATA_ERROR:
  144. case Z_MEM_ERROR:
  145. inflateEnd(&d_stream);
  146. return err;
  147. }
  148. // not enough memory ?
  149. if (err != Z_STREAM_END)
  150. {
  151. *out = (unsigned char*)realloc(*out, bufferSize * BUFFER_INC_FACTOR);
  152. /* not enough memory, ouch */
  153. if (! *out )
  154. {
  155. CCLOG("cocos2d: ZipUtils: realloc failed");
  156. inflateEnd(&d_stream);
  157. return Z_MEM_ERROR;
  158. }
  159. d_stream.next_out = *out + bufferSize;
  160. d_stream.avail_out = static_cast<unsigned int>(bufferSize);
  161. bufferSize *= BUFFER_INC_FACTOR;
  162. }
  163. }
  164. *outLength = bufferSize - d_stream.avail_out;
  165. err = inflateEnd(&d_stream);
  166. return err;
  167. }
  168. ssize_t ZipUtils::inflateMemoryWithHint(unsigned char *in, ssize_t inLength, unsigned char **out, ssize_t outLengthHint)
  169. {
  170. ssize_t outLength = 0;
  171. int err = inflateMemoryWithHint(in, inLength, out, &outLength, outLengthHint);
  172. if (err != Z_OK || *out == nullptr) {
  173. if (err == Z_MEM_ERROR)
  174. {
  175. CCLOG("cocos2d: ZipUtils: Out of memory while decompressing map data!");
  176. } else
  177. if (err == Z_VERSION_ERROR)
  178. {
  179. CCLOG("cocos2d: ZipUtils: Incompatible zlib version!");
  180. } else
  181. if (err == Z_DATA_ERROR)
  182. {
  183. CCLOG("cocos2d: ZipUtils: Incorrect zlib compressed data!");
  184. }
  185. else
  186. {
  187. CCLOG("cocos2d: ZipUtils: Unknown error while decompressing map data!");
  188. }
  189. if(*out) {
  190. free(*out);
  191. *out = nullptr;
  192. }
  193. outLength = 0;
  194. }
  195. return outLength;
  196. }
  197. ssize_t ZipUtils::inflateMemory(unsigned char *in, ssize_t inLength, unsigned char **out)
  198. {
  199. // 256k for hint
  200. return inflateMemoryWithHint(in, inLength, out, 256 * 1024);
  201. }
  202. int ZipUtils::inflateGZipFile(const char *path, unsigned char **out)
  203. {
  204. int len;
  205. unsigned int offset = 0;
  206. CCASSERT(out, "out can't be nullptr.");
  207. CCASSERT(&*out, "&*out can't be nullptr.");
  208. gzFile inFile = gzopen(FileUtils::getInstance()->getSuitableFOpen(path).c_str(), "rb");
  209. if( inFile == nullptr ) {
  210. CCLOG("cocos2d: ZipUtils: error open gzip file: %s", path);
  211. return -1;
  212. }
  213. /* 512k initial decompress buffer */
  214. unsigned int bufferSize = 512 * 1024;
  215. unsigned int totalBufferSize = bufferSize;
  216. *out = (unsigned char*)malloc( bufferSize );
  217. if(*out == NULL)
  218. {
  219. CCLOG("cocos2d: ZipUtils: out of memory");
  220. return -1;
  221. }
  222. for (;;) {
  223. len = gzread(inFile, *out + offset, bufferSize);
  224. if (len < 0)
  225. {
  226. CCLOG("cocos2d: ZipUtils: error in gzread");
  227. free( *out );
  228. *out = nullptr;
  229. return -1;
  230. }
  231. if (len == 0)
  232. {
  233. break;
  234. }
  235. offset += len;
  236. // finish reading the file
  237. if( (unsigned int)len < bufferSize )
  238. {
  239. break;
  240. }
  241. bufferSize *= BUFFER_INC_FACTOR;
  242. totalBufferSize += bufferSize;
  243. unsigned char *tmp = (unsigned char*)realloc(*out, totalBufferSize );
  244. if( ! tmp )
  245. {
  246. CCLOG("cocos2d: ZipUtils: out of memory");
  247. free( *out );
  248. *out = nullptr;
  249. return -1;
  250. }
  251. *out = tmp;
  252. }
  253. if (gzclose(inFile) != Z_OK)
  254. {
  255. CCLOG("cocos2d: ZipUtils: gzclose failed");
  256. }
  257. return offset;
  258. }
  259. bool ZipUtils::isCCZFile(const char *path)
  260. {
  261. // load file into memory
  262. Data compressedData = FileUtils::getInstance()->getDataFromFile(path);
  263. if (compressedData.isNull())
  264. {
  265. CCLOG("cocos2d: ZipUtils: loading file failed");
  266. return false;
  267. }
  268. return isCCZBuffer(compressedData.getBytes(), compressedData.getSize());
  269. }
  270. bool ZipUtils::isCCZBuffer(const unsigned char *buffer, ssize_t len)
  271. {
  272. if (static_cast<size_t>(len) < sizeof(struct CCZHeader))
  273. {
  274. return false;
  275. }
  276. struct CCZHeader *header = (struct CCZHeader*) buffer;
  277. return header->sig[0] == 'C' && header->sig[1] == 'C' && header->sig[2] == 'Z' && (header->sig[3] == '!' || header->sig[3] == 'p');
  278. }
  279. bool ZipUtils::isGZipFile(const char *path)
  280. {
  281. // load file into memory
  282. Data compressedData = FileUtils::getInstance()->getDataFromFile(path);
  283. if (compressedData.isNull())
  284. {
  285. CCLOG("cocos2d: ZipUtils: loading file failed");
  286. return false;
  287. }
  288. return isGZipBuffer(compressedData.getBytes(), compressedData.getSize());
  289. }
  290. bool ZipUtils::isGZipBuffer(const unsigned char *buffer, ssize_t len)
  291. {
  292. if (len < 2)
  293. {
  294. return false;
  295. }
  296. return buffer[0] == 0x1F && buffer[1] == 0x8B;
  297. }
  298. int ZipUtils::inflateCCZBuffer(const unsigned char *buffer, ssize_t bufferLen, unsigned char **out)
  299. {
  300. struct CCZHeader *header = (struct CCZHeader*) buffer;
  301. // verify header
  302. if( header->sig[0] == 'C' && header->sig[1] == 'C' && header->sig[2] == 'Z' && header->sig[3] == '!' )
  303. {
  304. // verify header version
  305. unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version );
  306. if( version > 2 )
  307. {
  308. CCLOG("cocos2d: Unsupported CCZ header format");
  309. return -1;
  310. }
  311. // verify compression format
  312. if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB )
  313. {
  314. CCLOG("cocos2d: CCZ Unsupported compression method");
  315. return -1;
  316. }
  317. }
  318. else if( header->sig[0] == 'C' && header->sig[1] == 'C' && header->sig[2] == 'Z' && header->sig[3] == 'p' )
  319. {
  320. // encrypted ccz file
  321. header = (struct CCZHeader*) buffer;
  322. // verify header version
  323. unsigned int version = CC_SWAP_INT16_BIG_TO_HOST( header->version );
  324. if( version > 0 )
  325. {
  326. CCLOG("cocos2d: Unsupported CCZ header format");
  327. return -1;
  328. }
  329. // verify compression format
  330. if( CC_SWAP_INT16_BIG_TO_HOST(header->compression_type) != CCZ_COMPRESSION_ZLIB )
  331. {
  332. CCLOG("cocos2d: CCZ Unsupported compression method");
  333. return -1;
  334. }
  335. // decrypt
  336. unsigned int* ints = (unsigned int*)(buffer+12);
  337. ssize_t enclen = (bufferLen-12)/4;
  338. decodeEncodedPvr(ints, enclen);
  339. #if COCOS2D_DEBUG > 0
  340. // verify checksum in debug mode
  341. unsigned int calculated = checksumPvr(ints, enclen);
  342. unsigned int required = CC_SWAP_INT32_BIG_TO_HOST( header->reserved );
  343. if(calculated != required)
  344. {
  345. CCLOG("cocos2d: Can't decrypt image file. Is the decryption key valid?");
  346. return -1;
  347. }
  348. #endif
  349. }
  350. else
  351. {
  352. CCLOG("cocos2d: Invalid CCZ file");
  353. return -1;
  354. }
  355. unsigned int len = CC_SWAP_INT32_BIG_TO_HOST( header->len );
  356. *out = (unsigned char*)malloc( len );
  357. if(! *out )
  358. {
  359. CCLOG("cocos2d: CCZ: Failed to allocate memory for texture");
  360. return -1;
  361. }
  362. unsigned long destlen = len;
  363. size_t source = (size_t) buffer + sizeof(*header);
  364. int ret = uncompress(*out, &destlen, (Bytef*)source, bufferLen - sizeof(*header) );
  365. if( ret != Z_OK )
  366. {
  367. CCLOG("cocos2d: CCZ: Failed to uncompress data");
  368. free( *out );
  369. *out = nullptr;
  370. return -1;
  371. }
  372. return len;
  373. }
  374. int ZipUtils::inflateCCZFile(const char *path, unsigned char **out)
  375. {
  376. CCASSERT(out, "Invalid pointer for buffer!");
  377. // load file into memory
  378. Data compressedData = FileUtils::getInstance()->getDataFromFile(path);
  379. if (compressedData.isNull())
  380. {
  381. CCLOG("cocos2d: Error loading CCZ compressed file");
  382. return -1;
  383. }
  384. return inflateCCZBuffer(compressedData.getBytes(), compressedData.getSize(), out);
  385. }
  386. void ZipUtils::setPvrEncryptionKeyPart(int index, unsigned int value)
  387. {
  388. CCASSERT(index >= 0, "Cocos2d: key part index cannot be less than 0");
  389. CCASSERT(index <= 3, "Cocos2d: key part index cannot be greater than 3");
  390. if(s_uEncryptedPvrKeyParts[index] != value)
  391. {
  392. s_uEncryptedPvrKeyParts[index] = value;
  393. s_bEncryptionKeyIsValid = false;
  394. }
  395. }
  396. void ZipUtils::setPvrEncryptionKey(unsigned int keyPart1, unsigned int keyPart2, unsigned int keyPart3, unsigned int keyPart4)
  397. {
  398. setPvrEncryptionKeyPart(0, keyPart1);
  399. setPvrEncryptionKeyPart(1, keyPart2);
  400. setPvrEncryptionKeyPart(2, keyPart3);
  401. setPvrEncryptionKeyPart(3, keyPart4);
  402. }
  403. // --------------------- ZipFile ---------------------
  404. // from unzip.cpp
  405. #define UNZ_MAXFILENAMEINZIP 256
  406. static const std::string emptyFilename("");
  407. struct ZipEntryInfo
  408. {
  409. unz_file_pos pos;
  410. uLong uncompressed_size;
  411. };
  412. class ZipFilePrivate
  413. {
  414. public:
  415. unzFile zipFile;
  416. std::unique_ptr<ourmemory_s> memfs;
  417. // std::unordered_map is faster if available on the platform
  418. typedef std::unordered_map<std::string, struct ZipEntryInfo> FileListContainer;
  419. FileListContainer fileList;
  420. };
  421. ZipFile *ZipFile::createWithBuffer(const void* buffer, uLong size)
  422. {
  423. ZipFile *zip = new (std::nothrow) ZipFile();
  424. if (zip && zip->initWithBuffer(buffer, size)) {
  425. return zip;
  426. } else {
  427. delete zip;
  428. return nullptr;
  429. }
  430. }
  431. ZipFile::ZipFile()
  432. : _data(new ZipFilePrivate)
  433. {
  434. _data->zipFile = nullptr;
  435. }
  436. ZipFile::ZipFile(const std::string &zipFile, const std::string &filter)
  437. : _data(new ZipFilePrivate)
  438. {
  439. _data->zipFile = unzOpen(FileUtils::getInstance()->getSuitableFOpen(zipFile).c_str());
  440. setFilter(filter);
  441. }
  442. ZipFile::~ZipFile()
  443. {
  444. if (_data && _data->zipFile)
  445. {
  446. unzClose(_data->zipFile);
  447. }
  448. CC_SAFE_DELETE(_data);
  449. }
  450. bool ZipFile::setFilter(const std::string &filter)
  451. {
  452. bool ret = false;
  453. do
  454. {
  455. CC_BREAK_IF(!_data);
  456. CC_BREAK_IF(!_data->zipFile);
  457. // clear existing file list
  458. _data->fileList.clear();
  459. // UNZ_MAXFILENAMEINZIP + 1 - it is done so in unzLocateFile
  460. char szCurrentFileName[UNZ_MAXFILENAMEINZIP + 1];
  461. unz_file_info64 fileInfo;
  462. // go through all files and store position information about the required files
  463. int err = unzGoToFirstFile64(_data->zipFile, &fileInfo,
  464. szCurrentFileName, sizeof(szCurrentFileName) - 1);
  465. while (err == UNZ_OK)
  466. {
  467. unz_file_pos posInfo;
  468. int posErr = unzGetFilePos(_data->zipFile, &posInfo);
  469. if (posErr == UNZ_OK)
  470. {
  471. std::string currentFileName = szCurrentFileName;
  472. // cache info about filtered files only (like 'assets/')
  473. if (filter.empty()
  474. || currentFileName.substr(0, filter.length()) == filter)
  475. {
  476. ZipEntryInfo entry;
  477. entry.pos = posInfo;
  478. entry.uncompressed_size = (uLong)fileInfo.uncompressed_size;
  479. _data->fileList[currentFileName] = entry;
  480. }
  481. }
  482. // next file - also get the information about it
  483. err = unzGoToNextFile64(_data->zipFile, &fileInfo,
  484. szCurrentFileName, sizeof(szCurrentFileName) - 1);
  485. }
  486. ret = true;
  487. } while(false);
  488. return ret;
  489. }
  490. bool ZipFile::fileExists(const std::string &fileName) const
  491. {
  492. bool ret = false;
  493. do
  494. {
  495. CC_BREAK_IF(!_data);
  496. ret = _data->fileList.find(fileName) != _data->fileList.end();
  497. } while(false);
  498. return ret;
  499. }
  500. std::vector<std::string> ZipFile::listFiles(const std::string &pathname) const
  501. {
  502. // filter files which `filename.startsWith(pathname)`
  503. // then make each path unique
  504. std::set<std::string> fileSet;
  505. ZipFilePrivate::FileListContainer::const_iterator it = _data->fileList.begin();
  506. ZipFilePrivate::FileListContainer::const_iterator end = _data->fileList.end();
  507. //ensure pathname ends with `/` as a directory
  508. std::string dirname = pathname[pathname.length() -1] == '/' ? pathname : pathname + "/";
  509. while(it != end)
  510. {
  511. const std::string &filename = it->first;
  512. if(filename.substr(0, dirname.length()) == dirname)
  513. {
  514. std::string suffix = filename.substr(dirname.length());
  515. auto pos = suffix.find('/');
  516. if (pos == std::string::npos)
  517. {
  518. fileSet.insert(suffix);
  519. }
  520. else {
  521. //fileSet.insert(parts[0] + "/");
  522. fileSet.insert(suffix.substr(0, pos + 1));
  523. }
  524. }
  525. it++;
  526. }
  527. return std::vector<std::string>(fileSet.begin(), fileSet.end());
  528. }
  529. unsigned char *ZipFile::getFileData(const std::string &fileName, ssize_t *size)
  530. {
  531. unsigned char * buffer = nullptr;
  532. if (size)
  533. *size = 0;
  534. do
  535. {
  536. CC_BREAK_IF(!_data->zipFile);
  537. CC_BREAK_IF(fileName.empty());
  538. ZipFilePrivate::FileListContainer::const_iterator it = _data->fileList.find(fileName);
  539. CC_BREAK_IF(it == _data->fileList.end());
  540. ZipEntryInfo fileInfo = it->second;
  541. int nRet = unzGoToFilePos(_data->zipFile, &fileInfo.pos);
  542. CC_BREAK_IF(UNZ_OK != nRet);
  543. nRet = unzOpenCurrentFile(_data->zipFile);
  544. CC_BREAK_IF(UNZ_OK != nRet);
  545. buffer = (unsigned char*)malloc(fileInfo.uncompressed_size);
  546. int CC_UNUSED nSize = unzReadCurrentFile(_data->zipFile, buffer, static_cast<unsigned int>(fileInfo.uncompressed_size));
  547. CCASSERT(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
  548. if (size)
  549. {
  550. *size = fileInfo.uncompressed_size;
  551. }
  552. unzCloseCurrentFile(_data->zipFile);
  553. } while (0);
  554. return buffer;
  555. }
  556. bool ZipFile::getFileData(const std::string &fileName, ResizableBuffer* buffer)
  557. {
  558. bool res = false;
  559. do
  560. {
  561. CC_BREAK_IF(!_data->zipFile);
  562. CC_BREAK_IF(fileName.empty());
  563. ZipFilePrivate::FileListContainer::const_iterator it = _data->fileList.find(fileName);
  564. CC_BREAK_IF(it == _data->fileList.end());
  565. ZipEntryInfo fileInfo = it->second;
  566. int nRet = unzGoToFilePos(_data->zipFile, &fileInfo.pos);
  567. CC_BREAK_IF(UNZ_OK != nRet);
  568. nRet = unzOpenCurrentFile(_data->zipFile);
  569. CC_BREAK_IF(UNZ_OK != nRet);
  570. buffer->resize(fileInfo.uncompressed_size);
  571. int CC_UNUSED nSize = unzReadCurrentFile(_data->zipFile, buffer->buffer(), static_cast<unsigned int>(fileInfo.uncompressed_size));
  572. CCASSERT(nSize == 0 || nSize == (int)fileInfo.uncompressed_size, "the file size is wrong");
  573. unzCloseCurrentFile(_data->zipFile);
  574. res = true;
  575. } while (0);
  576. return res;
  577. }
  578. std::string ZipFile::getFirstFilename()
  579. {
  580. if (unzGoToFirstFile(_data->zipFile) != UNZ_OK) return emptyFilename;
  581. std::string path;
  582. unz_file_info info;
  583. getCurrentFileInfo(&path, &info);
  584. return path;
  585. }
  586. std::string ZipFile::getNextFilename()
  587. {
  588. if (unzGoToNextFile(_data->zipFile) != UNZ_OK) return emptyFilename;
  589. std::string path;
  590. unz_file_info info;
  591. getCurrentFileInfo(&path, &info);
  592. return path;
  593. }
  594. int ZipFile::getCurrentFileInfo(std::string *filename, unz_file_info *info)
  595. {
  596. char path[FILENAME_MAX + 1];
  597. int ret = unzGetCurrentFileInfo(_data->zipFile, info, path, sizeof(path), nullptr, 0, nullptr, 0);
  598. if (ret != UNZ_OK) {
  599. *filename = emptyFilename;
  600. } else {
  601. filename->assign(path);
  602. }
  603. return ret;
  604. }
  605. bool ZipFile::initWithBuffer(const void *buffer, uLong size)
  606. {
  607. if (!buffer || size == 0) return false;
  608. zlib_filefunc_def memory_file = { 0 };
  609. std::unique_ptr<ourmemory_t> memfs(new(std::nothrow) ourmemory_t{ (char*)const_cast<void*>(buffer), static_cast<uint32_t>(size), 0, 0, 0 });
  610. if (!memfs) return false;
  611. fill_memory_filefunc(&memory_file, memfs.get());
  612. _data->zipFile = unzOpen2(nullptr, &memory_file);
  613. if (!_data->zipFile) return false;
  614. _data->memfs = std::move(memfs);
  615. setFilter(emptyFilename);
  616. return true;
  617. }
  618. NS_CC_END