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.

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