zip.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619
  1. /****************************************************************************
  2. ** Filename: zip.cpp
  3. ** Last updated [dd/mm/yyyy]: 01/02/2007
  4. **
  5. ** pkzip 2.0 file compression.
  6. **
  7. ** Some of the code has been inspired by other open source projects,
  8. ** (mainly Info-Zip and Gilles Vollant's minizip).
  9. ** Compression and decompression actually uses the zlib library.
  10. **
  11. ** Copyright (C) 2007-2012 Angius Fabrizio. All rights reserved.
  12. **
  13. ** This file is part of the OSDaB project (http://osdab.42cows.org/).
  14. **
  15. ** This file may be distributed and/or modified under the terms of the
  16. ** GNU General Public License version 2 as published by the Free Software
  17. ** Foundation and appearing in the file LICENSE.GPL included in the
  18. ** packaging of this file.
  19. **
  20. ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
  21. ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  22. **
  23. ** See the file LICENSE.GPL that came with this software distribution or
  24. ** visit http://www.gnu.org/copyleft/gpl.html for GPL licensing information.
  25. **
  26. **********************************************************************/
  27. #include "zip.h"
  28. #include "zip_p.h"
  29. #include "zipentry_p.h"
  30. // we only use this to seed the random number generator
  31. #include <ctime>
  32. #include <QtCore/QCoreApplication>
  33. #include <QtCore/QDateTime>
  34. #include <QtCore/QDir>
  35. #include <QtCore/QFile>
  36. #include <QtCore/QMap>
  37. #include <QtCore/QString>
  38. #include <QtCore/QStringList>
  39. // You can remove this #include if you replace the qDebug() statements.
  40. #include <QtCore/QtDebug>
  41. /*! #define OSDAB_ZIP_NO_PNG_RLE to disable the use of Z_RLE compression strategy with
  42. PNG files (achieves slightly better compression levels according to the authors).
  43. */
  44. // #define OSDAB_ZIP_NO_PNG_RLE
  45. #define OSDAB_ZIP_NO_DEBUG
  46. //! Local header size (including signature, excluding variable length fields)
  47. #define ZIP_LOCAL_HEADER_SIZE 30
  48. //! Encryption header size
  49. #define ZIP_LOCAL_ENC_HEADER_SIZE 12
  50. //! Data descriptor size (signature included)
  51. #define ZIP_DD_SIZE_WS 16
  52. //! Central Directory record size (signature included)
  53. #define ZIP_CD_SIZE 46
  54. //! End of Central Directory record size (signature included)
  55. #define ZIP_EOCD_SIZE 22
  56. // Some offsets inside a local header record (signature included)
  57. #define ZIP_LH_OFF_VERS 4
  58. #define ZIP_LH_OFF_GPFLAG 6
  59. #define ZIP_LH_OFF_CMET 8
  60. #define ZIP_LH_OFF_MODT 10
  61. #define ZIP_LH_OFF_MODD 12
  62. #define ZIP_LH_OFF_CRC 14
  63. #define ZIP_LH_OFF_CSIZE 18
  64. #define ZIP_LH_OFF_USIZE 22
  65. #define ZIP_LH_OFF_NAMELEN 26
  66. #define ZIP_LH_OFF_XLEN 28
  67. // Some offsets inside a data descriptor record (including signature)
  68. #define ZIP_DD_OFF_CRC32 4
  69. #define ZIP_DD_OFF_CSIZE 8
  70. #define ZIP_DD_OFF_USIZE 12
  71. // Some offsets inside a Central Directory record (including signature)
  72. #define ZIP_CD_OFF_MADEBY 4
  73. #define ZIP_CD_OFF_VERSION 6
  74. #define ZIP_CD_OFF_GPFLAG 8
  75. #define ZIP_CD_OFF_CMET 10
  76. #define ZIP_CD_OFF_MODT 12
  77. #define ZIP_CD_OFF_MODD 14
  78. #define ZIP_CD_OFF_CRC 16
  79. #define ZIP_CD_OFF_CSIZE 20
  80. #define ZIP_CD_OFF_USIZE 24
  81. #define ZIP_CD_OFF_NAMELEN 28
  82. #define ZIP_CD_OFF_XLEN 30
  83. #define ZIP_CD_OFF_COMMLEN 32
  84. #define ZIP_CD_OFF_DISKSTART 34
  85. #define ZIP_CD_OFF_IATTR 36
  86. #define ZIP_CD_OFF_EATTR 38
  87. #define ZIP_CD_OFF_LHOFF 42
  88. // Some offsets inside a EOCD record (including signature)
  89. #define ZIP_EOCD_OFF_DISKNUM 4
  90. #define ZIP_EOCD_OFF_CDDISKNUM 6
  91. #define ZIP_EOCD_OFF_ENTRIES 8
  92. #define ZIP_EOCD_OFF_CDENTRIES 10
  93. #define ZIP_EOCD_OFF_CDSIZE 12
  94. #define ZIP_EOCD_OFF_CDOFF 16
  95. #define ZIP_EOCD_OFF_COMMLEN 20
  96. //! PKZip version for archives created by this API
  97. #define ZIP_VERSION 0x14
  98. //! Do not store very small files as the compression headers overhead would be to big
  99. #define ZIP_COMPRESSION_THRESHOLD 60
  100. /*!
  101. \class Zip zip.h
  102. \brief Zip file compression.
  103. Some quick usage examples.
  104. \verbatim
  105. Suppose you have this directory structure:
  106. /home/user/dir1/file1.1
  107. /home/user/dir1/file1.2
  108. /home/user/dir1/dir1.1/
  109. /home/user/dir1/dir1.2/file1.2.1
  110. EXAMPLE 1:
  111. myZipInstance.addDirectory("/home/user/dir1");
  112. RESULT:
  113. Beheaves like any common zip software and creates a zip file with this structure:
  114. dir1/file1.1
  115. dir1/file1.2
  116. dir1/dir1.1/
  117. dir1/dir1.2/file1.2.1
  118. EXAMPLE 2:
  119. myZipInstance.addDirectory("/home/user/dir1", "myRoot/myFolder");
  120. RESULT:
  121. Adds a custom root to the paths and creates a zip file with this structure:
  122. myRoot/myFolder/dir1/file1.1
  123. myRoot/myFolder/dir1/file1.2
  124. myRoot/myFolder/dir1/dir1.1/
  125. myRoot/myFolder/dir1/dir1.2/file1.2.1
  126. EXAMPLE 3:
  127. myZipInstance.addDirectory("/home/user/dir1", Zip::AbsolutePaths);
  128. NOTE:
  129. Same as calling addDirectory(SOME_PATH, PARENT_PATH_of_SOME_PATH).
  130. RESULT:
  131. Preserves absolute paths and creates a zip file with this structure:
  132. /home/user/dir1/file1.1
  133. /home/user/dir1/file1.2
  134. /home/user/dir1/dir1.1/
  135. /home/user/dir1/dir1.2/file1.2.1
  136. EXAMPLE 4:
  137. myZipInstance.setPassword("hellopass");
  138. myZipInstance.addDirectory("/home/user/dir1", "/");
  139. RESULT:
  140. Adds and encrypts the files in /home/user/dir1, creating the following zip structure:
  141. /dir1/file1.1
  142. /dir1/file1.2
  143. /dir1/dir1.1/
  144. /dir1/dir1.2/file1.2.1
  145. EXAMPLE 5:
  146. myZipInstance.addDirectory("/home/user/dir1", Zip::IgnoreRoot);
  147. RESULT:
  148. Adds the files in /home/user/dir1 but doesn't create the top level
  149. directory:
  150. file1.1
  151. file1.2
  152. dir1.1/
  153. dir1.2/file1.2.1
  154. EXAMPLE 5:
  155. myZipInstance.addDirectory("/home/user/dir1", "data/backup", Zip::IgnoreRoot);
  156. RESULT:
  157. Adds the files in /home/user/dir1 but uses "data/backup" as top level
  158. directory instead of "dir1":
  159. data/backup/file1.1
  160. data/backup/file1.2
  161. data/backup/dir1.1/
  162. data/backup/dir1.2/file1.2.1
  163. \endverbatim
  164. */
  165. /*! \enum Zip::ErrorCode The result of a compression operation.
  166. \value Zip::Ok No error occurred.
  167. \value Zip::ZlibInit Failed to init or load the zlib library.
  168. \value Zip::ZlibError The zlib library returned some error.
  169. \value Zip::FileExists The file already exists and will not be overwritten.
  170. \value Zip::OpenFailed Unable to create or open a device.
  171. \value Zip::NoOpenArchive CreateArchive() has not been called yet.
  172. \value Zip::FileNotFound File or directory does not exist.
  173. \value Zip::ReadFailed Reading of a file failed.
  174. \value Zip::WriteFailed Writing of a file failed.
  175. \value Zip::SeekFailed Seek failed.
  176. */
  177. /*! \enum Zip::CompressionLevel Returns the result of a decompression operation.
  178. \value Zip::Store No compression.
  179. \value Zip::Deflate1 Deflate compression level 1(lowest compression).
  180. \value Zip::Deflate1 Deflate compression level 2.
  181. \value Zip::Deflate1 Deflate compression level 3.
  182. \value Zip::Deflate1 Deflate compression level 4.
  183. \value Zip::Deflate1 Deflate compression level 5.
  184. \value Zip::Deflate1 Deflate compression level 6.
  185. \value Zip::Deflate1 Deflate compression level 7.
  186. \value Zip::Deflate1 Deflate compression level 8.
  187. \value Zip::Deflate1 Deflate compression level 9 (maximum compression).
  188. \value Zip::AutoCPU Adapt compression level to CPU speed (faster CPU => better compression).
  189. \value Zip::AutoMIME Adapt compression level to MIME type of the file being compressed.
  190. \value Zip::AutoFull Use both CPU and MIME type detection.
  191. */
  192. namespace {
  193. struct ZippedDir {
  194. bool init;
  195. QString actualRoot;
  196. int files;
  197. ZippedDir() : init(false), actualRoot(), files(0) {}
  198. };
  199. void checkRootPath(QString& path)
  200. {
  201. const bool isUnixRoot = path.length() == 1 && path.at(0) == QLatin1Char('/');
  202. if (!path.isEmpty() && !isUnixRoot) {
  203. while (path.endsWith(QLatin1String("\\")))
  204. path.truncate(path.length() - 1);
  205. int sepCount = 0;
  206. for (int i = path.length()-1; i >= 0; --i) {
  207. if (path.at(i) == QLatin1Char('/'))
  208. ++sepCount;
  209. else break;
  210. }
  211. if (sepCount > 1)
  212. path.truncate(path.length() - (sepCount-1));
  213. else if (sepCount == 0)
  214. path.append(QLatin1String("/"));
  215. }
  216. }
  217. }
  218. //////////////////////////////////////////////////////////////////////////
  219. OSDAB_BEGIN_NAMESPACE(Zip)
  220. /************************************************************************
  221. Private interface
  222. *************************************************************************/
  223. //! \internal
  224. ZipPrivate::ZipPrivate() :
  225. headers(0),
  226. device(0),
  227. file(0),
  228. uBuffer(0),
  229. crcTable(0),
  230. comment(),
  231. password()
  232. {
  233. // keep an unsigned pointer so we avoid to over bloat the code with casts
  234. uBuffer = (unsigned char*) buffer1;
  235. crcTable = get_crc_table();
  236. }
  237. //! \internal
  238. ZipPrivate::~ZipPrivate()
  239. {
  240. closeArchive();
  241. }
  242. //! \internal
  243. Zip::ErrorCode ZipPrivate::createArchive(QIODevice* dev)
  244. {
  245. Q_ASSERT(dev);
  246. if (device)
  247. closeArchive();
  248. device = dev;
  249. if (device != file)
  250. connect(device, SIGNAL(destroyed(QObject*)), this, SLOT(deviceDestroyed(QObject*)));
  251. if (!device->isOpen()) {
  252. if (!device->open(QIODevice::ReadOnly)) {
  253. delete device;
  254. device = 0;
  255. qDebug() << "Unable to open device for writing.";
  256. return Zip::OpenFailed;
  257. }
  258. }
  259. headers = new QMap<QString,ZipEntryP*>;
  260. return Zip::Ok;
  261. }
  262. //! \internal
  263. void ZipPrivate::deviceDestroyed(QObject*)
  264. {
  265. qDebug("Unexpected device destruction detected.");
  266. do_closeArchive();
  267. }
  268. /*! Returns true if an entry for \p info has already been added.
  269. Uses file size and lower case absolute path to compare entries.
  270. */
  271. bool ZipPrivate::containsEntry(const QFileInfo& info) const
  272. {
  273. if (!headers || headers->isEmpty())
  274. return false;
  275. const qint64 sz = info.size();
  276. const QString path = info.absoluteFilePath().toLower();
  277. QMap<QString,ZipEntryP*>::ConstIterator b = headers->constBegin();
  278. const QMap<QString,ZipEntryP*>::ConstIterator e = headers->constEnd();
  279. while (b != e) {
  280. const ZipEntryP* e = b.value();
  281. if (e->fileSize == sz && e->absolutePath == path)
  282. return true;
  283. ++b;
  284. }
  285. return false;
  286. }
  287. //! \internal Actual implementation of the addDirectory* methods.
  288. Zip::ErrorCode ZipPrivate::addDirectory(const QString& path, const QString& root,
  289. Zip::CompressionOptions options, Zip::CompressionLevel level, int hierarchyLevel,
  290. int* addedFiles)
  291. {
  292. if (addedFiles)
  293. ++(*addedFiles);
  294. // Bad boy didn't call createArchive() yet :)
  295. if (!device)
  296. return Zip::NoOpenArchive;
  297. QDir dir(path);
  298. if (!dir.exists())
  299. return Zip::FileNotFound;
  300. // Remove any trailing separator
  301. QString actualRoot = root.trimmed();
  302. // Preserve Unix root but make sure the path ends only with a single
  303. // unix like separator
  304. ::checkRootPath(actualRoot);
  305. // QDir::cleanPath() fixes some issues with QDir::dirName()
  306. QFileInfo current(QDir::cleanPath(path));
  307. const bool path_absolute = options.testFlag(Zip::AbsolutePaths);
  308. const bool path_ignore = options.testFlag(Zip::IgnorePaths);
  309. const bool path_noroot = options.testFlag(Zip::IgnoreRoot);
  310. if (path_absolute && !path_ignore && !path_noroot) {
  311. QString absolutePath = extractRoot(path, options);
  312. if (!absolutePath.isEmpty() && absolutePath != QLatin1String("/"))
  313. absolutePath.append(QLatin1String("/"));
  314. actualRoot.append(absolutePath);
  315. }
  316. const bool skipDirName = !hierarchyLevel && path_noroot;
  317. if (!path_ignore && !skipDirName) {
  318. actualRoot.append(QDir(current.absoluteFilePath()).dirName());
  319. actualRoot.append(QLatin1String("/"));
  320. }
  321. // actualRoot now contains the path of the file relative to the zip archive
  322. // with a trailing /
  323. const bool skipBad = options & Zip::SkipBadFiles;
  324. const bool noDups = options & Zip::CheckForDuplicates;
  325. const QDir::Filters dir_filter =
  326. QDir::Files |
  327. QDir::Dirs |
  328. QDir::NoDotAndDotDot |
  329. QDir::NoSymLinks;
  330. const QDir::SortFlags dir_sort =
  331. QDir::DirsFirst;
  332. QFileInfoList list = dir.entryInfoList(dir_filter, dir_sort);
  333. Zip::ErrorCode ec = Zip::Ok;
  334. bool filesAdded = false;
  335. Zip::CompressionOptions recursionOptions;
  336. if (path_ignore)
  337. recursionOptions |= Zip::IgnorePaths;
  338. else recursionOptions |= Zip::RelativePaths;
  339. for (int i = 0; i < list.size(); ++i) {
  340. QFileInfo info = list.at(i);
  341. const QString absPath = info.absoluteFilePath();
  342. if (noDups && containsEntry(info))
  343. continue;
  344. if (info.isDir()) {
  345. // Recursion
  346. ec = addDirectory(absPath, actualRoot, recursionOptions,
  347. level, hierarchyLevel + 1, addedFiles);
  348. } else {
  349. ec = createEntry(info, actualRoot, level);
  350. if (ec == Zip::Ok) {
  351. filesAdded = true;
  352. if (addedFiles)
  353. ++(*addedFiles);
  354. }
  355. }
  356. if (ec != Zip::Ok && !skipBad) {
  357. break;
  358. }
  359. }
  360. // We need an explicit record for this dir
  361. // Non-empty directories don't need it because they have a path component in the filename
  362. if (!filesAdded && !path_ignore)
  363. ec = createEntry(current, actualRoot, level);
  364. return ec;
  365. }
  366. //! \internal Actual implementation of the addFile methods.
  367. Zip::ErrorCode ZipPrivate::addFiles(const QStringList& files, const QString& root,
  368. Zip::CompressionOptions options, Zip::CompressionLevel level,
  369. int* addedFiles)
  370. {
  371. if (addedFiles)
  372. *addedFiles = 0;
  373. const bool skipBad = options & Zip::SkipBadFiles;
  374. const bool noDups = options & Zip::CheckForDuplicates;
  375. // Bad boy didn't call createArchive() yet :)
  376. if (!device)
  377. return Zip::NoOpenArchive;
  378. QFileInfoList paths;
  379. paths.reserve(files.size());
  380. for (int i = 0; i < files.size(); ++i) {
  381. QFileInfo info(files.at(i));
  382. if (noDups && (paths.contains(info) || containsEntry(info)))
  383. continue;
  384. if (!info.exists() || !info.isReadable()) {
  385. if (skipBad) {
  386. continue;
  387. } else {
  388. return Zip::FileNotFound;
  389. }
  390. }
  391. paths.append(info);
  392. }
  393. if (paths.isEmpty())
  394. return Zip::Ok;
  395. // Remove any trailing separator
  396. QString actualRoot = root.trimmed();
  397. // Preserve Unix root but make sure the path ends only with a single
  398. // unix like separator
  399. ::checkRootPath(actualRoot);
  400. const bool path_absolute = options.testFlag(Zip::AbsolutePaths);
  401. const bool path_ignore = options.testFlag(Zip::IgnorePaths);
  402. const bool path_noroot = options.testFlag(Zip::IgnoreRoot);
  403. Zip::ErrorCode ec = Zip::Ok;
  404. QHash<QString, ZippedDir> dirMap;
  405. for (int i = 0; i < paths.size(); ++i) {
  406. const QFileInfo& info = paths.at(i);
  407. const QString path = QFileInfo(QDir::cleanPath(info.absolutePath())).absolutePath();
  408. ZippedDir& zd = dirMap[path];
  409. if (!zd.init) {
  410. zd.init = true;
  411. zd.actualRoot = actualRoot;
  412. if (path_absolute && !path_ignore && !path_noroot) {
  413. QString absolutePath = extractRoot(path, options);
  414. if (!absolutePath.isEmpty() && absolutePath != QLatin1String("/"))
  415. absolutePath.append(QLatin1String("/"));
  416. zd.actualRoot.append(absolutePath);
  417. }
  418. if (!path_ignore && !path_noroot) {
  419. zd.actualRoot.append(QDir(path).dirName());
  420. zd.actualRoot.append(QLatin1String("/"));
  421. }
  422. }
  423. // zd.actualRoot now contains the path of the file relative to the zip archive
  424. // with a trailing /
  425. if (info.isDir()) {
  426. // Recursion
  427. ec = addDirectory(info.absoluteFilePath(), actualRoot, options,
  428. level, 1, addedFiles);
  429. } else {
  430. ec = createEntry(info, actualRoot, level);
  431. if (ec == Zip::Ok) {
  432. ++zd.files;
  433. if (addedFiles)
  434. ++(*addedFiles);
  435. }
  436. }
  437. if (ec != Zip::Ok && !skipBad) {
  438. break;
  439. }
  440. }
  441. // Create explicit records for empty directories
  442. if (!path_ignore) {
  443. QHash<QString, ZippedDir>::ConstIterator b = dirMap.constBegin();
  444. const QHash<QString, ZippedDir>::ConstIterator e = dirMap.constEnd();
  445. while (b != e) {
  446. const ZippedDir& zd = b.value();
  447. if (zd.files <= 0) {
  448. ec = createEntry(b.key(), zd.actualRoot, level);
  449. }
  450. ++b;
  451. }
  452. }
  453. return ec;
  454. }
  455. //! \internal \p file must be a file and not a directory.
  456. Zip::ErrorCode ZipPrivate::deflateFile(const QFileInfo& fileInfo,
  457. quint32& crc, qint64& written, const Zip::CompressionLevel& level, quint32** keys)
  458. {
  459. const QString path = fileInfo.absoluteFilePath();
  460. QFile file(path);
  461. if (!file.open(QIODevice::ReadOnly)) {
  462. qDebug() << QString("An error occurred while opening %1").arg(path);
  463. return Zip::OpenFailed;
  464. }
  465. const Zip::ErrorCode ec = (level == Zip::Store)
  466. ? storeFile(path, file, crc, written, keys)
  467. : compressFile(path, file, crc, written, level, keys);
  468. file.close();
  469. return ec;
  470. }
  471. //! \internal
  472. Zip::ErrorCode ZipPrivate::storeFile(const QString& path, QIODevice& file,
  473. quint32& crc, qint64& totalWritten, quint32** keys)
  474. {
  475. Q_UNUSED(path);
  476. qint64 read = 0;
  477. qint64 written = 0;
  478. const bool encrypt = keys != 0;
  479. totalWritten = 0;
  480. crc = crc32(0L, Z_NULL, 0);
  481. while ( (read = file.read(buffer1, ZIP_READ_BUFFER)) > 0 ) {
  482. crc = crc32(crc, uBuffer, read);
  483. if (encrypt)
  484. encryptBytes(*keys, buffer1, read);
  485. written = device->write(buffer1, read);
  486. totalWritten += written;
  487. if (written != read) {
  488. return Zip::WriteFailed;
  489. }
  490. }
  491. return Zip::Ok;
  492. }
  493. //! \internal
  494. int ZipPrivate::compressionStrategy(const QString& path, QIODevice& file) const
  495. {
  496. Q_UNUSED(file);
  497. #ifndef OSDAB_ZIP_NO_PNG_RLE
  498. return Z_DEFAULT_STRATEGY;
  499. #endif
  500. const bool isPng = path.endsWith(QLatin1String("png"), Qt::CaseInsensitive);
  501. return isPng ? Z_RLE : Z_DEFAULT_STRATEGY;
  502. }
  503. //! \internal
  504. Zip::ErrorCode ZipPrivate::compressFile(const QString& path, QIODevice& file,
  505. quint32& crc, qint64& totalWritten, const Zip::CompressionLevel& level, quint32** keys)
  506. {
  507. qint64 read = 0;
  508. qint64 written = 0;
  509. qint64 totRead = 0;
  510. qint64 toRead = file.size();
  511. const bool encrypt = keys != 0;
  512. const int strategy = compressionStrategy(path, file);
  513. totalWritten = 0;
  514. crc = crc32(0L, Z_NULL, 0);
  515. z_stream zstr;
  516. // Initialize zalloc, zfree and opaque before calling the init function
  517. zstr.zalloc = Z_NULL;
  518. zstr.zfree = Z_NULL;
  519. zstr.opaque = Z_NULL;
  520. int zret;
  521. // Use deflateInit2 with negative windowBits to get raw compression
  522. if ((zret = deflateInit2_(
  523. &zstr,
  524. (int)level, // compression level
  525. Z_DEFLATED, // method
  526. -MAX_WBITS, // windowBits
  527. 8, // memLevel
  528. strategy,
  529. ZLIB_VERSION,
  530. sizeof(z_stream)
  531. )) != Z_OK ) {
  532. qDebug() << "Could not initialize zlib for compression";
  533. return Zip::ZlibError;
  534. }
  535. qint64 compressed;
  536. int flush = Z_NO_FLUSH;
  537. do {
  538. read = file.read(buffer1, ZIP_READ_BUFFER);
  539. totRead += read;
  540. if (!read)
  541. break;
  542. if (read < 0) {
  543. deflateEnd(&zstr);
  544. qDebug() << QString("Error while reading %1").arg(path);
  545. return Zip::ReadFailed;
  546. }
  547. crc = crc32(crc, uBuffer, read);
  548. zstr.next_in = (Bytef*) buffer1;
  549. zstr.avail_in = (uInt)read;
  550. // Tell zlib if this is the last chunk we want to encode
  551. // by setting the flush parameter to Z_FINISH
  552. flush = (totRead == toRead) ? Z_FINISH : Z_NO_FLUSH;
  553. // Run deflate() on input until output buffer not full
  554. // finish compression if all of source has been read in
  555. do {
  556. zstr.next_out = (Bytef*) buffer2;
  557. zstr.avail_out = ZIP_READ_BUFFER;
  558. zret = deflate(&zstr, flush);
  559. // State not clobbered
  560. Q_ASSERT(zret != Z_STREAM_ERROR);
  561. // Write compressed data to file and empty buffer
  562. compressed = ZIP_READ_BUFFER - zstr.avail_out;
  563. if (encrypt)
  564. encryptBytes(*keys, buffer2, compressed);
  565. written = device->write(buffer2, compressed);
  566. totalWritten += written;
  567. if (written != compressed) {
  568. deflateEnd(&zstr);
  569. qDebug() << QString("Error while writing %1").arg(path);
  570. return Zip::WriteFailed;
  571. }
  572. } while (zstr.avail_out == 0);
  573. // All input will be used
  574. Q_ASSERT(zstr.avail_in == 0);
  575. } while (flush != Z_FINISH);
  576. // Stream will be complete
  577. Q_ASSERT(zret == Z_STREAM_END);
  578. deflateEnd(&zstr);
  579. return Zip::Ok;
  580. }
  581. //! \internal Writes a new entry in the zip file.
  582. Zip::ErrorCode ZipPrivate::createEntry(const QFileInfo& file, const QString& root,
  583. Zip::CompressionLevel level)
  584. {
  585. const bool dirOnly = file.isDir();
  586. // entryName contains the path as it should be written
  587. // in the zip file records
  588. const QString entryName = dirOnly
  589. ? root
  590. : root + file.fileName();
  591. // Directory entry
  592. if (dirOnly || file.size() < ZIP_COMPRESSION_THRESHOLD) {
  593. level = Zip::Store;
  594. } else {
  595. switch (level) {
  596. case Zip::AutoCPU:
  597. level = Zip::Deflate5;
  598. #ifndef OSDAB_ZIP_NO_DEBUG
  599. qDebug("Compression level for '%s': %d", entryName.toLatin1().constData(), (int)level);
  600. #endif
  601. break;
  602. case Zip::AutoMIME:
  603. level = detectCompressionByMime(file.completeSuffix().toLower());
  604. #ifndef OSDAB_ZIP_NO_DEBUG
  605. qDebug("Compression level for '%s': %d", entryName.toLatin1().constData(), (int)level);
  606. #endif
  607. break;
  608. case Zip::AutoFull:
  609. level = detectCompressionByMime(file.completeSuffix().toLower());
  610. #ifndef OSDAB_ZIP_NO_DEBUG
  611. qDebug("Compression level for '%s': %d", entryName.toLatin1().constData(), (int)level);
  612. #endif
  613. break;
  614. default: ;
  615. }
  616. }
  617. // create header and store it to write a central directory later
  618. QScopedPointer<ZipEntryP> h(new ZipEntryP);
  619. h->absolutePath = file.absoluteFilePath().toLower();
  620. h->fileSize = file.size();
  621. // Set encryption bit and set the data descriptor bit
  622. // so we can use mod time instead of crc for password check
  623. bool encrypt = !dirOnly && !password.isEmpty();
  624. if (encrypt)
  625. h->gpFlag[0] |= 9;
  626. QDateTime dt = file.lastModified();
  627. dt = OSDAB_ZIP_MANGLE(fromFileTimestamp)(dt);
  628. QDate d = dt.date();
  629. h->modDate[1] = ((d.year() - 1980) << 1) & 254;
  630. h->modDate[1] |= ((d.month() >> 3) & 1);
  631. h->modDate[0] = ((d.month() & 7) << 5) & 224;
  632. h->modDate[0] |= d.day();
  633. QTime t = dt.time();
  634. h->modTime[1] = (t.hour() << 3) & 248;
  635. h->modTime[1] |= ((t.minute() >> 3) & 7);
  636. h->modTime[0] = ((t.minute() & 7) << 5) & 224;
  637. h->modTime[0] |= t.second() / 2;
  638. h->szUncomp = dirOnly ? 0 : file.size();
  639. h->compMethod = (level == Zip::Store) ? 0 : 0x0008;
  640. // **** Write local file header ****
  641. // signature
  642. buffer1[0] = 'P'; buffer1[1] = 'K';
  643. buffer1[2] = 0x3; buffer1[3] = 0x4;
  644. // version needed to extract
  645. buffer1[ZIP_LH_OFF_VERS] = ZIP_VERSION;
  646. buffer1[ZIP_LH_OFF_VERS + 1] = 0;
  647. // general purpose flag
  648. buffer1[ZIP_LH_OFF_GPFLAG] = h->gpFlag[0];
  649. buffer1[ZIP_LH_OFF_GPFLAG + 1] = h->gpFlag[1];
  650. // compression method
  651. buffer1[ZIP_LH_OFF_CMET] = h->compMethod & 0xFF;
  652. buffer1[ZIP_LH_OFF_CMET + 1] = (h->compMethod>>8) & 0xFF;
  653. // last mod file time
  654. buffer1[ZIP_LH_OFF_MODT] = h->modTime[0];
  655. buffer1[ZIP_LH_OFF_MODT + 1] = h->modTime[1];
  656. // last mod file date
  657. buffer1[ZIP_LH_OFF_MODD] = h->modDate[0];
  658. buffer1[ZIP_LH_OFF_MODD + 1] = h->modDate[1];
  659. // skip crc (4bytes) [14,15,16,17]
  660. // skip compressed size but include evtl. encryption header (4bytes: [18,19,20,21])
  661. buffer1[ZIP_LH_OFF_CSIZE] =
  662. buffer1[ZIP_LH_OFF_CSIZE + 1] =
  663. buffer1[ZIP_LH_OFF_CSIZE + 2] =
  664. buffer1[ZIP_LH_OFF_CSIZE + 3] = 0;
  665. h->szComp = encrypt ? ZIP_LOCAL_ENC_HEADER_SIZE : 0;
  666. // uncompressed size [22,23,24,25]
  667. setULong(h->szUncomp, buffer1, ZIP_LH_OFF_USIZE);
  668. // filename length
  669. QByteArray entryNameBytes = entryName.toAscii();
  670. int sz = entryNameBytes.size();
  671. buffer1[ZIP_LH_OFF_NAMELEN] = sz & 0xFF;
  672. buffer1[ZIP_LH_OFF_NAMELEN + 1] = (sz >> 8) & 0xFF;
  673. // extra field length
  674. buffer1[ZIP_LH_OFF_XLEN] = buffer1[ZIP_LH_OFF_XLEN + 1] = 0;
  675. // Store offset to write crc and compressed size
  676. h->lhOffset = device->pos();
  677. quint32 crcOffset = h->lhOffset + ZIP_LH_OFF_CRC;
  678. if (device->write(buffer1, ZIP_LOCAL_HEADER_SIZE) != ZIP_LOCAL_HEADER_SIZE) {
  679. return Zip::WriteFailed;
  680. }
  681. // Write out filename
  682. if (device->write(entryNameBytes) != sz) {
  683. return Zip::WriteFailed;
  684. }
  685. // Encryption keys
  686. quint32 keys[3] = { 0, 0, 0 };
  687. if (encrypt) {
  688. // **** encryption header ****
  689. // XOR with PI to ensure better random numbers
  690. // with poorly implemented rand() as suggested by Info-Zip
  691. srand(time(NULL) ^ 3141592654UL);
  692. int randByte;
  693. initKeys(keys);
  694. for (int i = 0; i < 10; ++i) {
  695. randByte = (rand() >> 7) & 0xff;
  696. buffer1[i] = decryptByte(keys[2]) ^ randByte;
  697. updateKeys(keys, randByte);
  698. }
  699. // Encrypt encryption header
  700. initKeys(keys);
  701. for (int i = 0; i < 10; ++i) {
  702. randByte = decryptByte(keys[2]);
  703. updateKeys(keys, buffer1[i]);
  704. buffer1[i] ^= randByte;
  705. }
  706. // We don't know the CRC at this time, so we use the modification time
  707. // as the last two bytes
  708. randByte = decryptByte(keys[2]);
  709. updateKeys(keys, h->modTime[0]);
  710. buffer1[10] ^= randByte;
  711. randByte = decryptByte(keys[2]);
  712. updateKeys(keys, h->modTime[1]);
  713. buffer1[11] ^= randByte;
  714. // Write out encryption header
  715. if (device->write(buffer1, ZIP_LOCAL_ENC_HEADER_SIZE) != ZIP_LOCAL_ENC_HEADER_SIZE) {
  716. return Zip::WriteFailed;
  717. }
  718. }
  719. quint32 crc = 0;
  720. qint64 written = 0;
  721. if (!dirOnly) {
  722. quint32* k = keys;
  723. const Zip::ErrorCode ec = deflateFile(file, crc, written, level, encrypt ? &k : 0);
  724. if (ec != Zip::Ok)
  725. return ec;
  726. Q_ASSERT(!h.isNull());
  727. }
  728. // Store end of entry offset
  729. quint32 current = device->pos();
  730. // Update crc and compressed size in local header
  731. if (!device->seek(crcOffset)) {
  732. return Zip::SeekFailed;
  733. }
  734. h->crc = dirOnly ? 0 : crc;
  735. h->szComp += written;
  736. setULong(h->crc, buffer1, 0);
  737. setULong(h->szComp, buffer1, 4);
  738. if ( device->write(buffer1, 8) != 8) {
  739. return Zip::WriteFailed;
  740. }
  741. // Seek to end of entry
  742. if (!device->seek(current)) {
  743. return Zip::SeekFailed;
  744. }
  745. if ((h->gpFlag[0] & 8) == 8) {
  746. // Write data descriptor
  747. // Signature: PK\7\8
  748. buffer1[0] = 'P';
  749. buffer1[1] = 'K';
  750. buffer1[2] = 0x07;
  751. buffer1[3] = 0x08;
  752. // CRC
  753. setULong(h->crc, buffer1, ZIP_DD_OFF_CRC32);
  754. // Compressed size
  755. setULong(h->szComp, buffer1, ZIP_DD_OFF_CSIZE);
  756. // Uncompressed size
  757. setULong(h->szUncomp, buffer1, ZIP_DD_OFF_USIZE);
  758. if (device->write(buffer1, ZIP_DD_SIZE_WS) != ZIP_DD_SIZE_WS) {
  759. return Zip::WriteFailed;
  760. }
  761. }
  762. headers->insert(entryName, h.take());
  763. return Zip::Ok;
  764. }
  765. //! \internal
  766. int ZipPrivate::decryptByte(quint32 key2) const
  767. {
  768. quint16 temp = ((quint16)(key2) & 0xffff) | 2;
  769. return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
  770. }
  771. //! \internal Writes an quint32 (4 bytes) to a byte array at given offset.
  772. void ZipPrivate::setULong(quint32 v, char* buffer, unsigned int offset)
  773. {
  774. buffer[offset+3] = ((v >> 24) & 0xFF);
  775. buffer[offset+2] = ((v >> 16) & 0xFF);
  776. buffer[offset+1] = ((v >> 8) & 0xFF);
  777. buffer[offset] = (v & 0xFF);
  778. }
  779. //! \internal Initializes decryption keys using a password.
  780. void ZipPrivate::initKeys(quint32* keys) const
  781. {
  782. // Encryption keys initialization constants are taken from the
  783. // PKZip file format specification docs
  784. keys[0] = 305419896L;
  785. keys[1] = 591751049L;
  786. keys[2] = 878082192L;
  787. QByteArray pwdBytes = password.toAscii();
  788. int sz = pwdBytes.size();
  789. const char* ascii = pwdBytes.data();
  790. for (int i = 0; i < sz; ++i)
  791. updateKeys(keys, (int)ascii[i]);
  792. }
  793. //! Updates a one-char-only CRC; it's the Info-Zip macro re-adapted.
  794. quint32 ZipPrivate::updateChecksum(const quint32& crc, const quint32& val) const
  795. {
  796. return quint32(crcTable[quint32(crc^val) & 0xff] ^ crc_t(crc >> 8));
  797. }
  798. //! \internal Updates encryption keys.
  799. void ZipPrivate::updateKeys(quint32* keys, int c) const
  800. {
  801. keys[0] = updateChecksum(keys[0], c);
  802. keys[1] += keys[0] & 0xff;
  803. keys[1] = keys[1] * 134775813L + 1;
  804. keys[2] = updateChecksum(keys[2], ((int)keys[1]) >> 24);
  805. }
  806. //! \internal Encrypts a byte array.
  807. void ZipPrivate::encryptBytes(quint32* keys, char* buffer, qint64 read)
  808. {
  809. char t;
  810. for (qint64 i = 0; i < read; ++i) {
  811. t = buffer[i];
  812. buffer[i] ^= decryptByte(keys[2]);
  813. updateKeys(keys, t);
  814. }
  815. }
  816. namespace {
  817. struct KeywordHelper {
  818. const QString needle;
  819. inline KeywordHelper(const QString& keyword) : needle(keyword) {}
  820. };
  821. bool operator<(const KeywordHelper& helper, const char* keyword) {
  822. return helper.needle.compare(QLatin1String(keyword)) < 0;
  823. }
  824. bool operator<(const char* keyword, const KeywordHelper& helper) {
  825. return helper.needle.compare(QLatin1String(keyword)) > 0;
  826. }
  827. bool hasExtension(const QString& ext, const char* const* map, int max) {
  828. const char* const* start = &map[0];
  829. const char* const* end = &map[max - 1];
  830. const char* const* kw = qBinaryFind(start, end, KeywordHelper(ext));
  831. return kw != end;
  832. }
  833. }
  834. //! \internal Detects the best compression level for a given file extension.
  835. Zip::CompressionLevel ZipPrivate::detectCompressionByMime(const QString& ext)
  836. {
  837. // NOTE: Keep the MAX_* and the number of strings in the map up to date.
  838. // NOTE: Alphabetically sort the strings in the map -- we use a binary search!
  839. // Archives or files that will hardly compress
  840. const int MAX_EXT1 = 14;
  841. const char* const ext1[MAX_EXT1] = {
  842. "7z", "bin", "deb", "exe", "gz", "gz2", "jar", "rar", "rpm", "tar", "tgz", "z", "zip",
  843. 0 // # MAX_EXT1
  844. };
  845. // Slow or usually large files that we should not spend to much time with
  846. const int MAX_EXT2 = 24;
  847. const char* const ext2[MAX_EXT2] = {
  848. "asf",
  849. "avi",
  850. "divx",
  851. "doc",
  852. "docx",
  853. "flv",
  854. "gif",
  855. "iso",
  856. "jpg",
  857. "jpeg",
  858. "mka",
  859. "mkv",
  860. "mp3",
  861. "mp4",
  862. "mpeg",
  863. "mpg",
  864. "odt",
  865. "ogg",
  866. "ogm",
  867. "ra",
  868. "rm",
  869. "wma",
  870. "wmv",
  871. 0 // # MAX_EXT2
  872. };
  873. // Files with high compression ratio
  874. const int MAX_EXT3 = 28;
  875. const char* const ext3[MAX_EXT3] = {
  876. "asp", "bat", "c", "conf", "cpp", "cpp", "css", "csv", "cxx", "h", "hpp", "htm", "html", "hxx",
  877. "ini", "js", "php", "pl", "py", "rtf", "sh", "tsv", "txt", "vb", "vbs", "xml", "xst",
  878. 0 // # MAX_EXT3
  879. };
  880. const char* const* map = ext1;
  881. if (hasExtension(ext, map, MAX_EXT1))
  882. return Zip::Store;
  883. map = ext2;
  884. if (hasExtension(ext, map, MAX_EXT2))
  885. return Zip::Deflate2;
  886. map = ext3;
  887. if (hasExtension(ext, map, MAX_EXT3))
  888. return Zip::Deflate9;
  889. return Zip::Deflate5;
  890. }
  891. /*!
  892. Closes the current archive and writes out pending data.
  893. */
  894. Zip::ErrorCode ZipPrivate::closeArchive()
  895. {
  896. if (!device) {
  897. Q_ASSERT(!file);
  898. return Zip::Ok;
  899. }
  900. if (device != file)
  901. disconnect(device, 0, this, 0);
  902. return do_closeArchive();
  903. }
  904. //! \internal
  905. Zip::ErrorCode ZipPrivate::do_closeArchive()
  906. {
  907. // Close current archive by writing out central directory
  908. // and free up resources
  909. if (!device && !headers)
  910. return Zip::Ok;
  911. quint32 szCentralDir = 0;
  912. quint32 offCentralDir = device->pos();
  913. Zip::ErrorCode c = Zip::Ok;
  914. if (headers && device) {
  915. for (QMap<QString,ZipEntryP*>::ConstIterator itr = headers->constBegin();
  916. itr != headers->constEnd(); ++itr) {
  917. const QString fileName = itr.key();
  918. const ZipEntryP* h = itr.value();
  919. c = writeEntry(fileName, h, szCentralDir);
  920. }
  921. }
  922. if (c == Zip::Ok)
  923. c = writeCentralDir(offCentralDir, szCentralDir);
  924. if (c != Zip::Ok) {
  925. if (file) {
  926. file->close();
  927. if (!file->remove()) {
  928. qDebug() << "Failed to delete corrupt archive.";
  929. }
  930. }
  931. }
  932. return c;
  933. }
  934. //! \internal
  935. Zip::ErrorCode ZipPrivate::writeEntry(const QString& fileName, const ZipEntryP* h, quint32& szCentralDir)
  936. {
  937. unsigned int sz;
  938. Q_ASSERT(h && device && headers);
  939. // signature
  940. buffer1[0] = 'P';
  941. buffer1[1] = 'K';
  942. buffer1[2] = 0x01;
  943. buffer1[3] = 0x02;
  944. // version made by (currently only MS-DOS/FAT - no symlinks or other stuff supported)
  945. buffer1[ZIP_CD_OFF_MADEBY] = buffer1[ZIP_CD_OFF_MADEBY + 1] = 0;
  946. // version needed to extract
  947. buffer1[ZIP_CD_OFF_VERSION] = ZIP_VERSION;
  948. buffer1[ZIP_CD_OFF_VERSION + 1] = 0;
  949. // general purpose flag
  950. buffer1[ZIP_CD_OFF_GPFLAG] = h->gpFlag[0];
  951. buffer1[ZIP_CD_OFF_GPFLAG + 1] = h->gpFlag[1];
  952. // compression method
  953. buffer1[ZIP_CD_OFF_CMET] = h->compMethod & 0xFF;
  954. buffer1[ZIP_CD_OFF_CMET + 1] = (h->compMethod >> 8) & 0xFF;
  955. // last mod file time
  956. buffer1[ZIP_CD_OFF_MODT] = h->modTime[0];
  957. buffer1[ZIP_CD_OFF_MODT + 1] = h->modTime[1];
  958. // last mod file date
  959. buffer1[ZIP_CD_OFF_MODD] = h->modDate[0];
  960. buffer1[ZIP_CD_OFF_MODD + 1] = h->modDate[1];
  961. // crc (4bytes) [16,17,18,19]
  962. setULong(h->crc, buffer1, ZIP_CD_OFF_CRC);
  963. // compressed size (4bytes: [20,21,22,23])
  964. setULong(h->szComp, buffer1, ZIP_CD_OFF_CSIZE);
  965. // uncompressed size [24,25,26,27]
  966. setULong(h->szUncomp, buffer1, ZIP_CD_OFF_USIZE);
  967. // filename
  968. QByteArray fileNameBytes = fileName.toAscii();
  969. sz = fileNameBytes.size();
  970. buffer1[ZIP_CD_OFF_NAMELEN] = sz & 0xFF;
  971. buffer1[ZIP_CD_OFF_NAMELEN + 1] = (sz >> 8) & 0xFF;
  972. // extra field length
  973. buffer1[ZIP_CD_OFF_XLEN] = buffer1[ZIP_CD_OFF_XLEN + 1] = 0;
  974. // file comment length
  975. buffer1[ZIP_CD_OFF_COMMLEN] = buffer1[ZIP_CD_OFF_COMMLEN + 1] = 0;
  976. // disk number start
  977. buffer1[ZIP_CD_OFF_DISKSTART] = buffer1[ZIP_CD_OFF_DISKSTART + 1] = 0;
  978. // internal file attributes
  979. buffer1[ZIP_CD_OFF_IATTR] = buffer1[ZIP_CD_OFF_IATTR + 1] = 0;
  980. // external file attributes
  981. buffer1[ZIP_CD_OFF_EATTR] =
  982. buffer1[ZIP_CD_OFF_EATTR + 1] =
  983. buffer1[ZIP_CD_OFF_EATTR + 2] =
  984. buffer1[ZIP_CD_OFF_EATTR + 3] = 0;
  985. // relative offset of local header [42->45]
  986. setULong(h->lhOffset, buffer1, ZIP_CD_OFF_LHOFF);
  987. if (device->write(buffer1, ZIP_CD_SIZE) != ZIP_CD_SIZE) {
  988. return Zip::WriteFailed;
  989. }
  990. // Write out filename
  991. if ((unsigned int)device->write(fileNameBytes) != sz) {
  992. return Zip::WriteFailed;
  993. }
  994. szCentralDir += (ZIP_CD_SIZE + sz);
  995. return Zip::Ok;
  996. }
  997. //! \internal
  998. Zip::ErrorCode ZipPrivate::writeCentralDir(quint32 offCentralDir, quint32 szCentralDir)
  999. {
  1000. Q_ASSERT(device && headers);
  1001. unsigned int sz;
  1002. // signature
  1003. buffer1[0] = 'P';
  1004. buffer1[1] = 'K';
  1005. buffer1[2] = 0x05;
  1006. buffer1[3] = 0x06;
  1007. // number of this disk
  1008. buffer1[ZIP_EOCD_OFF_DISKNUM] = buffer1[ZIP_EOCD_OFF_DISKNUM + 1] = 0;
  1009. // number of disk with central directory
  1010. buffer1[ZIP_EOCD_OFF_CDDISKNUM] = buffer1[ZIP_EOCD_OFF_CDDISKNUM + 1] = 0;
  1011. // number of entries in this disk
  1012. sz = headers->count();
  1013. buffer1[ZIP_EOCD_OFF_ENTRIES] = sz & 0xFF;
  1014. buffer1[ZIP_EOCD_OFF_ENTRIES + 1] = (sz >> 8) & 0xFF;
  1015. // total number of entries
  1016. buffer1[ZIP_EOCD_OFF_CDENTRIES] = buffer1[ZIP_EOCD_OFF_ENTRIES];
  1017. buffer1[ZIP_EOCD_OFF_CDENTRIES + 1] = buffer1[ZIP_EOCD_OFF_ENTRIES + 1];
  1018. // size of central directory [12->15]
  1019. setULong(szCentralDir, buffer1, ZIP_EOCD_OFF_CDSIZE);
  1020. // central dir offset [16->19]
  1021. setULong(offCentralDir, buffer1, ZIP_EOCD_OFF_CDOFF);
  1022. // ZIP file comment length
  1023. QByteArray commentBytes = comment.toAscii();
  1024. quint16 commentLength = commentBytes.size();
  1025. if (commentLength == 0) {
  1026. buffer1[ZIP_EOCD_OFF_COMMLEN] = buffer1[ZIP_EOCD_OFF_COMMLEN + 1] = 0;
  1027. } else {
  1028. buffer1[ZIP_EOCD_OFF_COMMLEN] = commentLength & 0xFF;
  1029. buffer1[ZIP_EOCD_OFF_COMMLEN + 1] = (commentLength >> 8) & 0xFF;
  1030. }
  1031. if (device->write(buffer1, ZIP_EOCD_SIZE) != ZIP_EOCD_SIZE) {
  1032. return Zip::WriteFailed;
  1033. }
  1034. if (commentLength != 0) {
  1035. if ((unsigned int)device->write(commentBytes) != commentLength) {
  1036. return Zip::WriteFailed;
  1037. }
  1038. }
  1039. return Zip::Ok;
  1040. }
  1041. //! \internal
  1042. void ZipPrivate::reset()
  1043. {
  1044. comment.clear();
  1045. if (headers) {
  1046. qDeleteAll(*headers);
  1047. delete headers;
  1048. headers = 0;
  1049. }
  1050. device = 0;
  1051. if (file)
  1052. delete file;
  1053. file = 0;
  1054. }
  1055. //! \internal Returns the path of the parent directory
  1056. QString ZipPrivate::extractRoot(const QString& p, Zip::CompressionOptions o)
  1057. {
  1058. Q_UNUSED(o);
  1059. QDir d(QDir::cleanPath(p));
  1060. if (!d.exists())
  1061. return QString();
  1062. if (!d.cdUp())
  1063. return QString();
  1064. return d.absolutePath();
  1065. }
  1066. /************************************************************************
  1067. Public interface
  1068. *************************************************************************/
  1069. /*!
  1070. Creates a new Zip file compressor.
  1071. */
  1072. Zip::Zip() : d(new ZipPrivate)
  1073. {
  1074. }
  1075. /*!
  1076. Closes any open archive and releases used resources.
  1077. */
  1078. Zip::~Zip()
  1079. {
  1080. closeArchive();
  1081. delete d;
  1082. }
  1083. /*!
  1084. Returns true if there is an open archive.
  1085. */
  1086. bool Zip::isOpen() const
  1087. {
  1088. return d->device;
  1089. }
  1090. /*!
  1091. Sets the password to be used for the next files being added!
  1092. Files added before calling this method will use the previously
  1093. set password (if any).
  1094. Closing the archive won't clear the password!
  1095. */
  1096. void Zip::setPassword(const QString& pwd)
  1097. {
  1098. d->password = pwd;
  1099. }
  1100. //! Convenience method, clears the current password.
  1101. void Zip::clearPassword()
  1102. {
  1103. d->password.clear();
  1104. }
  1105. //! Returns the currently used password.
  1106. QString Zip::password() const
  1107. {
  1108. return d->password;
  1109. }
  1110. /*!
  1111. Attempts to create a new Zip archive. If \p overwrite is true and the file
  1112. already exist it will be overwritten.
  1113. Any open archive will be closed.
  1114. */
  1115. Zip::ErrorCode Zip::createArchive(const QString& filename, bool overwrite)
  1116. {
  1117. closeArchive();
  1118. Q_ASSERT(!d->device && !d->file);
  1119. if (filename.isEmpty())
  1120. return Zip::FileNotFound;
  1121. d->file = new QFile(filename);
  1122. if (d->file->exists() && !overwrite) {
  1123. delete d->file;
  1124. d->file = 0;
  1125. return Zip::FileExists;
  1126. }
  1127. if (!d->file->open(QIODevice::WriteOnly)) {
  1128. delete d->file;
  1129. d->file = 0;
  1130. return Zip::OpenFailed;
  1131. }
  1132. const Zip::ErrorCode ec = createArchive(d->file);
  1133. if (ec != Zip::Ok) {
  1134. closeArchive();
  1135. }
  1136. return ec;
  1137. }
  1138. /*!
  1139. Attempts to create a new Zip archive. If there is another open archive this will be closed.
  1140. \warning The class takes ownership of the device!
  1141. */
  1142. Zip::ErrorCode Zip::createArchive(QIODevice* device)
  1143. {
  1144. if (!device) {
  1145. qDebug() << "Invalid device.";
  1146. return Zip::OpenFailed;
  1147. }
  1148. return d->createArchive(device);
  1149. }
  1150. /*!
  1151. Returns the current archive comment.
  1152. */
  1153. QString Zip::archiveComment() const
  1154. {
  1155. return d->comment;
  1156. }
  1157. /*!
  1158. Sets the comment for this archive. Note: createArchive() should have been
  1159. called before.
  1160. */
  1161. void Zip::setArchiveComment(const QString& comment)
  1162. {
  1163. d->comment = comment;
  1164. }
  1165. /*!
  1166. Convenience method, same as calling Zip::addDirectory(const QString&,const QString&,CompressionOptions,CompressionLevel)
  1167. with the Zip::IgnorePaths flag as compression option and an empty \p root parameter.
  1168. The result is that all files found in \p path (and in subdirectories) are
  1169. added to the zip file without a directory entry.
  1170. */
  1171. Zip::ErrorCode Zip::addDirectoryContents(const QString& path, CompressionLevel level)
  1172. {
  1173. return addDirectory(path, QString(), IgnorePaths, level);
  1174. }
  1175. /*!
  1176. Convenience method, same as calling Zip::addDirectory(const QString&,const QString&,CompressionOptions,CompressionLevel)
  1177. with the Zip::IgnorePaths flag as compression option.
  1178. The result is that all files found in \p path (and in subdirectories) are
  1179. added to the zip file without a directory entry (or within a directory
  1180. structure specified by \p root).
  1181. */
  1182. Zip::ErrorCode Zip::addDirectoryContents(const QString& path, const QString& root, CompressionLevel level)
  1183. {
  1184. return addDirectory(path, root, IgnorePaths, level);
  1185. }
  1186. /*!
  1187. Convenience method, same as calling
  1188. Zip::addDirectory(const QString&,const QString&,CompressionLevel)
  1189. with an empty \p root parameter and Zip::RelativePaths flag as compression option.
  1190. */
  1191. Zip::ErrorCode Zip::addDirectory(const QString& path, CompressionLevel level)
  1192. {
  1193. return addDirectory(path, QString(), Zip::RelativePaths, level);
  1194. }
  1195. /*!
  1196. Convenience method, same as calling Zip::addDirectory(const QString&,const QString&,CompressionOptions,CompressionLevel)
  1197. with the Zip::RelativePaths flag as compression option.
  1198. */
  1199. Zip::ErrorCode Zip::addDirectory(const QString& path, const QString& root, CompressionLevel level)
  1200. {
  1201. return addDirectory(path, root, Zip::RelativePaths, level);
  1202. }
  1203. /*!
  1204. Recursively adds files contained in \p dir to the archive, using \p root as name for the root folder.
  1205. Stops adding files if some error occurs.
  1206. The ExtractionOptions are checked in the order they are defined in the zip.h heaser file.
  1207. This means that the last one overwrites the previous one (if some conflict occurs), i.e.
  1208. Zip::IgnorePaths | Zip::AbsolutePaths would be interpreted as Zip::IgnorePaths.
  1209. The \p root parameter is ignored with the Zip::IgnorePaths parameter and used as path prefix (a trailing /
  1210. is always added as directory separator!) otherwise (even with Zip::AbsolutePaths set!).
  1211. If \p addedFiles is not null it is set to the number of successfully added
  1212. files.
  1213. */
  1214. Zip::ErrorCode Zip::addDirectory(const QString& path, const QString& root,
  1215. CompressionOptions options, CompressionLevel level, int* addedFiles)
  1216. {
  1217. const int hierarchyLev = 0;
  1218. return d->addDirectory(path, root, options, level, hierarchyLev, addedFiles);
  1219. }
  1220. /*!
  1221. Convenience method, same as calling Zip::addFile(const QString&,const QString&,CompressionOptions,CompressionLevel)
  1222. with an empty \p root parameter and Zip::RelativePaths as compression option.
  1223. */
  1224. Zip::ErrorCode Zip::addFile(const QString& path, CompressionLevel level)
  1225. {
  1226. return addFile(path, QString(), Zip::RelativePaths, level);
  1227. }
  1228. /*!
  1229. Convenience method, same as calling Zip::addFile(const QString&,const QString&,CompressionOptions,CompressionLevel)
  1230. with the Zip::RelativePaths flag as compression option.
  1231. */
  1232. Zip::ErrorCode Zip::addFile(const QString& path, const QString& root,
  1233. CompressionLevel level)
  1234. {
  1235. return addFile(path, root, Zip::RelativePaths, level);
  1236. }
  1237. /*!
  1238. Adds the file at \p path to the archive, using \p root as name for the root folder.
  1239. If \p path points to a directory the behaviour is basically the same as
  1240. addDirectory().
  1241. The ExtractionOptions are checked in the order they are defined in the zip.h heaser file.
  1242. This means that the last one overwrites the previous one (if some conflict occurs), i.e.
  1243. Zip::IgnorePaths | Zip::AbsolutePaths would be interpreted as Zip::IgnorePaths.
  1244. The \p root parameter is ignored with the Zip::IgnorePaths parameter and used as path prefix (a trailing /
  1245. is always added as directory separator!) otherwise (even with Zip::AbsolutePaths set!).
  1246. */
  1247. Zip::ErrorCode Zip::addFile(const QString& path, const QString& root,
  1248. CompressionOptions options, CompressionLevel level)
  1249. {
  1250. if (path.isEmpty())
  1251. return Zip::Ok;
  1252. return addFiles(QStringList() << path, root, options, level);
  1253. }
  1254. /*!
  1255. Convenience method, same as calling Zip::addFiles(const QStringList&,const QString&,CompressionOptions,CompressionLevel)
  1256. with an empty \p root parameter and Zip::RelativePaths as compression option.
  1257. */
  1258. Zip::ErrorCode Zip::addFiles(const QStringList& paths, CompressionLevel level)
  1259. {
  1260. return addFiles(paths, QString(), Zip::RelativePaths, level);
  1261. }
  1262. /*!
  1263. Convenience method, same as calling Zip::addFiles(const QStringList&,const QString&,CompressionOptions,CompressionLevel)
  1264. with the Zip::RelativePaths flag as compression option.
  1265. */
  1266. Zip::ErrorCode Zip::addFiles(const QStringList& paths, const QString& root,
  1267. CompressionLevel level)
  1268. {
  1269. return addFiles(paths, root, Zip::RelativePaths, level);
  1270. }
  1271. /*!
  1272. Adds the files or directories in \p paths to the archive, using \p root as
  1273. name for the root folder.
  1274. This is similar to calling addFile or addDirectory for all the entries in
  1275. \p paths, except it is slightly faster.
  1276. The ExtractionOptions are checked in the order they are defined in the zip.h heaser file.
  1277. This means that the last one overwrites the previous one (if some conflict occurs), i.e.
  1278. Zip::IgnorePaths | Zip::AbsolutePaths would be interpreted as Zip::IgnorePaths.
  1279. The \p root parameter is ignored with the Zip::IgnorePaths parameter and used as path prefix (a trailing /
  1280. is always added as directory separator!) otherwise (even with Zip::AbsolutePaths set!).
  1281. If \p addedFiles is not null it is set to the number of successfully added
  1282. files.
  1283. */
  1284. Zip::ErrorCode Zip::addFiles(const QStringList& paths, const QString& root,
  1285. CompressionOptions options, CompressionLevel level, int* addedFiles)
  1286. {
  1287. return d->addFiles(paths, root, options, level, addedFiles);
  1288. }
  1289. /*!
  1290. Closes the archive and writes any pending data.
  1291. */
  1292. Zip::ErrorCode Zip::closeArchive()
  1293. {
  1294. Zip::ErrorCode ec = d->closeArchive();
  1295. d->reset();
  1296. return ec;
  1297. }
  1298. /*!
  1299. Returns a locale translated error string for a given error code.
  1300. */
  1301. QString Zip::formatError(Zip::ErrorCode c) const
  1302. {
  1303. switch (c)
  1304. {
  1305. case Ok: return QCoreApplication::translate("Zip", "ZIP operation completed successfully."); break;
  1306. case ZlibInit: return QCoreApplication::translate("Zip", "Failed to initialize or load zlib library."); break;
  1307. case ZlibError: return QCoreApplication::translate("Zip", "zlib library error."); break;
  1308. case OpenFailed: return QCoreApplication::translate("Zip", "Unable to create or open file."); break;
  1309. case NoOpenArchive: return QCoreApplication::translate("Zip", "No archive has been created yet."); break;
  1310. case FileNotFound: return QCoreApplication::translate("Zip", "File or directory does not exist."); break;
  1311. case ReadFailed: return QCoreApplication::translate("Zip", "File read error."); break;
  1312. case WriteFailed: return QCoreApplication::translate("Zip", "File write error."); break;
  1313. case SeekFailed: return QCoreApplication::translate("Zip", "File seek error."); break;
  1314. default: ;
  1315. }
  1316. return QCoreApplication::translate("Zip", "Unknown error.");
  1317. }
  1318. OSDAB_END_NAMESPACE