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.

601 lines
18KB

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