juce_ZipFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. class ZipFile::ZipEntryHolder
  22. {
  23. public:
  24. ZipEntryHolder (const char* const buffer, const int fileNameLen)
  25. {
  26. entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  27. const int time = ByteOrder::littleEndianShort (buffer + 12);
  28. const int date = ByteOrder::littleEndianShort (buffer + 14);
  29. entry.fileTime = getFileTimeFromRawEncodings (time, date);
  30. compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  31. compressedSize = (size_t) ByteOrder::littleEndianInt (buffer + 20);
  32. entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  33. streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  34. }
  35. struct FileNameComparator
  36. {
  37. static int compareElements (const ZipEntryHolder* first, const ZipEntryHolder* second)
  38. {
  39. return first->entry.filename.compare (second->entry.filename);
  40. }
  41. };
  42. ZipEntry entry;
  43. size_t streamOffset;
  44. size_t compressedSize;
  45. bool compressed;
  46. private:
  47. static Time getFileTimeFromRawEncodings (int time, int date)
  48. {
  49. const int year = 1980 + (date >> 9);
  50. const int month = ((date >> 5) & 15) - 1;
  51. const int day = date & 31;
  52. const int hours = time >> 11;
  53. const int minutes = (time >> 5) & 63;
  54. const int seconds = (time & 31) << 1;
  55. return Time (year, month, day, hours, minutes, seconds);
  56. }
  57. };
  58. //==============================================================================
  59. namespace
  60. {
  61. int findEndOfZipEntryTable (InputStream& input, int& numEntries)
  62. {
  63. BufferedInputStream in (input, 8192);
  64. in.setPosition (in.getTotalLength());
  65. int64 pos = in.getPosition();
  66. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  67. char buffer [32] = { 0 };
  68. while (pos > lowestPos)
  69. {
  70. in.setPosition (pos - 22);
  71. pos = in.getPosition();
  72. memcpy (buffer + 22, buffer, 4);
  73. if (in.read (buffer, 22) != 22)
  74. return 0;
  75. for (int i = 0; i < 22; ++i)
  76. {
  77. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  78. {
  79. in.setPosition (pos + i);
  80. in.read (buffer, 22);
  81. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  82. return (int) ByteOrder::littleEndianInt (buffer + 16);
  83. }
  84. }
  85. }
  86. return 0;
  87. }
  88. }
  89. //==============================================================================
  90. class ZipFile::ZipInputStream : public InputStream
  91. {
  92. public:
  93. ZipInputStream (ZipFile& zf, ZipFile::ZipEntryHolder& zei)
  94. : file (zf),
  95. zipEntryHolder (zei),
  96. pos (0),
  97. headerSize (0),
  98. inputStream (zf.inputStream)
  99. {
  100. if (zf.inputSource != nullptr)
  101. {
  102. inputStream = streamToDelete = file.inputSource->createInputStream();
  103. }
  104. else
  105. {
  106. #if JUCE_DEBUG
  107. zf.streamCounter.numOpenStreams++;
  108. #endif
  109. }
  110. char buffer [30];
  111. if (inputStream != nullptr
  112. && inputStream->setPosition ((int64) zei.streamOffset)
  113. && inputStream->read (buffer, 30) == 30
  114. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  115. {
  116. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  117. + ByteOrder::littleEndianShort (buffer + 28);
  118. }
  119. }
  120. ~ZipInputStream()
  121. {
  122. #if JUCE_DEBUG
  123. if (inputStream != nullptr && inputStream == file.inputStream)
  124. file.streamCounter.numOpenStreams--;
  125. #endif
  126. }
  127. int64 getTotalLength()
  128. {
  129. return (int64) zipEntryHolder.compressedSize;
  130. }
  131. int read (void* buffer, int howMany)
  132. {
  133. if (headerSize <= 0)
  134. return 0;
  135. howMany = (int) jmin ((int64) howMany, ((int64) zipEntryHolder.compressedSize) - pos);
  136. if (inputStream == nullptr)
  137. return 0;
  138. int num;
  139. if (inputStream == file.inputStream)
  140. {
  141. const ScopedLock sl (file.lock);
  142. inputStream->setPosition (pos + (int64) zipEntryHolder.streamOffset + headerSize);
  143. num = inputStream->read (buffer, howMany);
  144. }
  145. else
  146. {
  147. inputStream->setPosition (pos + (int64) zipEntryHolder.streamOffset + headerSize);
  148. num = inputStream->read (buffer, howMany);
  149. }
  150. pos += num;
  151. return num;
  152. }
  153. bool isExhausted()
  154. {
  155. return headerSize <= 0 || pos >= (int64) zipEntryHolder.compressedSize;
  156. }
  157. int64 getPosition()
  158. {
  159. return pos;
  160. }
  161. bool setPosition (int64 newPos)
  162. {
  163. pos = jlimit ((int64) 0, (int64) zipEntryHolder.compressedSize, newPos);
  164. return true;
  165. }
  166. private:
  167. ZipFile& file;
  168. ZipEntryHolder zipEntryHolder;
  169. int64 pos;
  170. int headerSize;
  171. InputStream* inputStream;
  172. ScopedPointer<InputStream> streamToDelete;
  173. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ZipInputStream)
  174. };
  175. //==============================================================================
  176. ZipFile::ZipFile (InputStream* const stream, const bool deleteStreamWhenDestroyed)
  177. : inputStream (stream)
  178. {
  179. if (deleteStreamWhenDestroyed)
  180. streamToDelete = inputStream;
  181. init();
  182. }
  183. ZipFile::ZipFile (InputStream& stream)
  184. : inputStream (&stream)
  185. {
  186. init();
  187. }
  188. ZipFile::ZipFile (const File& file)
  189. : inputStream (nullptr),
  190. inputSource (new FileInputSource (file))
  191. {
  192. init();
  193. }
  194. ZipFile::ZipFile (InputSource* const source)
  195. : inputStream (nullptr),
  196. inputSource (source)
  197. {
  198. init();
  199. }
  200. ZipFile::~ZipFile()
  201. {
  202. entries.clear();
  203. }
  204. #if JUCE_DEBUG
  205. ZipFile::OpenStreamCounter::~OpenStreamCounter()
  206. {
  207. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  208. zipfile, but you've forgotten to delete that stream object before deleting the file..
  209. Streams can't be kept open after the file is deleted because they need to share the input
  210. stream that is managed by the ZipFile object.
  211. */
  212. jassert (numOpenStreams == 0);
  213. }
  214. #endif
  215. //==============================================================================
  216. int ZipFile::getNumEntries() const noexcept
  217. {
  218. return entries.size();
  219. }
  220. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const noexcept
  221. {
  222. if (ZipEntryHolder* const zei = entries [index])
  223. return &(zei->entry);
  224. return nullptr;
  225. }
  226. int ZipFile::getIndexOfFileName (const String& fileName) const noexcept
  227. {
  228. for (int i = 0; i < entries.size(); ++i)
  229. if (entries.getUnchecked (i)->entry.filename == fileName)
  230. return i;
  231. return -1;
  232. }
  233. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const noexcept
  234. {
  235. return getEntry (getIndexOfFileName (fileName));
  236. }
  237. InputStream* ZipFile::createStreamForEntry (const int index)
  238. {
  239. InputStream* stream = nullptr;
  240. if (ZipEntryHolder* const zei = entries[index])
  241. {
  242. stream = new ZipInputStream (*this, *zei);
  243. if (zei->compressed)
  244. {
  245. stream = new GZIPDecompressorInputStream (stream, true, true, (int64) 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. InputStream* ZipFile::createStreamForEntry (const ZipEntry& entry)
  253. {
  254. for (int i = 0; i < entries.size(); ++i)
  255. if (&entries.getUnchecked (i)->entry == &entry)
  256. return createStreamForEntry (i);
  257. return nullptr;
  258. }
  259. void ZipFile::sortEntriesByFilename()
  260. {
  261. ZipEntryHolder::FileNameComparator sorter;
  262. entries.sort (sorter);
  263. }
  264. //==============================================================================
  265. void ZipFile::init()
  266. {
  267. ScopedPointer <InputStream> toDelete;
  268. InputStream* in = inputStream;
  269. if (inputSource != nullptr)
  270. {
  271. in = inputSource->createInputStream();
  272. toDelete = in;
  273. }
  274. if (in != nullptr)
  275. {
  276. int numEntries = 0;
  277. int pos = findEndOfZipEntryTable (*in, numEntries);
  278. if (pos >= 0 && pos < in->getTotalLength())
  279. {
  280. const int size = (int) (in->getTotalLength() - pos);
  281. in->setPosition (pos);
  282. MemoryBlock headerData;
  283. if (in->readIntoMemoryBlock (headerData, size) == size)
  284. {
  285. pos = 0;
  286. for (int i = 0; i < numEntries; ++i)
  287. {
  288. if (pos + 46 > size)
  289. break;
  290. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  291. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  292. if (pos + 46 + fileNameLen > size)
  293. break;
  294. entries.add (new ZipEntryHolder (buffer, fileNameLen));
  295. pos += 46 + fileNameLen
  296. + ByteOrder::littleEndianShort (buffer + 30)
  297. + ByteOrder::littleEndianShort (buffer + 32);
  298. }
  299. }
  300. }
  301. }
  302. }
  303. Result ZipFile::uncompressTo (const File& targetDirectory,
  304. const bool shouldOverwriteFiles)
  305. {
  306. for (int i = 0; i < entries.size(); ++i)
  307. {
  308. Result result (uncompressEntry (i, targetDirectory, shouldOverwriteFiles));
  309. if (result.failed())
  310. return result;
  311. }
  312. return Result::ok();
  313. }
  314. Result ZipFile::uncompressEntry (const int index,
  315. const File& targetDirectory,
  316. bool shouldOverwriteFiles)
  317. {
  318. const ZipEntryHolder* zei = entries.getUnchecked (index);
  319. #if JUCE_WINDOWS
  320. const String entryPath (zei->entry.filename);
  321. #else
  322. const String entryPath (zei->entry.filename.replaceCharacter ('\\', '/'));
  323. #endif
  324. const File targetFile (targetDirectory.getChildFile (entryPath));
  325. if (entryPath.endsWithChar ('/') || entryPath.endsWithChar ('\\'))
  326. return targetFile.createDirectory(); // (entry is a directory, not a file)
  327. ScopedPointer<InputStream> in (createStreamForEntry (index));
  328. if (in == nullptr)
  329. return Result::fail ("Failed to open the zip file for reading");
  330. if (targetFile.exists())
  331. {
  332. if (! shouldOverwriteFiles)
  333. return Result::ok();
  334. if (! targetFile.deleteFile())
  335. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  336. }
  337. if (! targetFile.getParentDirectory().createDirectory())
  338. return Result::fail ("Failed to create target folder: " + targetFile.getParentDirectory().getFullPathName());
  339. {
  340. FileOutputStream out (targetFile);
  341. if (out.failedToOpen())
  342. return Result::fail ("Failed to write to target file: " + targetFile.getFullPathName());
  343. out << *in;
  344. }
  345. targetFile.setCreationTime (zei->entry.fileTime);
  346. targetFile.setLastModificationTime (zei->entry.fileTime);
  347. targetFile.setLastAccessTime (zei->entry.fileTime);
  348. return Result::ok();
  349. }
  350. //=============================================================================
  351. class ZipFile::Builder::Item
  352. {
  353. public:
  354. Item (const File& f, InputStream* s, const int compression, const String& storedPath, Time time)
  355. : file (f), stream (s), storedPathname (storedPath),
  356. fileTime (time), compressionLevel (compression),
  357. compressedSize (0), uncompressedSize (0), headerStart (0), checksum (0)
  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 = (int) compressedData.getDataSize();
  376. headerStart = (int) (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 (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. int compressionLevel, compressedSize, uncompressedSize, headerStart;
  402. unsigned long checksum;
  403. static void writeTimeAndDate (OutputStream& target, Time t)
  404. {
  405. target.writeShort ((short) (t.getSeconds() + (t.getMinutes() << 5) + (t.getHours() << 11)));
  406. target.writeShort ((short) (t.getDayOfMonth() + ((t.getMonth() + 1) << 5) + ((t.getYear() - 1980) << 9)));
  407. }
  408. bool writeSource (OutputStream& target)
  409. {
  410. if (stream == nullptr)
  411. {
  412. stream = file.createInputStream();
  413. if (stream == nullptr)
  414. return false;
  415. }
  416. checksum = 0;
  417. uncompressedSize = 0;
  418. const int bufferSize = 4096;
  419. HeapBlock<unsigned char> buffer (bufferSize);
  420. while (! stream->isExhausted())
  421. {
  422. const int bytesRead = stream->read (buffer, bufferSize);
  423. if (bytesRead < 0)
  424. return false;
  425. checksum = zlibNamespace::crc32 (checksum, buffer, (unsigned int) bytesRead);
  426. target.write (buffer, (size_t) bytesRead);
  427. uncompressedSize += bytesRead;
  428. }
  429. stream = nullptr;
  430. return true;
  431. }
  432. void writeFlagsAndSizes (OutputStream& target) const
  433. {
  434. target.writeShort (10); // version needed
  435. target.writeShort ((short) (1 << 11)); // this flag indicates UTF-8 filename encoding
  436. target.writeShort (compressionLevel > 0 ? (short) 8 : (short) 0);
  437. writeTimeAndDate (target, fileTime);
  438. target.writeInt ((int) checksum);
  439. target.writeInt (compressedSize);
  440. target.writeInt (uncompressedSize);
  441. target.writeShort ((short) storedPathname.toUTF8().sizeInBytes() - 1);
  442. target.writeShort (0); // extra field length
  443. }
  444. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Item)
  445. };
  446. //=============================================================================
  447. ZipFile::Builder::Builder() {}
  448. ZipFile::Builder::~Builder() {}
  449. void ZipFile::Builder::addFile (const File& file, const int compression, const String& path)
  450. {
  451. items.add (new Item (file, nullptr, compression,
  452. path.isEmpty() ? file.getFileName() : path,
  453. file.getLastModificationTime()));
  454. }
  455. void ZipFile::Builder::addEntry (InputStream* stream, int compression, const String& path, Time time)
  456. {
  457. jassert (stream != nullptr); // must not be null!
  458. jassert (path.isNotEmpty());
  459. items.add (new Item (File(), stream, compression, path, time));
  460. }
  461. bool ZipFile::Builder::writeToStream (OutputStream& target, double* const progress) const
  462. {
  463. const int64 fileStart = target.getPosition();
  464. for (int i = 0; i < items.size(); ++i)
  465. {
  466. if (progress != nullptr)
  467. *progress = (i + 0.5) / items.size();
  468. if (! items.getUnchecked (i)->writeData (target, fileStart))
  469. return false;
  470. }
  471. const int64 directoryStart = target.getPosition();
  472. for (int i = 0; i < items.size(); ++i)
  473. if (! items.getUnchecked (i)->writeDirectoryEntry (target))
  474. return false;
  475. const int64 directoryEnd = target.getPosition();
  476. target.writeInt (0x06054b50);
  477. target.writeShort (0);
  478. target.writeShort (0);
  479. target.writeShort ((short) items.size());
  480. target.writeShort ((short) items.size());
  481. target.writeInt ((int) (directoryEnd - directoryStart));
  482. target.writeInt ((int) (directoryStart - fileStart));
  483. target.writeShort (0);
  484. if (progress != nullptr)
  485. *progress = 1.0;
  486. return true;
  487. }