The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

664 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. inline uint16 readUnalignedLittleEndianShort (const void* buffer)
  20. {
  21. auto data = readUnaligned<uint16> (buffer);
  22. return ByteOrder::littleEndianShort (&data);
  23. }
  24. inline uint32 readUnalignedLittleEndianInt (const void* buffer)
  25. {
  26. auto data = readUnaligned<uint32> (buffer);
  27. return ByteOrder::littleEndianInt (&data);
  28. }
  29. struct ZipFile::ZipEntryHolder
  30. {
  31. ZipEntryHolder (const char* buffer, int fileNameLen)
  32. {
  33. isCompressed = readUnalignedLittleEndianShort (buffer + 10) != 0;
  34. entry.fileTime = parseFileTime (readUnalignedLittleEndianShort (buffer + 12),
  35. readUnalignedLittleEndianShort (buffer + 14));
  36. compressedSize = (int64) readUnalignedLittleEndianInt (buffer + 20);
  37. entry.uncompressedSize = (int64) readUnalignedLittleEndianInt (buffer + 24);
  38. streamOffset = (int64) readUnalignedLittleEndianInt (buffer + 42);
  39. entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  40. }
  41. static Time parseFileTime (uint32 time, uint32 date) noexcept
  42. {
  43. int year = 1980 + (date >> 9);
  44. int month = ((date >> 5) & 15) - 1;
  45. int day = date & 31;
  46. int hours = time >> 11;
  47. int minutes = (time >> 5) & 63;
  48. int seconds = (int) ((time & 31) << 1);
  49. return { year, month, day, hours, minutes, seconds };
  50. }
  51. ZipEntry entry;
  52. int64 streamOffset, compressedSize;
  53. bool isCompressed;
  54. };
  55. //==============================================================================
  56. static int64 findCentralDirectoryFileHeader (InputStream& input, int& numEntries)
  57. {
  58. BufferedInputStream in (input, 8192);
  59. in.setPosition (in.getTotalLength());
  60. auto pos = in.getPosition();
  61. auto lowestPos = jmax ((int64) 0, pos - 1024);
  62. char buffer[32] = {};
  63. while (pos > lowestPos)
  64. {
  65. in.setPosition (pos - 22);
  66. pos = in.getPosition();
  67. memcpy (buffer + 22, buffer, 4);
  68. if (in.read (buffer, 22) != 22)
  69. return 0;
  70. for (int i = 0; i < 22; ++i)
  71. {
  72. if (readUnalignedLittleEndianInt (buffer + i) == 0x06054b50)
  73. {
  74. in.setPosition (pos + i);
  75. in.read (buffer, 22);
  76. numEntries = readUnalignedLittleEndianShort (buffer + 10);
  77. auto offset = (int64) readUnalignedLittleEndianInt (buffer + 16);
  78. if (offset >= 4)
  79. {
  80. in.setPosition (offset);
  81. // This is a workaround for some zip files which seem to contain the
  82. // wrong offset for the central directory - instead of including the
  83. // header, they point to the byte immediately after it.
  84. if (in.readInt() != 0x02014b50)
  85. {
  86. in.setPosition (offset - 4);
  87. if (in.readInt() == 0x02014b50)
  88. offset -= 4;
  89. }
  90. }
  91. return offset;
  92. }
  93. }
  94. }
  95. return 0;
  96. }
  97. //==============================================================================
  98. struct ZipFile::ZipInputStream : public InputStream
  99. {
  100. ZipInputStream (ZipFile& zf, const ZipFile::ZipEntryHolder& zei)
  101. : file (zf),
  102. zipEntryHolder (zei),
  103. inputStream (zf.inputStream)
  104. {
  105. if (zf.inputSource != nullptr)
  106. {
  107. streamToDelete.reset (file.inputSource->createInputStream());
  108. inputStream = streamToDelete.get();
  109. }
  110. else
  111. {
  112. #if JUCE_DEBUG
  113. zf.streamCounter.numOpenStreams++;
  114. #endif
  115. }
  116. char buffer[30];
  117. if (inputStream != nullptr
  118. && inputStream->setPosition (zei.streamOffset)
  119. && inputStream->read (buffer, 30) == 30
  120. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  121. {
  122. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  123. + ByteOrder::littleEndianShort (buffer + 28);
  124. }
  125. }
  126. ~ZipInputStream()
  127. {
  128. #if JUCE_DEBUG
  129. if (inputStream != nullptr && inputStream == file.inputStream)
  130. file.streamCounter.numOpenStreams--;
  131. #endif
  132. }
  133. int64 getTotalLength() override
  134. {
  135. return zipEntryHolder.compressedSize;
  136. }
  137. int read (void* buffer, int howMany) override
  138. {
  139. if (headerSize <= 0)
  140. return 0;
  141. howMany = (int) jmin ((int64) howMany, zipEntryHolder.compressedSize - pos);
  142. if (inputStream == nullptr)
  143. return 0;
  144. int num;
  145. if (inputStream == file.inputStream)
  146. {
  147. const ScopedLock sl (file.lock);
  148. inputStream->setPosition (pos + zipEntryHolder.streamOffset + headerSize);
  149. num = inputStream->read (buffer, howMany);
  150. }
  151. else
  152. {
  153. inputStream->setPosition (pos + zipEntryHolder.streamOffset + headerSize);
  154. num = inputStream->read (buffer, howMany);
  155. }
  156. pos += num;
  157. return num;
  158. }
  159. bool isExhausted() override
  160. {
  161. return headerSize <= 0 || pos >= zipEntryHolder.compressedSize;
  162. }
  163. int64 getPosition() override
  164. {
  165. return pos;
  166. }
  167. bool setPosition (int64 newPos) override
  168. {
  169. pos = jlimit ((int64) 0, zipEntryHolder.compressedSize, newPos);
  170. return true;
  171. }
  172. private:
  173. ZipFile& file;
  174. ZipEntryHolder zipEntryHolder;
  175. int64 pos = 0;
  176. int headerSize = 0;
  177. InputStream* inputStream;
  178. ScopedPointer<InputStream> streamToDelete;
  179. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream)
  180. };
  181. //==============================================================================
  182. ZipFile::ZipFile (InputStream* stream, bool deleteStreamWhenDestroyed)
  183. : inputStream (stream)
  184. {
  185. if (deleteStreamWhenDestroyed)
  186. streamToDelete.reset (inputStream);
  187. init();
  188. }
  189. ZipFile::ZipFile (InputStream& stream) : inputStream (&stream)
  190. {
  191. init();
  192. }
  193. ZipFile::ZipFile (const File& file) : inputSource (new FileInputSource (file))
  194. {
  195. init();
  196. }
  197. ZipFile::ZipFile (InputSource* source) : inputSource (source)
  198. {
  199. init();
  200. }
  201. ZipFile::~ZipFile()
  202. {
  203. entries.clear();
  204. }
  205. #if JUCE_DEBUG
  206. ZipFile::OpenStreamCounter::~OpenStreamCounter()
  207. {
  208. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  209. zipfile, but you've forgotten to delete that stream object before deleting the file..
  210. Streams can't be kept open after the file is deleted because they need to share the input
  211. stream that is managed by the ZipFile object.
  212. */
  213. jassert (numOpenStreams == 0);
  214. }
  215. #endif
  216. //==============================================================================
  217. int ZipFile::getNumEntries() const noexcept
  218. {
  219. return entries.size();
  220. }
  221. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const noexcept
  222. {
  223. if (auto* zei = entries[index])
  224. return &(zei->entry);
  225. return nullptr;
  226. }
  227. int ZipFile::getIndexOfFileName (const String& fileName, bool ignoreCase) const noexcept
  228. {
  229. for (int i = 0; i < entries.size(); ++i)
  230. {
  231. auto& entryFilename = entries.getUnchecked (i)->entry.filename;
  232. if (ignoreCase ? entryFilename.equalsIgnoreCase (fileName)
  233. : entryFilename == fileName)
  234. return i;
  235. }
  236. return -1;
  237. }
  238. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName, bool ignoreCase) const noexcept
  239. {
  240. return getEntry (getIndexOfFileName (fileName, ignoreCase));
  241. }
  242. InputStream* ZipFile::createStreamForEntry (const int index)
  243. {
  244. InputStream* stream = nullptr;
  245. if (auto* zei = entries[index])
  246. {
  247. stream = new ZipInputStream (*this, *zei);
  248. if (zei->isCompressed)
  249. {
  250. stream = new GZIPDecompressorInputStream (stream, true,
  251. GZIPDecompressorInputStream::deflateFormat,
  252. zei->entry.uncompressedSize);
  253. // (much faster to unzip in big blocks using a buffer..)
  254. stream = new BufferedInputStream (stream, 32768, true);
  255. }
  256. }
  257. return stream;
  258. }
  259. InputStream* ZipFile::createStreamForEntry (const ZipEntry& entry)
  260. {
  261. for (int i = 0; i < entries.size(); ++i)
  262. if (&entries.getUnchecked (i)->entry == &entry)
  263. return createStreamForEntry (i);
  264. return nullptr;
  265. }
  266. void ZipFile::sortEntriesByFilename()
  267. {
  268. std::sort (entries.begin(), entries.end(),
  269. [] (const ZipEntryHolder* e1, const ZipEntryHolder* e2) { return e1->entry.filename < e2->entry.filename; });
  270. }
  271. //==============================================================================
  272. void ZipFile::init()
  273. {
  274. ScopedPointer<InputStream> toDelete;
  275. InputStream* in = inputStream;
  276. if (inputSource != nullptr)
  277. {
  278. in = inputSource->createInputStream();
  279. toDelete.reset (in);
  280. }
  281. if (in != nullptr)
  282. {
  283. int numEntries = 0;
  284. auto centralDirectoryPos = findCentralDirectoryFileHeader (*in, numEntries);
  285. if (centralDirectoryPos >= 0 && centralDirectoryPos < in->getTotalLength())
  286. {
  287. auto size = (size_t) (in->getTotalLength() - centralDirectoryPos);
  288. in->setPosition (centralDirectoryPos);
  289. MemoryBlock headerData;
  290. if (in->readIntoMemoryBlock (headerData, (ssize_t) size) == size)
  291. {
  292. size_t pos = 0;
  293. for (int i = 0; i < numEntries; ++i)
  294. {
  295. if (pos + 46 > size)
  296. break;
  297. auto* buffer = static_cast<const char*> (headerData.getData()) + pos;
  298. auto fileNameLen = readUnalignedLittleEndianShort (buffer + 28);
  299. if (pos + 46 + fileNameLen > size)
  300. break;
  301. entries.add (new ZipEntryHolder (buffer, fileNameLen));
  302. pos += 46 + fileNameLen
  303. + readUnalignedLittleEndianShort (buffer + 30)
  304. + readUnalignedLittleEndianShort (buffer + 32);
  305. }
  306. }
  307. }
  308. }
  309. }
  310. Result ZipFile::uncompressTo (const File& targetDirectory,
  311. const bool shouldOverwriteFiles)
  312. {
  313. for (int i = 0; i < entries.size(); ++i)
  314. {
  315. auto result = uncompressEntry (i, targetDirectory, shouldOverwriteFiles);
  316. if (result.failed())
  317. return result;
  318. }
  319. return Result::ok();
  320. }
  321. Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles)
  322. {
  323. auto* zei = entries.getUnchecked (index);
  324. #if JUCE_WINDOWS
  325. auto entryPath = zei->entry.filename;
  326. #else
  327. auto entryPath = zei->entry.filename.replaceCharacter ('\\', '/');
  328. #endif
  329. if (entryPath.isEmpty())
  330. return Result::ok();
  331. auto targetFile = targetDirectory.getChildFile (entryPath);
  332. if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\'))
  333. return targetFile.createDirectory(); // (entry is a directory, not a file)
  334. ScopedPointer<InputStream> in (createStreamForEntry (index));
  335. if (in == nullptr)
  336. return Result::fail ("Failed to open the zip file for reading");
  337. if (targetFile.exists())
  338. {
  339. if (! shouldOverwriteFiles)
  340. return Result::ok();
  341. if (! targetFile.deleteFile())
  342. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  343. }
  344. if (! targetFile.getParentDirectory().createDirectory())
  345. return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName());
  346. {
  347. FileOutputStream out (targetFile);
  348. if (out.failedToOpen())
  349. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  350. out << *in;
  351. }
  352. targetFile.setCreationTime (zei->entry.fileTime);
  353. targetFile.setLastModificationTime (zei->entry.fileTime);
  354. targetFile.setLastAccessTime (zei->entry.fileTime);
  355. return Result::ok();
  356. }
  357. //==============================================================================
  358. struct ZipFile::Builder::Item
  359. {
  360. Item (const File& f, InputStream* s, int compression, const String& storedPath, Time time)
  361. : file (f), stream (s), storedPathname (storedPath), fileTime (time), compressionLevel (compression)
  362. {
  363. }
  364. bool writeData (OutputStream& target, const int64 overallStartPosition)
  365. {
  366. MemoryOutputStream compressedData ((size_t) file.getSize());
  367. if (compressionLevel > 0)
  368. {
  369. GZIPCompressorOutputStream compressor (compressedData, compressionLevel,
  370. GZIPCompressorOutputStream::windowBitsRaw);
  371. if (! writeSource (compressor))
  372. return false;
  373. }
  374. else
  375. {
  376. if (! writeSource (compressedData))
  377. return false;
  378. }
  379. compressedSize = (int64) compressedData.getDataSize();
  380. headerStart = target.getPosition() - overallStartPosition;
  381. target.writeInt (0x04034b50);
  382. writeFlagsAndSizes (target);
  383. target << storedPathname
  384. << compressedData;
  385. return true;
  386. }
  387. bool writeDirectoryEntry (OutputStream& target)
  388. {
  389. target.writeInt (0x02014b50);
  390. target.writeShort (20); // version written
  391. writeFlagsAndSizes (target);
  392. target.writeShort (0); // comment length
  393. target.writeShort (0); // start disk num
  394. target.writeShort (0); // internal attributes
  395. target.writeInt (0); // external attributes
  396. target.writeInt ((int) (uint32) headerStart);
  397. target << storedPathname;
  398. return true;
  399. }
  400. private:
  401. const File file;
  402. ScopedPointer<InputStream> stream;
  403. String storedPathname;
  404. Time fileTime;
  405. int64 compressedSize = 0, uncompressedSize = 0, headerStart = 0;
  406. int compressionLevel = 0;
  407. unsigned long checksum = 0;
  408. static void writeTimeAndDate (OutputStream& target, Time t)
  409. {
  410. target.writeShort ((short) (t.getSeconds() + (t.getMinutes() << 5) + (t.getHours() << 11)));
  411. target.writeShort ((short) (t.getDayOfMonth() + ((t.getMonth() + 1) << 5) + ((t.getYear() - 1980) << 9)));
  412. }
  413. bool writeSource (OutputStream& target)
  414. {
  415. if (stream == nullptr)
  416. {
  417. stream.reset (file.createInputStream());
  418. if (stream == nullptr)
  419. return false;
  420. }
  421. checksum = 0;
  422. uncompressedSize = 0;
  423. const int bufferSize = 4096;
  424. HeapBlock<unsigned char> buffer (bufferSize);
  425. while (! stream->isExhausted())
  426. {
  427. auto bytesRead = stream->read (buffer, bufferSize);
  428. if (bytesRead < 0)
  429. return false;
  430. checksum = zlibNamespace::crc32 (checksum, buffer, (unsigned int) bytesRead);
  431. target.write (buffer, (size_t) bytesRead);
  432. uncompressedSize += bytesRead;
  433. }
  434. stream.reset();
  435. return true;
  436. }
  437. void writeFlagsAndSizes (OutputStream& target) const
  438. {
  439. target.writeShort (10); // version needed
  440. target.writeShort ((short) (1 << 11)); // this flag indicates UTF-8 filename encoding
  441. target.writeShort (compressionLevel > 0 ? (short) 8 : (short) 0);
  442. writeTimeAndDate (target, fileTime);
  443. target.writeInt ((int) checksum);
  444. target.writeInt ((int) (uint32) compressedSize);
  445. target.writeInt ((int) (uint32) uncompressedSize);
  446. target.writeShort ((short) storedPathname.toUTF8().sizeInBytes() - 1);
  447. target.writeShort (0); // extra field length
  448. }
  449. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Item)
  450. };
  451. //==============================================================================
  452. ZipFile::Builder::Builder() {}
  453. ZipFile::Builder::~Builder() {}
  454. void ZipFile::Builder::addFile (const File& file, int compression, const String& path)
  455. {
  456. items.add (new Item (file, nullptr, compression,
  457. path.isEmpty() ? file.getFileName() : path,
  458. file.getLastModificationTime()));
  459. }
  460. void ZipFile::Builder::addEntry (InputStream* stream, int compression, const String& path, Time time)
  461. {
  462. jassert (stream != nullptr); // must not be null!
  463. jassert (path.isNotEmpty());
  464. items.add (new Item ({}, stream, compression, path, time));
  465. }
  466. bool ZipFile::Builder::writeToStream (OutputStream& target, double* const progress) const
  467. {
  468. auto fileStart = target.getPosition();
  469. for (int i = 0; i < items.size(); ++i)
  470. {
  471. if (progress != nullptr)
  472. *progress = (i + 0.5) / items.size();
  473. if (! items.getUnchecked (i)->writeData (target, fileStart))
  474. return false;
  475. }
  476. auto directoryStart = target.getPosition();
  477. for (auto* item : items)
  478. if (! item->writeDirectoryEntry (target))
  479. return false;
  480. auto directoryEnd = target.getPosition();
  481. target.writeInt (0x06054b50);
  482. target.writeShort (0);
  483. target.writeShort (0);
  484. target.writeShort ((short) items.size());
  485. target.writeShort ((short) items.size());
  486. target.writeInt ((int) (directoryEnd - directoryStart));
  487. target.writeInt ((int) (directoryStart - fileStart));
  488. target.writeShort (0);
  489. if (progress != nullptr)
  490. *progress = 1.0;
  491. return true;
  492. }
  493. //==============================================================================
  494. #if JUCE_UNIT_TESTS
  495. struct ZIPTests : public UnitTest
  496. {
  497. ZIPTests() : UnitTest ("ZIP") {}
  498. void runTest() override
  499. {
  500. beginTest ("ZIP");
  501. ZipFile::Builder builder;
  502. StringArray entryNames { "first", "second", "third" };
  503. HashMap<String, MemoryBlock> blocks;
  504. for (auto& entryName : entryNames)
  505. {
  506. auto& block = blocks.getReference (entryName);
  507. MemoryOutputStream mo (block, false);
  508. mo << entryName;
  509. mo.flush();
  510. builder.addEntry (new MemoryInputStream (block, false), 9, entryName, Time::getCurrentTime());
  511. }
  512. MemoryBlock data;
  513. MemoryOutputStream mo (data, false);
  514. builder.writeToStream (mo, nullptr);
  515. MemoryInputStream mi (data, false);
  516. ZipFile zip (mi);
  517. expectEquals (zip.getNumEntries(), entryNames.size());
  518. for (auto& entryName : entryNames)
  519. {
  520. auto* entry = zip.getEntry (entryName);
  521. ScopedPointer<InputStream> input (zip.createStreamForEntry (*entry));
  522. expectEquals (input->readEntireStreamAsString(), entryName);
  523. }
  524. }
  525. };
  526. static ZIPTests zipTests;
  527. #endif
  528. } // namespace juce