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.

612 lines
19KB

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