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.

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