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.

579 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. class ZipFile::ZipEntryHolder
  19. {
  20. public:
  21. ZipEntryHolder (const char* const buffer, const int fileNameLen)
  22. {
  23. entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  24. const int time = ByteOrder::littleEndianShort (buffer + 12);
  25. const int date = ByteOrder::littleEndianShort (buffer + 14);
  26. entry.fileTime = getFileTimeFromRawEncodings (time, date);
  27. compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  28. compressedSize = (size_t) ByteOrder::littleEndianInt (buffer + 20);
  29. entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  30. streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  31. }
  32. struct FileNameComparator
  33. {
  34. static int compareElements (const ZipEntryHolder* first, const ZipEntryHolder* second)
  35. {
  36. return first->entry.filename.compare (second->entry.filename);
  37. }
  38. };
  39. ZipEntry entry;
  40. size_t streamOffset;
  41. size_t compressedSize;
  42. bool compressed;
  43. private:
  44. static Time getFileTimeFromRawEncodings (int time, int date)
  45. {
  46. const int year = 1980 + (date >> 9);
  47. const int month = ((date >> 5) & 15) - 1;
  48. const int day = date & 31;
  49. const int hours = time >> 11;
  50. const int minutes = (time >> 5) & 63;
  51. const int seconds = (time & 31) << 1;
  52. return Time (year, month, day, hours, minutes, seconds);
  53. }
  54. };
  55. //==============================================================================
  56. namespace
  57. {
  58. int findEndOfZipEntryTable (InputStream& input, int& numEntries)
  59. {
  60. BufferedInputStream in (input, 8192);
  61. in.setPosition (in.getTotalLength());
  62. int64 pos = in.getPosition();
  63. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  64. char buffer [32] = { 0 };
  65. while (pos > lowestPos)
  66. {
  67. in.setPosition (pos - 22);
  68. pos = in.getPosition();
  69. memcpy (buffer + 22, buffer, 4);
  70. if (in.read (buffer, 22) != 22)
  71. return 0;
  72. for (int i = 0; i < 22; ++i)
  73. {
  74. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  75. {
  76. in.setPosition (pos + i);
  77. in.read (buffer, 22);
  78. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  79. return (int) ByteOrder::littleEndianInt (buffer + 16);
  80. }
  81. }
  82. }
  83. return 0;
  84. }
  85. }
  86. //==============================================================================
  87. class ZipFile::ZipInputStream : public InputStream
  88. {
  89. public:
  90. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryHolder& zei)
  91. : file (file_),
  92. zipEntryHolder (zei),
  93. pos (0),
  94. headerSize (0),
  95. inputStream (file_.inputStream)
  96. {
  97. if (file_.inputSource != nullptr)
  98. {
  99. inputStream = streamToDelete = file.inputSource->createInputStream();
  100. }
  101. else
  102. {
  103. #if JUCE_DEBUG
  104. file_.streamCounter.numOpenStreams++;
  105. #endif
  106. }
  107. char buffer [30];
  108. if (inputStream != nullptr
  109. && inputStream->setPosition (zei.streamOffset)
  110. && inputStream->read (buffer, 30) == 30
  111. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  112. {
  113. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  114. + ByteOrder::littleEndianShort (buffer + 28);
  115. }
  116. }
  117. ~ZipInputStream()
  118. {
  119. #if JUCE_DEBUG
  120. if (inputStream != nullptr && inputStream == file.inputStream)
  121. file.streamCounter.numOpenStreams--;
  122. #endif
  123. }
  124. int64 getTotalLength()
  125. {
  126. return zipEntryHolder.compressedSize;
  127. }
  128. int read (void* buffer, int howMany)
  129. {
  130. if (headerSize <= 0)
  131. return 0;
  132. howMany = (int) jmin ((int64) howMany, (int64) (zipEntryHolder.compressedSize - pos));
  133. if (inputStream == nullptr)
  134. return 0;
  135. int num;
  136. if (inputStream == file.inputStream)
  137. {
  138. const ScopedLock sl (file.lock);
  139. inputStream->setPosition (pos + zipEntryHolder.streamOffset + headerSize);
  140. num = inputStream->read (buffer, howMany);
  141. }
  142. else
  143. {
  144. inputStream->setPosition (pos + zipEntryHolder.streamOffset + headerSize);
  145. num = inputStream->read (buffer, howMany);
  146. }
  147. pos += num;
  148. return num;
  149. }
  150. bool isExhausted()
  151. {
  152. return headerSize <= 0 || pos >= (int64) zipEntryHolder.compressedSize;
  153. }
  154. int64 getPosition()
  155. {
  156. return pos;
  157. }
  158. bool setPosition (int64 newPos)
  159. {
  160. pos = jlimit ((int64) 0, (int64) zipEntryHolder.compressedSize, newPos);
  161. return true;
  162. }
  163. private:
  164. ZipFile& file;
  165. ZipEntryHolder zipEntryHolder;
  166. int64 pos;
  167. int headerSize;
  168. InputStream* inputStream;
  169. ScopedPointer<InputStream> streamToDelete;
  170. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream);
  171. };
  172. //==============================================================================
  173. ZipFile::ZipFile (InputStream* const stream, const bool deleteStreamWhenDestroyed)
  174. : inputStream (stream)
  175. {
  176. if (deleteStreamWhenDestroyed)
  177. streamToDelete = inputStream;
  178. init();
  179. }
  180. ZipFile::ZipFile (InputStream& stream)
  181. : inputStream (&stream)
  182. {
  183. init();
  184. }
  185. ZipFile::ZipFile (const File& file)
  186. : inputStream (nullptr),
  187. inputSource (new FileInputSource (file))
  188. {
  189. init();
  190. }
  191. ZipFile::ZipFile (InputSource* const inputSource_)
  192. : inputStream (nullptr),
  193. inputSource (inputSource_)
  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. ZipEntryHolder* const zei = entries [index];
  220. return zei != nullptr ? &(zei->entry) : nullptr;
  221. }
  222. int ZipFile::getIndexOfFileName (const String& fileName) const noexcept
  223. {
  224. for (int i = 0; i < entries.size(); ++i)
  225. if (entries.getUnchecked (i)->entry.filename == fileName)
  226. return i;
  227. return -1;
  228. }
  229. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const noexcept
  230. {
  231. return getEntry (getIndexOfFileName (fileName));
  232. }
  233. InputStream* ZipFile::createStreamForEntry (const int index)
  234. {
  235. ZipEntryHolder* const zei = entries[index];
  236. InputStream* stream = nullptr;
  237. if (zei != nullptr)
  238. {
  239. stream = new ZipInputStream (*this, *zei);
  240. if (zei->compressed)
  241. {
  242. stream = new GZIPDecompressorInputStream (stream, true, true,
  243. zei->entry.uncompressedSize);
  244. // (much faster to unzip in big blocks using a buffer..)
  245. stream = new BufferedInputStream (stream, 32768, true);
  246. }
  247. }
  248. return stream;
  249. }
  250. void ZipFile::sortEntriesByFilename()
  251. {
  252. ZipEntryHolder::FileNameComparator sorter;
  253. entries.sort (sorter);
  254. }
  255. //==============================================================================
  256. void ZipFile::init()
  257. {
  258. ScopedPointer <InputStream> toDelete;
  259. InputStream* in = inputStream;
  260. if (inputSource != nullptr)
  261. {
  262. in = inputSource->createInputStream();
  263. toDelete = in;
  264. }
  265. if (in != nullptr)
  266. {
  267. int numEntries = 0;
  268. int pos = findEndOfZipEntryTable (*in, numEntries);
  269. if (pos >= 0 && pos < in->getTotalLength())
  270. {
  271. const int size = (int) (in->getTotalLength() - pos);
  272. in->setPosition (pos);
  273. MemoryBlock headerData;
  274. if (in->readIntoMemoryBlock (headerData, size) == size)
  275. {
  276. pos = 0;
  277. for (int i = 0; i < numEntries; ++i)
  278. {
  279. if (pos + 46 > size)
  280. break;
  281. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  282. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  283. if (pos + 46 + fileNameLen > size)
  284. break;
  285. entries.add (new ZipEntryHolder (buffer, fileNameLen));
  286. pos += 46 + fileNameLen
  287. + ByteOrder::littleEndianShort (buffer + 30)
  288. + ByteOrder::littleEndianShort (buffer + 32);
  289. }
  290. }
  291. }
  292. }
  293. }
  294. Result ZipFile::uncompressTo (const File& targetDirectory,
  295. const bool shouldOverwriteFiles)
  296. {
  297. for (int i = 0; i < entries.size(); ++i)
  298. {
  299. Result result (uncompressEntry (i, targetDirectory, shouldOverwriteFiles));
  300. if (result.failed())
  301. return result;
  302. }
  303. return Result::ok();
  304. }
  305. Result ZipFile::uncompressEntry (const int index,
  306. const File& targetDirectory,
  307. bool shouldOverwriteFiles)
  308. {
  309. const ZipEntryHolder* zei = entries.getUnchecked (index);
  310. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  311. if (zei->entry.filename.endsWithChar ('/'))
  312. return targetFile.createDirectory(); // (entry is a directory, not a file)
  313. ScopedPointer<InputStream> in (createStreamForEntry (index));
  314. if (in == nullptr)
  315. return Result::fail ("Failed to open the zip file for reading");
  316. if (targetFile.exists())
  317. {
  318. if (! shouldOverwriteFiles)
  319. return Result::ok();
  320. if (! targetFile.deleteFile())
  321. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  322. }
  323. if (! targetFile.getParentDirectory().createDirectory())
  324. return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName());
  325. {
  326. FileOutputStream out (targetFile);
  327. if (out.failedToOpen())
  328. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  329. out << *in;
  330. }
  331. targetFile.setCreationTime (zei->entry.fileTime);
  332. targetFile.setLastModificationTime (zei->entry.fileTime);
  333. targetFile.setLastAccessTime (zei->entry.fileTime);
  334. return Result::ok();
  335. }
  336. //=============================================================================
  337. extern unsigned long juce_crc32 (unsigned long crc, const unsigned char* buf, unsigned len);
  338. class ZipFile::Builder::Item
  339. {
  340. public:
  341. Item (const File& file_, const int compressionLevel_, const String& storedPathName_)
  342. : file (file_),
  343. storedPathname (storedPathName_.isEmpty() ? file_.getFileName() : storedPathName_),
  344. compressionLevel (compressionLevel_),
  345. compressedSize (0),
  346. headerStart (0)
  347. {
  348. }
  349. bool writeData (OutputStream& target, const int64 overallStartPosition)
  350. {
  351. MemoryOutputStream compressedData;
  352. if (compressionLevel > 0)
  353. {
  354. GZIPCompressorOutputStream compressor (&compressedData, compressionLevel, false,
  355. GZIPCompressorOutputStream::windowBitsRaw);
  356. if (! writeSource (compressor))
  357. return false;
  358. }
  359. else
  360. {
  361. if (! writeSource (compressedData))
  362. return false;
  363. }
  364. compressedSize = (int) compressedData.getDataSize();
  365. headerStart = (int) (target.getPosition() - overallStartPosition);
  366. target.writeInt (0x04034b50);
  367. writeFlagsAndSizes (target);
  368. target << storedPathname
  369. << compressedData;
  370. return true;
  371. }
  372. bool writeDirectoryEntry (OutputStream& target)
  373. {
  374. target.writeInt (0x02014b50);
  375. target.writeShort (20); // version written
  376. writeFlagsAndSizes (target);
  377. target.writeShort (0); // comment length
  378. target.writeShort (0); // start disk num
  379. target.writeShort (0); // internal attributes
  380. target.writeInt (0); // external attributes
  381. target.writeInt (headerStart);
  382. target << storedPathname;
  383. return true;
  384. }
  385. private:
  386. const File file;
  387. String storedPathname;
  388. int compressionLevel, compressedSize, headerStart;
  389. unsigned long checksum;
  390. void writeTimeAndDate (OutputStream& target) const
  391. {
  392. const Time t (file.getLastModificationTime());
  393. target.writeShort ((short) (t.getSeconds() + (t.getMinutes() << 5) + (t.getHours() << 11)));
  394. target.writeShort ((short) (t.getDayOfMonth() + ((t.getMonth() + 1) << 5) + ((t.getYear() - 1980) << 9)));
  395. }
  396. bool writeSource (OutputStream& target)
  397. {
  398. checksum = 0;
  399. FileInputStream input (file);
  400. if (input.failedToOpen())
  401. return false;
  402. const int bufferSize = 2048;
  403. HeapBlock<unsigned char> buffer (bufferSize);
  404. while (! input.isExhausted())
  405. {
  406. const int bytesRead = input.read (buffer, bufferSize);
  407. if (bytesRead < 0)
  408. return false;
  409. checksum = juce_crc32 (checksum, buffer, (unsigned int) bytesRead);
  410. target.write (buffer, bytesRead);
  411. }
  412. return true;
  413. }
  414. void writeFlagsAndSizes (OutputStream& target) const
  415. {
  416. target.writeShort (10); // version needed
  417. target.writeShort (0); // flags
  418. target.writeShort (compressionLevel > 0 ? (short) 8 : (short) 0);
  419. writeTimeAndDate (target);
  420. target.writeInt ((int) checksum);
  421. target.writeInt (compressedSize);
  422. target.writeInt ((int) file.getSize());
  423. target.writeShort ((short) storedPathname.toUTF8().sizeInBytes() - 1);
  424. target.writeShort (0); // extra field length
  425. }
  426. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Item);
  427. };
  428. //=============================================================================
  429. ZipFile::Builder::Builder() {}
  430. ZipFile::Builder::~Builder() {}
  431. void ZipFile::Builder::addFile (const File& fileToAdd, const int compressionLevel, const String& storedPathName)
  432. {
  433. items.add (new Item (fileToAdd, compressionLevel, storedPathName));
  434. }
  435. bool ZipFile::Builder::writeToStream (OutputStream& target, double* const progress) const
  436. {
  437. const int64 fileStart = target.getPosition();
  438. for (int i = 0; i < items.size(); ++i)
  439. {
  440. if (progress != nullptr)
  441. *progress = (i + 0.5) / items.size();
  442. if (! items.getUnchecked (i)->writeData (target, fileStart))
  443. return false;
  444. }
  445. const int64 directoryStart = target.getPosition();
  446. for (int i = 0; i < items.size(); ++i)
  447. if (! items.getUnchecked (i)->writeDirectoryEntry (target))
  448. return false;
  449. const int64 directoryEnd = target.getPosition();
  450. target.writeInt (0x06054b50);
  451. target.writeShort (0);
  452. target.writeShort (0);
  453. target.writeShort ((short) items.size());
  454. target.writeShort ((short) items.size());
  455. target.writeInt ((int) (directoryEnd - directoryStart));
  456. target.writeInt ((int) (directoryStart - fileStart));
  457. target.writeShort (0);
  458. if (progress != nullptr)
  459. *progress = 1.0;
  460. return true;
  461. }