ZipArchiveIOSystem.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file ZipArchiveIOSystem.cpp
  34. * @brief Zip File I/O implementation for #Importer
  35. */
  36. #include <assimp/BaseImporter.h>
  37. #include <assimp/ZipArchiveIOSystem.h>
  38. #include <assimp/ai_assert.h>
  39. #include <map>
  40. #include <memory>
  41. #ifdef ASSIMP_USE_HUNTER
  42. # include <minizip/unzip.h>
  43. #else
  44. # include <unzip.h>
  45. #endif
  46. namespace Assimp {
  47. // ----------------------------------------------------------------
  48. // Wraps an existing Assimp::IOSystem for unzip
  49. class IOSystem2Unzip {
  50. public:
  51. static voidpf open(voidpf opaque, const char *filename, int mode);
  52. static uLong read(voidpf opaque, voidpf stream, void *buf, uLong size);
  53. static uLong write(voidpf opaque, voidpf stream, const void *buf, uLong size);
  54. static long tell(voidpf opaque, voidpf stream);
  55. static long seek(voidpf opaque, voidpf stream, uLong offset, int origin);
  56. static int close(voidpf opaque, voidpf stream);
  57. static int testerror(voidpf opaque, voidpf stream);
  58. static zlib_filefunc_def get(IOSystem *pIOHandler);
  59. };
  60. voidpf IOSystem2Unzip::open(voidpf opaque, const char *filename, int mode) {
  61. IOSystem *io_system = reinterpret_cast<IOSystem *>(opaque);
  62. const char *mode_fopen = nullptr;
  63. if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) {
  64. mode_fopen = "rb";
  65. } else {
  66. if (mode & ZLIB_FILEFUNC_MODE_EXISTING) {
  67. mode_fopen = "r+b";
  68. } else {
  69. if (mode & ZLIB_FILEFUNC_MODE_CREATE) {
  70. mode_fopen = "wb";
  71. }
  72. }
  73. }
  74. return (voidpf)io_system->Open(filename, mode_fopen);
  75. }
  76. uLong IOSystem2Unzip::read(voidpf /*opaque*/, voidpf stream, void *buf, uLong size) {
  77. IOStream *io_stream = (IOStream *)stream;
  78. return static_cast<uLong>(io_stream->Read(buf, 1, size));
  79. }
  80. uLong IOSystem2Unzip::write(voidpf /*opaque*/, voidpf stream, const void *buf, uLong size) {
  81. IOStream *io_stream = (IOStream *)stream;
  82. return static_cast<uLong>(io_stream->Write(buf, 1, size));
  83. }
  84. long IOSystem2Unzip::tell(voidpf /*opaque*/, voidpf stream) {
  85. IOStream *io_stream = (IOStream *)stream;
  86. return static_cast<long>(io_stream->Tell());
  87. }
  88. long IOSystem2Unzip::seek(voidpf /*opaque*/, voidpf stream, uLong offset, int origin) {
  89. IOStream *io_stream = (IOStream *)stream;
  90. aiOrigin assimp_origin;
  91. switch (origin) {
  92. default:
  93. case ZLIB_FILEFUNC_SEEK_CUR:
  94. assimp_origin = aiOrigin_CUR;
  95. break;
  96. case ZLIB_FILEFUNC_SEEK_END:
  97. assimp_origin = aiOrigin_END;
  98. break;
  99. case ZLIB_FILEFUNC_SEEK_SET:
  100. assimp_origin = aiOrigin_SET;
  101. break;
  102. }
  103. return (io_stream->Seek(offset, assimp_origin) == aiReturn_SUCCESS ? 0 : -1);
  104. }
  105. int IOSystem2Unzip::close(voidpf opaque, voidpf stream) {
  106. IOSystem *io_system = (IOSystem *)opaque;
  107. IOStream *io_stream = (IOStream *)stream;
  108. io_system->Close(io_stream);
  109. return 0;
  110. }
  111. int IOSystem2Unzip::testerror(voidpf /*opaque*/, voidpf /*stream*/) {
  112. return 0;
  113. }
  114. zlib_filefunc_def IOSystem2Unzip::get(IOSystem *pIOHandler) {
  115. zlib_filefunc_def mapping;
  116. mapping.zopen_file = (open_file_func)open;
  117. mapping.zread_file = (read_file_func)read;
  118. mapping.zwrite_file = (write_file_func)write;
  119. mapping.ztell_file = (tell_file_func)tell;
  120. mapping.zseek_file = (seek_file_func)seek;
  121. mapping.zclose_file = (close_file_func)close;
  122. mapping.zerror_file = (error_file_func)testerror;
  123. mapping.opaque = reinterpret_cast<voidpf>(pIOHandler);
  124. return mapping;
  125. }
  126. // ----------------------------------------------------------------
  127. // A read-only file inside a ZIP
  128. class ZipFile : public IOStream {
  129. friend class ZipFileInfo;
  130. explicit ZipFile(size_t size);
  131. public:
  132. virtual ~ZipFile();
  133. // IOStream interface
  134. size_t Read(void *pvBuffer, size_t pSize, size_t pCount) override;
  135. size_t Write(const void * /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/) override { return 0; }
  136. size_t FileSize() const override;
  137. aiReturn Seek(size_t pOffset, aiOrigin pOrigin) override;
  138. size_t Tell() const override;
  139. void Flush() override {}
  140. private:
  141. size_t m_Size = 0;
  142. size_t m_SeekPtr = 0;
  143. std::unique_ptr<uint8_t[]> m_Buffer;
  144. };
  145. // ----------------------------------------------------------------
  146. // Info about a read-only file inside a ZIP
  147. class ZipFileInfo {
  148. public:
  149. explicit ZipFileInfo(unzFile zip_handle, size_t size);
  150. // Allocate and Extract data from the ZIP
  151. ZipFile *Extract(unzFile zip_handle) const;
  152. private:
  153. size_t m_Size = 0;
  154. unz_file_pos_s m_ZipFilePos;
  155. };
  156. ZipFileInfo::ZipFileInfo(unzFile zip_handle, size_t size) :
  157. m_Size(size) {
  158. ai_assert(m_Size != 0);
  159. // Workaround for MSVC 2013 - C2797
  160. m_ZipFilePos.num_of_file = 0;
  161. m_ZipFilePos.pos_in_zip_directory = 0;
  162. unzGetFilePos(zip_handle, &(m_ZipFilePos));
  163. }
  164. ZipFile *ZipFileInfo::Extract(unzFile zip_handle) const {
  165. // Find in the ZIP. This cannot fail
  166. unz_file_pos_s *filepos = const_cast<unz_file_pos_s *>(&(m_ZipFilePos));
  167. if (unzGoToFilePos(zip_handle, filepos) != UNZ_OK)
  168. return nullptr;
  169. if (unzOpenCurrentFile(zip_handle) != UNZ_OK)
  170. return nullptr;
  171. ZipFile *zip_file = new ZipFile(m_Size);
  172. // Unzip has a limit of UINT16_MAX bytes buffer
  173. uint16_t unzipBufferSize = zip_file->m_Size <= UINT16_MAX ? static_cast<uint16_t>(zip_file->m_Size) : UINT16_MAX;
  174. std::unique_ptr<uint8_t[]> unzipBuffer = std::unique_ptr<uint8_t[]>(new uint8_t[unzipBufferSize]);
  175. size_t readCount = 0;
  176. while (readCount < zip_file->m_Size)
  177. {
  178. size_t bufferSize = zip_file->m_Size - readCount;
  179. if (bufferSize > UINT16_MAX) {
  180. bufferSize = UINT16_MAX;
  181. }
  182. int ret = unzReadCurrentFile(zip_handle, unzipBuffer.get(), static_cast<unsigned int>(bufferSize));
  183. if (ret != static_cast<int>(bufferSize))
  184. {
  185. // Failed, release the memory
  186. delete zip_file;
  187. zip_file = nullptr;
  188. break;
  189. }
  190. std::memcpy(zip_file->m_Buffer.get() + readCount, unzipBuffer.get(), ret);
  191. readCount += ret;
  192. }
  193. ai_assert(unzCloseCurrentFile(zip_handle) == UNZ_OK);
  194. return zip_file;
  195. }
  196. ZipFile::ZipFile(size_t size) :
  197. m_Size(size) {
  198. ai_assert(m_Size != 0);
  199. m_Buffer = std::unique_ptr<uint8_t[]>(new uint8_t[m_Size]);
  200. }
  201. ZipFile::~ZipFile() {
  202. }
  203. size_t ZipFile::Read(void *pvBuffer, size_t pSize, size_t pCount) {
  204. // Should be impossible
  205. ai_assert(m_Buffer != nullptr);
  206. ai_assert(nullptr != pvBuffer);
  207. ai_assert(0 != pSize);
  208. ai_assert(0 != pCount);
  209. // Clip down to file size
  210. size_t byteSize = pSize * pCount;
  211. if ((byteSize + m_SeekPtr) > m_Size) {
  212. pCount = (m_Size - m_SeekPtr) / pSize;
  213. byteSize = pSize * pCount;
  214. if (byteSize == 0) {
  215. return 0;
  216. }
  217. }
  218. std::memcpy(pvBuffer, m_Buffer.get() + m_SeekPtr, byteSize);
  219. m_SeekPtr += byteSize;
  220. return pCount;
  221. }
  222. size_t ZipFile::FileSize() const {
  223. return m_Size;
  224. }
  225. aiReturn ZipFile::Seek(size_t pOffset, aiOrigin pOrigin) {
  226. switch (pOrigin) {
  227. case aiOrigin_SET: {
  228. if (pOffset > m_Size) return aiReturn_FAILURE;
  229. m_SeekPtr = pOffset;
  230. return aiReturn_SUCCESS;
  231. }
  232. case aiOrigin_CUR: {
  233. if ((pOffset + m_SeekPtr) > m_Size) return aiReturn_FAILURE;
  234. m_SeekPtr += pOffset;
  235. return aiReturn_SUCCESS;
  236. }
  237. case aiOrigin_END: {
  238. if (pOffset > m_Size) return aiReturn_FAILURE;
  239. m_SeekPtr = m_Size - pOffset;
  240. return aiReturn_SUCCESS;
  241. }
  242. default:;
  243. }
  244. return aiReturn_FAILURE;
  245. }
  246. size_t ZipFile::Tell() const {
  247. return m_SeekPtr;
  248. }
  249. // ----------------------------------------------------------------
  250. // pImpl of the Zip Archive IO
  251. class ZipArchiveIOSystem::Implement {
  252. public:
  253. static const unsigned int FileNameSize = 256;
  254. Implement(IOSystem *pIOHandler, const char *pFilename, const char *pMode);
  255. ~Implement();
  256. bool isOpen() const;
  257. void getFileList(std::vector<std::string> &rFileList);
  258. void getFileListExtension(std::vector<std::string> &rFileList, const std::string &extension);
  259. bool Exists(std::string &filename);
  260. IOStream *OpenFile(std::string &filename);
  261. static void SimplifyFilename(std::string &filename);
  262. private:
  263. void MapArchive();
  264. private:
  265. typedef std::map<std::string, ZipFileInfo> ZipFileInfoMap;
  266. unzFile m_ZipFileHandle = nullptr;
  267. ZipFileInfoMap m_ArchiveMap;
  268. };
  269. ZipArchiveIOSystem::Implement::Implement(IOSystem *pIOHandler, const char *pFilename, const char *pMode) {
  270. ai_assert(strcmp(pMode, "r") == 0);
  271. ai_assert(pFilename != nullptr);
  272. if (pFilename[0] == 0 || nullptr == pMode) {
  273. return;
  274. }
  275. zlib_filefunc_def mapping = IOSystem2Unzip::get(pIOHandler);
  276. m_ZipFileHandle = unzOpen2(pFilename, &mapping);
  277. }
  278. ZipArchiveIOSystem::Implement::~Implement() {
  279. if (m_ZipFileHandle != nullptr) {
  280. unzClose(m_ZipFileHandle);
  281. m_ZipFileHandle = nullptr;
  282. }
  283. }
  284. void ZipArchiveIOSystem::Implement::MapArchive() {
  285. if (m_ZipFileHandle == nullptr)
  286. return;
  287. if (!m_ArchiveMap.empty())
  288. return;
  289. // At first ensure file is already open
  290. if (unzGoToFirstFile(m_ZipFileHandle) != UNZ_OK)
  291. return;
  292. // Loop over all files
  293. do {
  294. char filename[FileNameSize];
  295. unz_file_info fileInfo;
  296. if (unzGetCurrentFileInfo(m_ZipFileHandle, &fileInfo, filename, FileNameSize, nullptr, 0, nullptr, 0) == UNZ_OK) {
  297. if (fileInfo.uncompressed_size != 0) {
  298. std::string filename_string(filename, fileInfo.size_filename);
  299. SimplifyFilename(filename_string);
  300. m_ArchiveMap.emplace(filename_string, ZipFileInfo(m_ZipFileHandle, fileInfo.uncompressed_size));
  301. }
  302. }
  303. } while (unzGoToNextFile(m_ZipFileHandle) != UNZ_END_OF_LIST_OF_FILE);
  304. }
  305. bool ZipArchiveIOSystem::Implement::isOpen() const {
  306. return (m_ZipFileHandle != nullptr);
  307. }
  308. void ZipArchiveIOSystem::Implement::getFileList(std::vector<std::string> &rFileList) {
  309. MapArchive();
  310. rFileList.clear();
  311. for (const auto &file : m_ArchiveMap) {
  312. rFileList.push_back(file.first);
  313. }
  314. }
  315. void ZipArchiveIOSystem::Implement::getFileListExtension(std::vector<std::string> &rFileList, const std::string &extension) {
  316. MapArchive();
  317. rFileList.clear();
  318. for (const auto &file : m_ArchiveMap) {
  319. if (extension == BaseImporter::GetExtension(file.first))
  320. rFileList.push_back(file.first);
  321. }
  322. }
  323. bool ZipArchiveIOSystem::Implement::Exists(std::string &filename) {
  324. MapArchive();
  325. ZipFileInfoMap::const_iterator it = m_ArchiveMap.find(filename);
  326. return (it != m_ArchiveMap.end());
  327. }
  328. IOStream *ZipArchiveIOSystem::Implement::OpenFile(std::string &filename) {
  329. MapArchive();
  330. SimplifyFilename(filename);
  331. // Find in the map
  332. ZipFileInfoMap::const_iterator zip_it = m_ArchiveMap.find(filename);
  333. if (zip_it == m_ArchiveMap.cend())
  334. return nullptr;
  335. const ZipFileInfo &zip_file = (*zip_it).second;
  336. return zip_file.Extract(m_ZipFileHandle);
  337. }
  338. inline void ReplaceAll(std::string &data, const std::string &before, const std::string &after) {
  339. size_t pos = data.find(before);
  340. while (pos != std::string::npos) {
  341. data.replace(pos, before.size(), after);
  342. pos = data.find(before, pos + after.size());
  343. }
  344. }
  345. inline void ReplaceAllChar(std::string &data, const char before, const char after) {
  346. size_t pos = data.find(before);
  347. while (pos != std::string::npos) {
  348. data[pos] = after;
  349. pos = data.find(before, pos + 1);
  350. }
  351. }
  352. void ZipArchiveIOSystem::Implement::SimplifyFilename(std::string &filename) {
  353. ReplaceAllChar(filename, '\\', '/');
  354. // Remove all . and / from the beginning of the path
  355. size_t pos = filename.find_first_not_of("./");
  356. if (pos != 0)
  357. filename.erase(0, pos);
  358. // Simplify "my/folder/../file.png" constructions, if any
  359. static const std::string relative("/../");
  360. const size_t relsize = relative.size() - 1;
  361. pos = filename.find(relative);
  362. while (pos != std::string::npos) {
  363. // Previous slash
  364. size_t prevpos = filename.rfind('/', pos - 1);
  365. if (prevpos == pos)
  366. filename.erase(0, pos + relative.size());
  367. else
  368. filename.erase(prevpos, pos + relsize - prevpos);
  369. pos = filename.find(relative);
  370. }
  371. }
  372. ZipArchiveIOSystem::ZipArchiveIOSystem(IOSystem *pIOHandler, const char *pFilename, const char *pMode) :
  373. pImpl(new Implement(pIOHandler, pFilename, pMode)) {
  374. }
  375. // ----------------------------------------------------------------
  376. // The ZipArchiveIO
  377. ZipArchiveIOSystem::ZipArchiveIOSystem(IOSystem *pIOHandler, const std::string &rFilename, const char *pMode) :
  378. pImpl(new Implement(pIOHandler, rFilename.c_str(), pMode)) {
  379. }
  380. ZipArchiveIOSystem::~ZipArchiveIOSystem() {
  381. delete pImpl;
  382. }
  383. bool ZipArchiveIOSystem::Exists(const char *pFilename) const {
  384. ai_assert(pFilename != nullptr);
  385. if (pFilename == nullptr) {
  386. return false;
  387. }
  388. std::string filename(pFilename);
  389. return pImpl->Exists(filename);
  390. }
  391. // This is always '/' in a ZIP
  392. char ZipArchiveIOSystem::getOsSeparator() const {
  393. return '/';
  394. }
  395. // Only supports Reading
  396. IOStream *ZipArchiveIOSystem::Open(const char *pFilename, const char *pMode) {
  397. ai_assert(pFilename != nullptr);
  398. for (size_t i = 0; pMode[i] != 0; ++i) {
  399. ai_assert(pMode[i] != 'w');
  400. if (pMode[i] == 'w')
  401. return nullptr;
  402. }
  403. std::string filename(pFilename);
  404. return pImpl->OpenFile(filename);
  405. }
  406. void ZipArchiveIOSystem::Close(IOStream *pFile) {
  407. delete pFile;
  408. }
  409. bool ZipArchiveIOSystem::isOpen() const {
  410. return (pImpl->isOpen());
  411. }
  412. void ZipArchiveIOSystem::getFileList(std::vector<std::string> &rFileList) const {
  413. return pImpl->getFileList(rFileList);
  414. }
  415. void ZipArchiveIOSystem::getFileListExtension(std::vector<std::string> &rFileList, const std::string &extension) const {
  416. return pImpl->getFileListExtension(rFileList, extension);
  417. }
  418. bool ZipArchiveIOSystem::isZipArchive(IOSystem *pIOHandler, const char *pFilename) {
  419. Implement tmp(pIOHandler, pFilename, "r");
  420. return tmp.isOpen();
  421. }
  422. bool ZipArchiveIOSystem::isZipArchive(IOSystem *pIOHandler, const std::string &rFilename) {
  423. return isZipArchive(pIOHandler, rFilename.c_str());
  424. }
  425. } // namespace Assimp