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.

663 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. uint16 readUnalignedLittleEndianShort (const void* buffer)
  20. {
  21. auto data = readUnaligned<uint16> (buffer);
  22. return ByteOrder::littleEndianShort (&data);
  23. }
  24. 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. inputStream = streamToDelete = file.inputSource->createInputStream();
  108. }
  109. else
  110. {
  111. #if JUCE_DEBUG
  112. zf.streamCounter.numOpenStreams++;
  113. #endif
  114. }
  115. char buffer[30];
  116. if (inputStream != nullptr
  117. && inputStream->setPosition (zei.streamOffset)
  118. && inputStream->read (buffer, 30) == 30
  119. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  120. {
  121. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  122. + ByteOrder::littleEndianShort (buffer + 28);
  123. }
  124. }
  125. ~ZipInputStream()
  126. {
  127. #if JUCE_DEBUG
  128. if (inputStream != nullptr && inputStream == file.inputStream)
  129. file.streamCounter.numOpenStreams--;
  130. #endif
  131. }
  132. int64 getTotalLength() override
  133. {
  134. return zipEntryHolder.compressedSize;
  135. }
  136. int read (void* buffer, int howMany) override
  137. {
  138. if (headerSize <= 0)
  139. return 0;
  140. howMany = (int) jmin ((int64) howMany, zipEntryHolder.compressedSize - pos);
  141. if (inputStream == nullptr)
  142. return 0;
  143. int num;
  144. if (inputStream == file.inputStream)
  145. {
  146. const ScopedLock sl (file.lock);
  147. inputStream->setPosition (pos + zipEntryHolder.streamOffset + headerSize);
  148. num = inputStream->read (buffer, howMany);
  149. }
  150. else
  151. {
  152. inputStream->setPosition (pos + zipEntryHolder.streamOffset + headerSize);
  153. num = inputStream->read (buffer, howMany);
  154. }
  155. pos += num;
  156. return num;
  157. }
  158. bool isExhausted() override
  159. {
  160. return headerSize <= 0 || pos >= zipEntryHolder.compressedSize;
  161. }
  162. int64 getPosition() override
  163. {
  164. return pos;
  165. }
  166. bool setPosition (int64 newPos) override
  167. {
  168. pos = jlimit ((int64) 0, zipEntryHolder.compressedSize, newPos);
  169. return true;
  170. }
  171. private:
  172. ZipFile& file;
  173. ZipEntryHolder zipEntryHolder;
  174. int64 pos = 0;
  175. int headerSize = 0;
  176. InputStream* inputStream;
  177. ScopedPointer<InputStream> streamToDelete;
  178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream)
  179. };
  180. //==============================================================================
  181. ZipFile::ZipFile (InputStream* stream, bool deleteStreamWhenDestroyed)
  182. : inputStream (stream)
  183. {
  184. if (deleteStreamWhenDestroyed)
  185. streamToDelete = inputStream;
  186. init();
  187. }
  188. ZipFile::ZipFile (InputStream& stream) : inputStream (&stream)
  189. {
  190. init();
  191. }
  192. ZipFile::ZipFile (const File& file) : inputSource (new FileInputSource (file))
  193. {
  194. init();
  195. }
  196. ZipFile::ZipFile (InputSource* source) : inputSource (source)
  197. {
  198. init();
  199. }
  200. ZipFile::~ZipFile()
  201. {
  202. entries.clear();
  203. }
  204. #if JUCE_DEBUG
  205. ZipFile::OpenStreamCounter::~OpenStreamCounter()
  206. {
  207. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  208. zipfile, but you've forgotten to delete that stream object before deleting the file..
  209. Streams can't be kept open after the file is deleted because they need to share the input
  210. stream that is managed by the ZipFile object.
  211. */
  212. jassert (numOpenStreams == 0);
  213. }
  214. #endif
  215. //==============================================================================
  216. int ZipFile::getNumEntries() const noexcept
  217. {
  218. return entries.size();
  219. }
  220. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const noexcept
  221. {
  222. if (auto* zei = entries[index])
  223. return &(zei->entry);
  224. return nullptr;
  225. }
  226. int ZipFile::getIndexOfFileName (const String& fileName, bool ignoreCase) const noexcept
  227. {
  228. for (int i = 0; i < entries.size(); ++i)
  229. {
  230. auto& entryFilename = entries.getUnchecked (i)->entry.filename;
  231. if (ignoreCase ? entryFilename.equalsIgnoreCase (fileName)
  232. : entryFilename == fileName)
  233. return i;
  234. }
  235. return -1;
  236. }
  237. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName, bool ignoreCase) const noexcept
  238. {
  239. return getEntry (getIndexOfFileName (fileName, ignoreCase));
  240. }
  241. InputStream* ZipFile::createStreamForEntry (const int index)
  242. {
  243. InputStream* stream = nullptr;
  244. if (auto* zei = entries[index])
  245. {
  246. stream = new ZipInputStream (*this, *zei);
  247. if (zei->isCompressed)
  248. {
  249. stream = new GZIPDecompressorInputStream (stream, true,
  250. GZIPDecompressorInputStream::deflateFormat,
  251. zei->entry.uncompressedSize);
  252. // (much faster to unzip in big blocks using a buffer..)
  253. stream = new BufferedInputStream (stream, 32768, true);
  254. }
  255. }
  256. return stream;
  257. }
  258. InputStream* ZipFile::createStreamForEntry (const ZipEntry& entry)
  259. {
  260. for (int i = 0; i < entries.size(); ++i)
  261. if (&entries.getUnchecked (i)->entry == &entry)
  262. return createStreamForEntry (i);
  263. return nullptr;
  264. }
  265. void ZipFile::sortEntriesByFilename()
  266. {
  267. std::sort (entries.begin(), entries.end(),
  268. [] (const ZipEntryHolder* e1, const ZipEntryHolder* e2) { return e1->entry.filename < e2->entry.filename; });
  269. }
  270. //==============================================================================
  271. void ZipFile::init()
  272. {
  273. ScopedPointer<InputStream> toDelete;
  274. InputStream* in = inputStream;
  275. if (inputSource != nullptr)
  276. {
  277. in = inputSource->createInputStream();
  278. toDelete = in;
  279. }
  280. if (in != nullptr)
  281. {
  282. int numEntries = 0;
  283. auto centralDirectoryPos = findCentralDirectoryFileHeader (*in, numEntries);
  284. if (centralDirectoryPos >= 0 && centralDirectoryPos < in->getTotalLength())
  285. {
  286. auto size = (size_t) (in->getTotalLength() - centralDirectoryPos);
  287. in->setPosition (centralDirectoryPos);
  288. MemoryBlock headerData;
  289. if (in->readIntoMemoryBlock (headerData, (ssize_t) size) == size)
  290. {
  291. size_t pos = 0;
  292. for (int i = 0; i < numEntries; ++i)
  293. {
  294. if (pos + 46 > size)
  295. break;
  296. auto* buffer = static_cast<const char*> (headerData.getData()) + pos;
  297. auto fileNameLen = readUnalignedLittleEndianShort (buffer + 28);
  298. if (pos + 46 + fileNameLen > size)
  299. break;
  300. entries.add (new ZipEntryHolder (buffer, fileNameLen));
  301. pos += 46 + fileNameLen
  302. + readUnalignedLittleEndianShort (buffer + 30)
  303. + readUnalignedLittleEndianShort (buffer + 32);
  304. }
  305. }
  306. }
  307. }
  308. }
  309. Result ZipFile::uncompressTo (const File& targetDirectory,
  310. const bool shouldOverwriteFiles)
  311. {
  312. for (int i = 0; i < entries.size(); ++i)
  313. {
  314. auto result = uncompressEntry (i, targetDirectory, shouldOverwriteFiles);
  315. if (result.failed())
  316. return result;
  317. }
  318. return Result::ok();
  319. }
  320. Result ZipFile::uncompressEntry (int index, const File& targetDirectory, bool shouldOverwriteFiles)
  321. {
  322. auto* zei = entries.getUnchecked (index);
  323. #if JUCE_WINDOWS
  324. auto entryPath = zei->entry.filename;
  325. #else
  326. auto entryPath = zei->entry.filename.replaceCharacter ('\\', '/');
  327. #endif
  328. if (entryPath.isEmpty())
  329. return Result::ok();
  330. auto targetFile = targetDirectory.getChildFile (entryPath);
  331. if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\'))
  332. return targetFile.createDirectory(); // (entry is a directory, not a file)
  333. ScopedPointer<InputStream> in (createStreamForEntry (index));
  334. if (in == nullptr)
  335. return Result::fail ("Failed to open the zip file for reading");
  336. if (targetFile.exists())
  337. {
  338. if (! shouldOverwriteFiles)
  339. return Result::ok();
  340. if (! targetFile.deleteFile())
  341. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  342. }
  343. if (! targetFile.getParentDirectory().createDirectory())
  344. return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName());
  345. {
  346. FileOutputStream out (targetFile);
  347. if (out.failedToOpen())
  348. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  349. out << *in;
  350. }
  351. targetFile.setCreationTime (zei->entry.fileTime);
  352. targetFile.setLastModificationTime (zei->entry.fileTime);
  353. targetFile.setLastAccessTime (zei->entry.fileTime);
  354. return Result::ok();
  355. }
  356. //==============================================================================
  357. struct ZipFile::Builder::Item
  358. {
  359. Item (const File& f, InputStream* s, int compression, const String& storedPath, Time time)
  360. : file (f), stream (s), storedPathname (storedPath), fileTime (time), compressionLevel (compression)
  361. {
  362. }
  363. bool writeData (OutputStream& target, const int64 overallStartPosition)
  364. {
  365. MemoryOutputStream compressedData ((size_t) file.getSize());
  366. if (compressionLevel > 0)
  367. {
  368. GZIPCompressorOutputStream compressor (compressedData, compressionLevel,
  369. GZIPCompressorOutputStream::windowBitsRaw);
  370. if (! writeSource (compressor))
  371. return false;
  372. }
  373. else
  374. {
  375. if (! writeSource (compressedData))
  376. return false;
  377. }
  378. compressedSize = (int64) compressedData.getDataSize();
  379. headerStart = target.getPosition() - overallStartPosition;
  380. target.writeInt (0x04034b50);
  381. writeFlagsAndSizes (target);
  382. target << storedPathname
  383. << compressedData;
  384. return true;
  385. }
  386. bool writeDirectoryEntry (OutputStream& target)
  387. {
  388. target.writeInt (0x02014b50);
  389. target.writeShort (20); // version written
  390. writeFlagsAndSizes (target);
  391. target.writeShort (0); // comment length
  392. target.writeShort (0); // start disk num
  393. target.writeShort (0); // internal attributes
  394. target.writeInt (0); // external attributes
  395. target.writeInt ((int) (uint32) headerStart);
  396. target << storedPathname;
  397. return true;
  398. }
  399. private:
  400. const File file;
  401. ScopedPointer<InputStream> stream;
  402. String storedPathname;
  403. Time fileTime;
  404. int64 compressedSize = 0, uncompressedSize = 0, headerStart = 0;
  405. int compressionLevel = 0;
  406. unsigned long checksum = 0;
  407. static void writeTimeAndDate (OutputStream& target, Time t)
  408. {
  409. target.writeShort ((short) (t.getSeconds() + (t.getMinutes() << 5) + (t.getHours() << 11)));
  410. target.writeShort ((short) (t.getDayOfMonth() + ((t.getMonth() + 1) << 5) + ((t.getYear() - 1980) << 9)));
  411. }
  412. bool writeSource (OutputStream& target)
  413. {
  414. if (stream == nullptr)
  415. {
  416. stream = file.createInputStream();
  417. if (stream == nullptr)
  418. return false;
  419. }
  420. checksum = 0;
  421. uncompressedSize = 0;
  422. const int bufferSize = 4096;
  423. HeapBlock<unsigned char> buffer (bufferSize);
  424. while (! stream->isExhausted())
  425. {
  426. auto bytesRead = stream->read (buffer, bufferSize);
  427. if (bytesRead < 0)
  428. return false;
  429. checksum = zlibNamespace::crc32 (checksum, buffer, (unsigned int) bytesRead);
  430. target.write (buffer, (size_t) bytesRead);
  431. uncompressedSize += bytesRead;
  432. }
  433. stream.reset();
  434. return true;
  435. }
  436. void writeFlagsAndSizes (OutputStream& target) const
  437. {
  438. target.writeShort (10); // version needed
  439. target.writeShort ((short) (1 << 11)); // this flag indicates UTF-8 filename encoding
  440. target.writeShort (compressionLevel > 0 ? (short) 8 : (short) 0);
  441. writeTimeAndDate (target, fileTime);
  442. target.writeInt ((int) checksum);
  443. target.writeInt ((int) (uint32) compressedSize);
  444. target.writeInt ((int) (uint32) uncompressedSize);
  445. target.writeShort ((short) storedPathname.toUTF8().sizeInBytes() - 1);
  446. target.writeShort (0); // extra field length
  447. }
  448. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Item)
  449. };
  450. //==============================================================================
  451. ZipFile::Builder::Builder() {}
  452. ZipFile::Builder::~Builder() {}
  453. void ZipFile::Builder::addFile (const File& file, int compression, const String& path)
  454. {
  455. items.add (new Item (file, nullptr, compression,
  456. path.isEmpty() ? file.getFileName() : path,
  457. file.getLastModificationTime()));
  458. }
  459. void ZipFile::Builder::addEntry (InputStream* stream, int compression, const String& path, Time time)
  460. {
  461. jassert (stream != nullptr); // must not be null!
  462. jassert (path.isNotEmpty());
  463. items.add (new Item ({}, stream, compression, path, time));
  464. }
  465. bool ZipFile::Builder::writeToStream (OutputStream& target, double* const progress) const
  466. {
  467. auto fileStart = target.getPosition();
  468. for (int i = 0; i < items.size(); ++i)
  469. {
  470. if (progress != nullptr)
  471. *progress = (i + 0.5) / items.size();
  472. if (! items.getUnchecked (i)->writeData (target, fileStart))
  473. return false;
  474. }
  475. auto directoryStart = target.getPosition();
  476. for (auto* item : items)
  477. if (! item->writeDirectoryEntry (target))
  478. return false;
  479. auto directoryEnd = target.getPosition();
  480. target.writeInt (0x06054b50);
  481. target.writeShort (0);
  482. target.writeShort (0);
  483. target.writeShort ((short) items.size());
  484. target.writeShort ((short) items.size());
  485. target.writeInt ((int) (directoryEnd - directoryStart));
  486. target.writeInt ((int) (directoryStart - fileStart));
  487. target.writeShort (0);
  488. if (progress != nullptr)
  489. *progress = 1.0;
  490. return true;
  491. }
  492. //==============================================================================
  493. #if JUCE_UNIT_TESTS
  494. struct ZIPTests : public UnitTest
  495. {
  496. ZIPTests() : UnitTest ("ZIP") {}
  497. void runTest() override
  498. {
  499. beginTest ("ZIP");
  500. ZipFile::Builder builder;
  501. StringArray entryNames { "first", "second", "third" };
  502. HashMap<String, MemoryBlock> blocks;
  503. for (auto& entryName : entryNames)
  504. {
  505. auto& block = blocks.getReference (entryName);
  506. MemoryOutputStream mo (block, false);
  507. mo << entryName;
  508. mo.flush();
  509. builder.addEntry (new MemoryInputStream (block, false), 9, entryName, Time::getCurrentTime());
  510. }
  511. MemoryBlock data;
  512. MemoryOutputStream mo (data, false);
  513. builder.writeToStream (mo, nullptr);
  514. MemoryInputStream mi (data, false);
  515. ZipFile zip (mi);
  516. expectEquals (zip.getNumEntries(), entryNames.size());
  517. for (auto& entryName : entryNames)
  518. {
  519. auto* entry = zip.getEntry (entryName);
  520. ScopedPointer<InputStream> input (zip.createStreamForEntry (*entry));
  521. expectEquals (input->readEntireStreamAsString(), entryName);
  522. }
  523. }
  524. };
  525. static ZIPTests zipTests;
  526. #endif
  527. } // namespace juce