SSZipArchive.m 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434
  1. //
  2. // SSZipArchive.m
  3. // SSZipArchive
  4. //
  5. // Created by Sam Soffes on 7/21/10.
  6. //
  7. #import "SSZipArchive.h"
  8. #include "minizip/mz_compat.h"
  9. #include "minizip/mz_zip.h"
  10. #include "minizip/mz_os.h"
  11. #include <zlib.h>
  12. #include <sys/stat.h>
  13. NSString *const SSZipArchiveErrorDomain = @"SSZipArchiveErrorDomain";
  14. #define CHUNK 16384
  15. int _zipOpenEntry(zipFile entry, NSString *name, const zip_fileinfo *zipfi, int level, NSString *password, BOOL aes);
  16. BOOL _fileIsSymbolicLink(const unz_file_info *fileInfo);
  17. #ifndef API_AVAILABLE
  18. // Xcode 7- compatibility
  19. #define API_AVAILABLE(...)
  20. #endif
  21. @interface NSData(SSZipArchive)
  22. - (NSString *)_base64RFC4648 API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
  23. - (NSString *)_hexString;
  24. @end
  25. @interface NSString (SSZipArchive)
  26. - (NSString *)_sanitizedPath;
  27. @end
  28. @interface SSZipArchive ()
  29. - (instancetype)init NS_DESIGNATED_INITIALIZER;
  30. @end
  31. @implementation SSZipArchive
  32. {
  33. /// path for zip file
  34. NSString *_path;
  35. zipFile _zip;
  36. }
  37. #pragma mark - Password check
  38. + (BOOL)isFilePasswordProtectedAtPath:(NSString *)path {
  39. // Begin opening
  40. zipFile zip = unzOpen(path.fileSystemRepresentation);
  41. if (zip == NULL) {
  42. return NO;
  43. }
  44. BOOL passwordProtected = NO;
  45. int ret = unzGoToFirstFile(zip);
  46. if (ret == UNZ_OK) {
  47. do {
  48. ret = unzOpenCurrentFile(zip);
  49. if (ret != UNZ_OK) {
  50. // attempting with an arbitrary password to workaround `unzOpenCurrentFile` limitation on AES encrypted files
  51. ret = unzOpenCurrentFilePassword(zip, "");
  52. unzCloseCurrentFile(zip);
  53. if (ret == UNZ_OK || ret == MZ_PASSWORD_ERROR) {
  54. passwordProtected = YES;
  55. }
  56. break;
  57. }
  58. unz_file_info fileInfo = {};
  59. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  60. unzCloseCurrentFile(zip);
  61. if (ret != UNZ_OK) {
  62. break;
  63. } else if ((fileInfo.flag & MZ_ZIP_FLAG_ENCRYPTED) == 1) {
  64. passwordProtected = YES;
  65. break;
  66. }
  67. ret = unzGoToNextFile(zip);
  68. } while (ret == UNZ_OK);
  69. }
  70. unzClose(zip);
  71. return passwordProtected;
  72. }
  73. + (BOOL)isPasswordValidForArchiveAtPath:(NSString *)path password:(NSString *)pw error:(NSError **)error {
  74. if (error) {
  75. *error = nil;
  76. }
  77. zipFile zip = unzOpen(path.fileSystemRepresentation);
  78. if (zip == NULL) {
  79. if (error) {
  80. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  81. code:SSZipArchiveErrorCodeFailedOpenZipFile
  82. userInfo:@{NSLocalizedDescriptionKey: @"failed to open zip file"}];
  83. }
  84. return NO;
  85. }
  86. // Initialize passwordValid to YES (No password required)
  87. BOOL passwordValid = YES;
  88. int ret = unzGoToFirstFile(zip);
  89. if (ret == UNZ_OK) {
  90. do {
  91. if (pw.length == 0) {
  92. ret = unzOpenCurrentFile(zip);
  93. } else {
  94. ret = unzOpenCurrentFilePassword(zip, [pw cStringUsingEncoding:NSUTF8StringEncoding]);
  95. }
  96. if (ret != UNZ_OK) {
  97. if (ret != MZ_PASSWORD_ERROR) {
  98. if (error) {
  99. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  100. code:SSZipArchiveErrorCodeFailedOpenFileInZip
  101. userInfo:@{NSLocalizedDescriptionKey: @"failed to open file in zip archive"}];
  102. }
  103. }
  104. passwordValid = NO;
  105. break;
  106. }
  107. unz_file_info fileInfo = {};
  108. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  109. if (ret != UNZ_OK) {
  110. if (error) {
  111. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  112. code:SSZipArchiveErrorCodeFileInfoNotLoadable
  113. userInfo:@{NSLocalizedDescriptionKey: @"failed to retrieve info for file"}];
  114. }
  115. passwordValid = NO;
  116. break;
  117. } else if ((fileInfo.flag & 1) == 1) {
  118. unsigned char buffer[10] = {0};
  119. int readBytes = unzReadCurrentFile(zip, buffer, (unsigned)MIN(10UL,fileInfo.uncompressed_size));
  120. if (readBytes < 0) {
  121. // Let's assume error Z_DATA_ERROR is caused by an invalid password
  122. // Let's assume other errors are caused by Content Not Readable
  123. if (readBytes != Z_DATA_ERROR) {
  124. if (error) {
  125. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  126. code:SSZipArchiveErrorCodeFileContentNotReadable
  127. userInfo:@{NSLocalizedDescriptionKey: @"failed to read contents of file entry"}];
  128. }
  129. }
  130. passwordValid = NO;
  131. break;
  132. }
  133. passwordValid = YES;
  134. break;
  135. }
  136. unzCloseCurrentFile(zip);
  137. ret = unzGoToNextFile(zip);
  138. } while (ret == UNZ_OK);
  139. }
  140. unzClose(zip);
  141. return passwordValid;
  142. }
  143. + (NSNumber *)payloadSizeForArchiveAtPath:(NSString *)path error:(NSError **)error {
  144. if (error) {
  145. *error = nil;
  146. }
  147. zipFile zip = unzOpen(path.fileSystemRepresentation);
  148. if (zip == NULL) {
  149. if (error) {
  150. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  151. code:SSZipArchiveErrorCodeFailedOpenZipFile
  152. userInfo:@{NSLocalizedDescriptionKey: @"failed to open zip file"}];
  153. }
  154. return @0;
  155. }
  156. unsigned long long totalSize = 0;
  157. int ret = unzGoToFirstFile(zip);
  158. if (ret == UNZ_OK) {
  159. do {
  160. ret = unzOpenCurrentFile(zip);
  161. if (ret != UNZ_OK) {
  162. if (error) {
  163. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  164. code:SSZipArchiveErrorCodeFailedOpenFileInZip
  165. userInfo:@{NSLocalizedDescriptionKey: @"failed to open file in zip archive"}];
  166. }
  167. break;
  168. }
  169. unz_file_info fileInfo = {};
  170. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  171. if (ret != UNZ_OK) {
  172. if (error) {
  173. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  174. code:SSZipArchiveErrorCodeFileInfoNotLoadable
  175. userInfo:@{NSLocalizedDescriptionKey: @"failed to retrieve info for file"}];
  176. }
  177. break;
  178. }
  179. totalSize += fileInfo.uncompressed_size;
  180. unzCloseCurrentFile(zip);
  181. ret = unzGoToNextFile(zip);
  182. } while (ret == UNZ_OK);
  183. }
  184. unzClose(zip);
  185. return [NSNumber numberWithUnsignedLongLong:totalSize];
  186. }
  187. #pragma mark - Unzipping
  188. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination
  189. {
  190. return [self unzipFileAtPath:path toDestination:destination delegate:nil];
  191. }
  192. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(nullable NSString *)password error:(NSError **)error
  193. {
  194. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:overwrite password:password error:error delegate:nil progressHandler:nil completionHandler:nil];
  195. }
  196. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination delegate:(nullable id<SSZipArchiveDelegate>)delegate
  197. {
  198. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:YES password:nil error:nil delegate:delegate progressHandler:nil completionHandler:nil];
  199. }
  200. + (BOOL)unzipFileAtPath:(NSString *)path
  201. toDestination:(NSString *)destination
  202. overwrite:(BOOL)overwrite
  203. password:(nullable NSString *)password
  204. error:(NSError **)error
  205. delegate:(nullable id<SSZipArchiveDelegate>)delegate
  206. {
  207. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:overwrite password:password error:error delegate:delegate progressHandler:nil completionHandler:nil];
  208. }
  209. + (BOOL)unzipFileAtPath:(NSString *)path
  210. toDestination:(NSString *)destination
  211. overwrite:(BOOL)overwrite
  212. password:(NSString *)password
  213. progressHandler:(void (^)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  214. completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler
  215. {
  216. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:overwrite password:password error:nil delegate:nil progressHandler:progressHandler completionHandler:completionHandler];
  217. }
  218. + (BOOL)unzipFileAtPath:(NSString *)path
  219. toDestination:(NSString *)destination
  220. progressHandler:(void (^_Nullable)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  221. completionHandler:(void (^_Nullable)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler
  222. {
  223. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:YES password:nil error:nil delegate:nil progressHandler:progressHandler completionHandler:completionHandler];
  224. }
  225. + (BOOL)unzipFileAtPath:(NSString *)path
  226. toDestination:(NSString *)destination
  227. preserveAttributes:(BOOL)preserveAttributes
  228. overwrite:(BOOL)overwrite
  229. password:(nullable NSString *)password
  230. error:(NSError * *)error
  231. delegate:(nullable id<SSZipArchiveDelegate>)delegate
  232. {
  233. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:preserveAttributes overwrite:overwrite password:password error:error delegate:delegate progressHandler:nil completionHandler:nil];
  234. }
  235. + (BOOL)unzipFileAtPath:(NSString *)path
  236. toDestination:(NSString *)destination
  237. preserveAttributes:(BOOL)preserveAttributes
  238. overwrite:(BOOL)overwrite
  239. password:(nullable NSString *)password
  240. error:(NSError **)error
  241. delegate:(nullable id<SSZipArchiveDelegate>)delegate
  242. progressHandler:(void (^_Nullable)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  243. completionHandler:(void (^_Nullable)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler
  244. {
  245. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:preserveAttributes overwrite:overwrite nestedZipLevel:0 password:password error:error delegate:delegate progressHandler:progressHandler completionHandler:completionHandler];
  246. }
  247. + (BOOL)unzipFileAtPath:(NSString *)path
  248. toDestination:(NSString *)destination
  249. preserveAttributes:(BOOL)preserveAttributes
  250. overwrite:(BOOL)overwrite
  251. nestedZipLevel:(NSInteger)nestedZipLevel
  252. password:(nullable NSString *)password
  253. error:(NSError **)error
  254. delegate:(nullable id<SSZipArchiveDelegate>)delegate
  255. progressHandler:(void (^_Nullable)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  256. completionHandler:(void (^_Nullable)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler
  257. {
  258. // Guard against empty strings
  259. if (path.length == 0 || destination.length == 0)
  260. {
  261. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"received invalid argument(s)"};
  262. NSError *err = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeInvalidArguments userInfo:userInfo];
  263. if (error)
  264. {
  265. *error = err;
  266. }
  267. if (completionHandler)
  268. {
  269. completionHandler(nil, NO, err);
  270. }
  271. return NO;
  272. }
  273. // Begin opening
  274. zipFile zip = unzOpen(path.fileSystemRepresentation);
  275. if (zip == NULL)
  276. {
  277. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"failed to open zip file"};
  278. NSError *err = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeFailedOpenZipFile userInfo:userInfo];
  279. if (error)
  280. {
  281. *error = err;
  282. }
  283. if (completionHandler)
  284. {
  285. completionHandler(nil, NO, err);
  286. }
  287. return NO;
  288. }
  289. NSDictionary * fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
  290. unsigned long long fileSize = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue];
  291. unsigned long long currentPosition = 0;
  292. unz_global_info globalInfo = {};
  293. unzGetGlobalInfo(zip, &globalInfo);
  294. // Begin unzipping
  295. int ret = 0;
  296. ret = unzGoToFirstFile(zip);
  297. if (ret != UNZ_OK && ret != MZ_END_OF_LIST)
  298. {
  299. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"failed to open first file in zip file"};
  300. NSError *err = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeFailedOpenFileInZip userInfo:userInfo];
  301. if (error)
  302. {
  303. *error = err;
  304. }
  305. if (completionHandler)
  306. {
  307. completionHandler(nil, NO, err);
  308. }
  309. unzClose(zip);
  310. return NO;
  311. }
  312. BOOL success = YES;
  313. BOOL canceled = NO;
  314. int crc_ret = 0;
  315. unsigned char buffer[4096] = {0};
  316. NSFileManager *fileManager = [NSFileManager defaultManager];
  317. NSMutableArray<NSDictionary *> *directoriesModificationDates = [[NSMutableArray alloc] init];
  318. // Message delegate
  319. if ([delegate respondsToSelector:@selector(zipArchiveWillUnzipArchiveAtPath:zipInfo:)]) {
  320. [delegate zipArchiveWillUnzipArchiveAtPath:path zipInfo:globalInfo];
  321. }
  322. if ([delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  323. [delegate zipArchiveProgressEvent:currentPosition total:fileSize];
  324. }
  325. NSInteger currentFileNumber = -1;
  326. NSError *unzippingError;
  327. do {
  328. currentFileNumber++;
  329. if (ret == MZ_END_OF_LIST) {
  330. break;
  331. }
  332. @autoreleasepool {
  333. if (password.length == 0) {
  334. ret = unzOpenCurrentFile(zip);
  335. } else {
  336. ret = unzOpenCurrentFilePassword(zip, [password cStringUsingEncoding:NSUTF8StringEncoding]);
  337. }
  338. if (ret != UNZ_OK) {
  339. unzippingError = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:SSZipArchiveErrorCodeFailedOpenFileInZip userInfo:@{NSLocalizedDescriptionKey: @"failed to open file in zip file"}];
  340. success = NO;
  341. break;
  342. }
  343. // Reading data and write to file
  344. unz_file_info fileInfo;
  345. memset(&fileInfo, 0, sizeof(unz_file_info));
  346. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  347. if (ret != UNZ_OK) {
  348. unzippingError = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:SSZipArchiveErrorCodeFileInfoNotLoadable userInfo:@{NSLocalizedDescriptionKey: @"failed to retrieve info for file"}];
  349. success = NO;
  350. unzCloseCurrentFile(zip);
  351. break;
  352. }
  353. currentPosition += fileInfo.compressed_size;
  354. // Message delegate
  355. if ([delegate respondsToSelector:@selector(zipArchiveShouldUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  356. if (![delegate zipArchiveShouldUnzipFileAtIndex:currentFileNumber
  357. totalFiles:(NSInteger)globalInfo.number_entry
  358. archivePath:path
  359. fileInfo:fileInfo]) {
  360. success = NO;
  361. canceled = YES;
  362. break;
  363. }
  364. }
  365. if ([delegate respondsToSelector:@selector(zipArchiveWillUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  366. [delegate zipArchiveWillUnzipFileAtIndex:currentFileNumber totalFiles:(NSInteger)globalInfo.number_entry
  367. archivePath:path fileInfo:fileInfo];
  368. }
  369. if ([delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  370. [delegate zipArchiveProgressEvent:(NSInteger)currentPosition total:(NSInteger)fileSize];
  371. }
  372. char *filename = (char *)malloc(fileInfo.size_filename + 1);
  373. if (filename == NULL)
  374. {
  375. success = NO;
  376. break;
  377. }
  378. unzGetCurrentFileInfo(zip, &fileInfo, filename, fileInfo.size_filename + 1, NULL, 0, NULL, 0);
  379. filename[fileInfo.size_filename] = '\0';
  380. BOOL fileIsSymbolicLink = _fileIsSymbolicLink(&fileInfo);
  381. NSString * strPath = [SSZipArchive _filenameStringWithCString:filename
  382. version_made_by:fileInfo.version
  383. general_purpose_flag:fileInfo.flag
  384. size:fileInfo.size_filename];
  385. if ([strPath hasPrefix:@"__MACOSX/"]) {
  386. // ignoring resource forks: https://superuser.com/questions/104500/what-is-macosx-folder
  387. unzCloseCurrentFile(zip);
  388. ret = unzGoToNextFile(zip);
  389. free(filename);
  390. continue;
  391. }
  392. // Check if it contains directory
  393. BOOL isDirectory = NO;
  394. if (filename[fileInfo.size_filename-1] == '/' || filename[fileInfo.size_filename-1] == '\\') {
  395. isDirectory = YES;
  396. }
  397. free(filename);
  398. // Sanitize paths in the file name.
  399. strPath = [strPath _sanitizedPath];
  400. if (!strPath.length) {
  401. // if filename data is unsalvageable, we default to currentFileNumber
  402. strPath = @(currentFileNumber).stringValue;
  403. }
  404. NSString *fullPath = [destination stringByAppendingPathComponent:strPath];
  405. NSError *err = nil;
  406. NSDictionary *directoryAttr;
  407. if (preserveAttributes) {
  408. NSDate *modDate = [[self class] _dateWithMSDOSFormat:(UInt32)fileInfo.mz_dos_date];
  409. directoryAttr = @{NSFileCreationDate: modDate, NSFileModificationDate: modDate};
  410. [directoriesModificationDates addObject: @{@"path": fullPath, @"modDate": modDate}];
  411. }
  412. if (isDirectory) {
  413. [fileManager createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:directoryAttr error:&err];
  414. } else {
  415. [fileManager createDirectoryAtPath:fullPath.stringByDeletingLastPathComponent withIntermediateDirectories:YES attributes:directoryAttr error:&err];
  416. }
  417. if (err != nil) {
  418. if ([err.domain isEqualToString:NSCocoaErrorDomain] &&
  419. err.code == 640) {
  420. unzippingError = err;
  421. unzCloseCurrentFile(zip);
  422. success = NO;
  423. break;
  424. }
  425. NSLog(@"[SSZipArchive] Error: %@", err.localizedDescription);
  426. }
  427. if ([fileManager fileExistsAtPath:fullPath] && !isDirectory && !overwrite) {
  428. //FIXME: couldBe CRC Check?
  429. unzCloseCurrentFile(zip);
  430. ret = unzGoToNextFile(zip);
  431. continue;
  432. }
  433. if (isDirectory && !fileIsSymbolicLink) {
  434. // nothing to read/write for a directory
  435. } else if (!fileIsSymbolicLink) {
  436. // ensure we are not creating stale file entries
  437. int readBytes = unzReadCurrentFile(zip, buffer, 4096);
  438. if (readBytes >= 0) {
  439. FILE *fp = fopen(fullPath.fileSystemRepresentation, "wb");
  440. while (fp) {
  441. if (readBytes > 0) {
  442. if (0 == fwrite(buffer, readBytes, 1, fp)) {
  443. if (ferror(fp)) {
  444. NSString *message = [NSString stringWithFormat:@"Failed to write file (check your free space)"];
  445. NSLog(@"[SSZipArchive] %@", message);
  446. success = NO;
  447. unzippingError = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:SSZipArchiveErrorCodeFailedToWriteFile userInfo:@{NSLocalizedDescriptionKey: message}];
  448. break;
  449. }
  450. }
  451. } else {
  452. break;
  453. }
  454. readBytes = unzReadCurrentFile(zip, buffer, 4096);
  455. if (readBytes < 0) {
  456. // Let's assume error Z_DATA_ERROR is caused by an invalid password
  457. // Let's assume other errors are caused by Content Not Readable
  458. success = NO;
  459. }
  460. }
  461. if (fp) {
  462. fclose(fp);
  463. if (nestedZipLevel
  464. && [fullPath.pathExtension.lowercaseString isEqualToString:@"zip"]
  465. && [self unzipFileAtPath:fullPath
  466. toDestination:fullPath.stringByDeletingLastPathComponent
  467. preserveAttributes:preserveAttributes
  468. overwrite:overwrite
  469. nestedZipLevel:nestedZipLevel - 1
  470. password:password
  471. error:nil
  472. delegate:nil
  473. progressHandler:nil
  474. completionHandler:nil]) {
  475. [directoriesModificationDates removeLastObject];
  476. [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
  477. } else if (preserveAttributes) {
  478. // Set the original datetime property
  479. if (fileInfo.mz_dos_date != 0) {
  480. NSDate *orgDate = [[self class] _dateWithMSDOSFormat:(UInt32)fileInfo.mz_dos_date];
  481. NSDictionary *attr = @{NSFileModificationDate: orgDate};
  482. if (attr) {
  483. if (![fileManager setAttributes:attr ofItemAtPath:fullPath error:nil]) {
  484. // Can't set attributes
  485. NSLog(@"[SSZipArchive] Failed to set attributes - whilst setting modification date");
  486. }
  487. }
  488. }
  489. // Set the original permissions on the file (+read/write to solve #293)
  490. uLong permissions = fileInfo.external_fa >> 16 | 0b110000000;
  491. if (permissions != 0) {
  492. // Store it into a NSNumber
  493. NSNumber *permissionsValue = @(permissions);
  494. // Retrieve any existing attributes
  495. NSMutableDictionary *attrs = [[NSMutableDictionary alloc] initWithDictionary:[fileManager attributesOfItemAtPath:fullPath error:nil]];
  496. // Set the value in the attributes dict
  497. [attrs setObject:permissionsValue forKey:NSFilePosixPermissions];
  498. // Update attributes
  499. if (![fileManager setAttributes:attrs ofItemAtPath:fullPath error:nil]) {
  500. // Unable to set the permissions attribute
  501. NSLog(@"[SSZipArchive] Failed to set attributes - whilst setting permissions");
  502. }
  503. }
  504. }
  505. }
  506. else
  507. {
  508. // if we couldn't open file descriptor we can validate global errno to see the reason
  509. int errnoSave = errno;
  510. BOOL isSeriousError = NO;
  511. switch (errnoSave) {
  512. case EISDIR:
  513. // Is a directory
  514. // assumed case
  515. break;
  516. case ENOSPC:
  517. case EMFILE:
  518. // No space left on device
  519. // or
  520. // Too many open files
  521. isSeriousError = YES;
  522. break;
  523. default:
  524. // ignore case
  525. // Just log the error
  526. {
  527. NSError *errorObject = [NSError errorWithDomain:NSPOSIXErrorDomain
  528. code:errnoSave
  529. userInfo:nil];
  530. NSLog(@"[SSZipArchive] Failed to open file on unzipping.(%@)", errorObject);
  531. }
  532. break;
  533. }
  534. if (isSeriousError) {
  535. // serious case
  536. unzippingError = [NSError errorWithDomain:NSPOSIXErrorDomain
  537. code:errnoSave
  538. userInfo:nil];
  539. unzCloseCurrentFile(zip);
  540. // Log the error
  541. NSLog(@"[SSZipArchive] Failed to open file on unzipping.(%@)", unzippingError);
  542. // Break unzipping
  543. success = NO;
  544. break;
  545. }
  546. }
  547. } else {
  548. // Let's assume error Z_DATA_ERROR is caused by an invalid password
  549. // Let's assume other errors are caused by Content Not Readable
  550. success = NO;
  551. break;
  552. }
  553. }
  554. else
  555. {
  556. // Assemble the path for the symbolic link
  557. NSMutableString *destinationPath = [NSMutableString string];
  558. int bytesRead = 0;
  559. while ((bytesRead = unzReadCurrentFile(zip, buffer, 4096)) > 0)
  560. {
  561. buffer[bytesRead] = 0;
  562. [destinationPath appendString:@((const char *)buffer)];
  563. }
  564. if (bytesRead < 0) {
  565. // Let's assume error Z_DATA_ERROR is caused by an invalid password
  566. // Let's assume other errors are caused by Content Not Readable
  567. success = NO;
  568. break;
  569. }
  570. // Check if the symlink exists and delete it if we're overwriting
  571. if (overwrite)
  572. {
  573. if ([fileManager fileExistsAtPath:fullPath])
  574. {
  575. NSError *localError = nil;
  576. BOOL removeSuccess = [fileManager removeItemAtPath:fullPath error:&localError];
  577. if (!removeSuccess)
  578. {
  579. NSString *message = [NSString stringWithFormat:@"Failed to delete existing symbolic link at \"%@\"", localError.localizedDescription];
  580. NSLog(@"[SSZipArchive] %@", message);
  581. success = NO;
  582. unzippingError = [NSError errorWithDomain:SSZipArchiveErrorDomain code:localError.code userInfo:@{NSLocalizedDescriptionKey: message}];
  583. }
  584. }
  585. }
  586. // Create the symbolic link (making sure it stays relative if it was relative before)
  587. int symlinkError = symlink([destinationPath cStringUsingEncoding:NSUTF8StringEncoding],
  588. [fullPath cStringUsingEncoding:NSUTF8StringEncoding]);
  589. if (symlinkError != 0)
  590. {
  591. // Bubble the error up to the completion handler
  592. NSString *message = [NSString stringWithFormat:@"Failed to create symbolic link at \"%@\" to \"%@\" - symlink() error code: %d", fullPath, destinationPath, errno];
  593. NSLog(@"[SSZipArchive] %@", message);
  594. success = NO;
  595. unzippingError = [NSError errorWithDomain:NSPOSIXErrorDomain code:symlinkError userInfo:@{NSLocalizedDescriptionKey: message}];
  596. }
  597. }
  598. crc_ret = unzCloseCurrentFile(zip);
  599. if (crc_ret == MZ_CRC_ERROR) {
  600. // CRC ERROR
  601. success = NO;
  602. break;
  603. }
  604. ret = unzGoToNextFile(zip);
  605. // Message delegate
  606. if ([delegate respondsToSelector:@selector(zipArchiveDidUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  607. [delegate zipArchiveDidUnzipFileAtIndex:currentFileNumber totalFiles:(NSInteger)globalInfo.number_entry
  608. archivePath:path fileInfo:fileInfo];
  609. } else if ([delegate respondsToSelector: @selector(zipArchiveDidUnzipFileAtIndex:totalFiles:archivePath:unzippedFilePath:)]) {
  610. [delegate zipArchiveDidUnzipFileAtIndex: currentFileNumber totalFiles: (NSInteger)globalInfo.number_entry
  611. archivePath:path unzippedFilePath: fullPath];
  612. }
  613. if (progressHandler)
  614. {
  615. progressHandler(strPath, fileInfo, currentFileNumber, globalInfo.number_entry);
  616. }
  617. }
  618. } while (ret == UNZ_OK && success);
  619. // Close
  620. unzClose(zip);
  621. // The process of decompressing the .zip archive causes the modification times on the folders
  622. // to be set to the present time. So, when we are done, they need to be explicitly set.
  623. // set the modification date on all of the directories.
  624. if (success && preserveAttributes) {
  625. NSError * err = nil;
  626. for (NSDictionary * d in directoriesModificationDates) {
  627. if (![[NSFileManager defaultManager] setAttributes:@{NSFileModificationDate: [d objectForKey:@"modDate"]} ofItemAtPath:[d objectForKey:@"path"] error:&err]) {
  628. NSLog(@"[SSZipArchive] Set attributes failed for directory: %@.", [d objectForKey:@"path"]);
  629. }
  630. if (err) {
  631. NSLog(@"[SSZipArchive] Error setting directory file modification date attribute: %@", err.localizedDescription);
  632. }
  633. }
  634. }
  635. // Message delegate
  636. if (success && [delegate respondsToSelector:@selector(zipArchiveDidUnzipArchiveAtPath:zipInfo:unzippedPath:)]) {
  637. [delegate zipArchiveDidUnzipArchiveAtPath:path zipInfo:globalInfo unzippedPath:destination];
  638. }
  639. // final progress event = 100%
  640. if (!canceled && [delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  641. [delegate zipArchiveProgressEvent:fileSize total:fileSize];
  642. }
  643. NSError *retErr = nil;
  644. if (crc_ret == MZ_CRC_ERROR)
  645. {
  646. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"crc check failed for file"};
  647. retErr = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeFileInfoNotLoadable userInfo:userInfo];
  648. }
  649. if (error) {
  650. if (unzippingError) {
  651. *error = unzippingError;
  652. }
  653. else {
  654. *error = retErr;
  655. }
  656. }
  657. if (completionHandler)
  658. {
  659. if (unzippingError) {
  660. completionHandler(path, success, unzippingError);
  661. }
  662. else
  663. {
  664. completionHandler(path, success, retErr);
  665. }
  666. }
  667. return success;
  668. }
  669. #pragma mark - Zipping
  670. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray<NSString *> *)paths
  671. {
  672. return [SSZipArchive createZipFileAtPath:path withFilesAtPaths:paths withPassword:nil];
  673. }
  674. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath {
  675. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath withPassword:nil];
  676. }
  677. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory {
  678. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:keepParentDirectory withPassword:nil];
  679. }
  680. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray<NSString *> *)paths withPassword:(NSString *)password {
  681. return [self createZipFileAtPath:path withFilesAtPaths:paths withPassword:password progressHandler:nil];
  682. }
  683. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray<NSString *> *)paths withPassword:(NSString *)password progressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler
  684. {
  685. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  686. BOOL success = [zipArchive open];
  687. if (success) {
  688. NSUInteger total = paths.count, complete = 0;
  689. for (NSString *filePath in paths) {
  690. success &= [zipArchive writeFile:filePath withPassword:password];
  691. if (progressHandler) {
  692. complete++;
  693. progressHandler(complete, total);
  694. }
  695. }
  696. success &= [zipArchive close];
  697. }
  698. return success;
  699. }
  700. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath withPassword:(nullable NSString *)password {
  701. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:NO withPassword:password];
  702. }
  703. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory withPassword:(nullable NSString *)password {
  704. return [SSZipArchive createZipFileAtPath:path
  705. withContentsOfDirectory:directoryPath
  706. keepParentDirectory:keepParentDirectory
  707. withPassword:password
  708. andProgressHandler:nil
  709. ];
  710. }
  711. + (BOOL)createZipFileAtPath:(NSString *)path
  712. withContentsOfDirectory:(NSString *)directoryPath
  713. keepParentDirectory:(BOOL)keepParentDirectory
  714. withPassword:(nullable NSString *)password
  715. andProgressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler {
  716. return [self createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:keepParentDirectory compressionLevel:Z_DEFAULT_COMPRESSION password:password AES:YES progressHandler:progressHandler];
  717. }
  718. + (BOOL)createZipFileAtPath:(NSString *)path
  719. withContentsOfDirectory:(NSString *)directoryPath
  720. keepParentDirectory:(BOOL)keepParentDirectory
  721. compressionLevel:(int)compressionLevel
  722. password:(nullable NSString *)password
  723. AES:(BOOL)aes
  724. progressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler {
  725. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  726. BOOL success = [zipArchive open];
  727. if (success) {
  728. // use a local fileManager (queue/thread compatibility)
  729. NSFileManager *fileManager = [[NSFileManager alloc] init];
  730. NSDirectoryEnumerator *dirEnumerator = [fileManager enumeratorAtPath:directoryPath];
  731. NSArray<NSString *> *allObjects = dirEnumerator.allObjects;
  732. NSUInteger total = allObjects.count, complete = 0;
  733. if (keepParentDirectory && !total) {
  734. allObjects = @[@""];
  735. total = 1;
  736. }
  737. for (__strong NSString *fileName in allObjects) {
  738. NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:fileName];
  739. if ([fullFilePath isEqualToString:path]) {
  740. NSLog(@"[SSZipArchive] the archive path and the file path: %@ are the same, which is forbidden.", fullFilePath);
  741. continue;
  742. }
  743. if (keepParentDirectory) {
  744. fileName = [directoryPath.lastPathComponent stringByAppendingPathComponent:fileName];
  745. }
  746. BOOL isDir;
  747. [fileManager fileExistsAtPath:fullFilePath isDirectory:&isDir];
  748. if (!isDir) {
  749. // file
  750. success &= [zipArchive writeFileAtPath:fullFilePath withFileName:fileName compressionLevel:compressionLevel password:password AES:aes];
  751. } else {
  752. // directory
  753. if (![fileManager enumeratorAtPath:fullFilePath].nextObject) {
  754. // empty directory
  755. success &= [zipArchive writeFolderAtPath:fullFilePath withFolderName:fileName withPassword:password];
  756. }
  757. }
  758. if (progressHandler) {
  759. complete++;
  760. progressHandler(complete, total);
  761. }
  762. }
  763. success &= [zipArchive close];
  764. }
  765. return success;
  766. }
  767. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray<NSString *> *)paths withPassword:(nullable NSString *)password keepSymlinks:(BOOL)keeplinks {
  768. if (!keeplinks) {
  769. return [SSZipArchive createZipFileAtPath:path withFilesAtPaths:paths withPassword:password];
  770. } else {
  771. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  772. BOOL success = [zipArchive open];
  773. if (success) {
  774. for (NSString *filePath in paths) {
  775. //is symlink
  776. if (mz_os_is_symlink(filePath.fileSystemRepresentation) == MZ_OK) {
  777. success &= [zipArchive writeSymlinkFileAtPath:filePath withFileName:nil compressionLevel:Z_DEFAULT_COMPRESSION password:password AES:YES];
  778. } else {
  779. success &= [zipArchive writeFile:filePath withPassword:password];
  780. }
  781. }
  782. success &= [zipArchive close];
  783. }
  784. return success;
  785. }
  786. }
  787. + (BOOL)createZipFileAtPath:(NSString *)path
  788. withContentsOfDirectory:(NSString *)directoryPath
  789. keepParentDirectory:(BOOL)keepParentDirectory
  790. compressionLevel:(int)compressionLevel
  791. password:(nullable NSString *)password
  792. AES:(BOOL)aes
  793. progressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler
  794. keepSymlinks:(BOOL)keeplinks {
  795. if (!keeplinks) {
  796. return [SSZipArchive createZipFileAtPath:path
  797. withContentsOfDirectory:directoryPath
  798. keepParentDirectory:keepParentDirectory
  799. compressionLevel:compressionLevel
  800. password:password
  801. AES:aes
  802. progressHandler:progressHandler];
  803. } else {
  804. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  805. BOOL success = [zipArchive open];
  806. if (success) {
  807. // use a local fileManager (queue/thread compatibility)
  808. NSFileManager *fileManager = [[NSFileManager alloc] init];
  809. NSDirectoryEnumerator *dirEnumerator = [fileManager enumeratorAtPath:directoryPath];
  810. NSArray<NSString *> *allObjects = dirEnumerator.allObjects;
  811. NSUInteger total = allObjects.count, complete = 0;
  812. if (keepParentDirectory && !total) {
  813. allObjects = @[@""];
  814. total = 1;
  815. }
  816. for (__strong NSString *fileName in allObjects) {
  817. NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:fileName];
  818. if (keepParentDirectory) {
  819. fileName = [directoryPath.lastPathComponent stringByAppendingPathComponent:fileName];
  820. }
  821. //is symlink
  822. BOOL isSymlink = NO;
  823. if (mz_os_is_symlink(fullFilePath.fileSystemRepresentation) == MZ_OK)
  824. isSymlink = YES;
  825. BOOL isDir;
  826. [fileManager fileExistsAtPath:fullFilePath isDirectory:&isDir];
  827. if (!isDir || isSymlink) {
  828. // file or symlink
  829. if (!isSymlink) {
  830. success &= [zipArchive writeFileAtPath:fullFilePath withFileName:fileName compressionLevel:compressionLevel password:password AES:aes];
  831. } else {
  832. success &= [zipArchive writeSymlinkFileAtPath:fullFilePath withFileName:fileName compressionLevel:compressionLevel password:password AES:aes];
  833. }
  834. } else {
  835. // directory
  836. if (![fileManager enumeratorAtPath:fullFilePath].nextObject) {
  837. // empty directory
  838. success &= [zipArchive writeFolderAtPath:fullFilePath withFolderName:fileName withPassword:password];
  839. }
  840. }
  841. if (progressHandler) {
  842. complete++;
  843. progressHandler(complete, total);
  844. }
  845. }
  846. success &= [zipArchive close];
  847. }
  848. return success;
  849. }
  850. }
  851. - (BOOL)writeSymlinkFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName compressionLevel:(int)compressionLevel password:(nullable NSString *)password AES:(BOOL)aes
  852. {
  853. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  854. //read symlink
  855. char link_path[1024];
  856. int32_t err = MZ_OK;
  857. err = mz_os_read_symlink(path.fileSystemRepresentation, link_path, sizeof(link_path));
  858. if (err != MZ_OK) {
  859. NSLog(@"[SSZipArchive] Failed to read sylink");
  860. return NO;
  861. }
  862. if (!fileName) {
  863. fileName = path.lastPathComponent;
  864. }
  865. zip_fileinfo zipInfo = {};
  866. [SSZipArchive zipInfo:&zipInfo setAttributesOfItemAtPath:path];
  867. //unpdate zipInfo.external_fa
  868. uint32_t target_attrib = 0;
  869. uint32_t src_attrib = 0;
  870. uint32_t src_sys = 0;
  871. mz_os_get_file_attribs(path.fileSystemRepresentation, &src_attrib);
  872. src_sys = MZ_HOST_SYSTEM(MZ_VERSION_MADEBY);
  873. if ((src_sys != MZ_HOST_SYSTEM_MSDOS) && (src_sys != MZ_HOST_SYSTEM_WINDOWS_NTFS)) {
  874. /* High bytes are OS specific attributes, low byte is always DOS attributes */
  875. if (mz_zip_attrib_convert(src_sys, src_attrib, MZ_HOST_SYSTEM_MSDOS, &target_attrib) == MZ_OK)
  876. zipInfo.external_fa = target_attrib;
  877. zipInfo.external_fa |= (src_attrib << 16);
  878. } else {
  879. zipInfo.external_fa = src_attrib;
  880. }
  881. uint16_t version_madeby = 3 << 8;//UNIX
  882. int error = zipOpenNewFileInZip5(_zip, fileName.fileSystemRepresentation, &zipInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, compressionLevel, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password.UTF8String, aes, version_madeby, 0, 0);
  883. zipWriteInFileInZip(_zip, link_path, (uint32_t)strlen(link_path));
  884. zipCloseFileInZip(_zip);
  885. return error == ZIP_OK;
  886. }
  887. // disabling `init` because designated initializer is `initWithPath:`
  888. - (instancetype)init { @throw nil; }
  889. // designated initializer
  890. - (instancetype)initWithPath:(NSString *)path
  891. {
  892. if ((self = [super init])) {
  893. _path = [path copy];
  894. }
  895. return self;
  896. }
  897. - (BOOL)open
  898. {
  899. NSAssert((_zip == NULL), @"Attempting to open an archive which is already open");
  900. _zip = zipOpen(_path.fileSystemRepresentation, APPEND_STATUS_CREATE);
  901. return (NULL != _zip);
  902. }
  903. - (BOOL)openForAppending
  904. {
  905. NSAssert((_zip == NULL), @"Attempting to open an archive which is already open");
  906. _zip = zipOpen(_path.fileSystemRepresentation, APPEND_STATUS_ADDINZIP);
  907. return (NULL != _zip);
  908. }
  909. - (BOOL)writeFolderAtPath:(NSString *)path withFolderName:(NSString *)folderName withPassword:(nullable NSString *)password
  910. {
  911. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  912. zip_fileinfo zipInfo = {};
  913. [SSZipArchive zipInfo:&zipInfo setAttributesOfItemAtPath:path];
  914. int error = _zipOpenEntry(_zip, [folderName stringByAppendingString:@"/"], &zipInfo, Z_NO_COMPRESSION, password, NO);
  915. const void *buffer = NULL;
  916. zipWriteInFileInZip(_zip, buffer, 0);
  917. zipCloseFileInZip(_zip);
  918. return error == ZIP_OK;
  919. }
  920. - (BOOL)writeFile:(NSString *)path withPassword:(nullable NSString *)password
  921. {
  922. return [self writeFileAtPath:path withFileName:nil withPassword:password];
  923. }
  924. - (BOOL)writeFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName withPassword:(nullable NSString *)password
  925. {
  926. return [self writeFileAtPath:path withFileName:fileName compressionLevel:Z_DEFAULT_COMPRESSION password:password AES:YES];
  927. }
  928. // supports writing files with logical folder/directory structure
  929. // *path* is the absolute path of the file that will be compressed
  930. // *fileName* is the relative name of the file how it is stored within the zip e.g. /folder/subfolder/text1.txt
  931. - (BOOL)writeFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName compressionLevel:(int)compressionLevel password:(nullable NSString *)password AES:(BOOL)aes
  932. {
  933. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  934. FILE *input = fopen(path.fileSystemRepresentation, "r");
  935. if (NULL == input) {
  936. return NO;
  937. }
  938. if (!fileName) {
  939. fileName = path.lastPathComponent;
  940. }
  941. zip_fileinfo zipInfo = {};
  942. [SSZipArchive zipInfo:&zipInfo setAttributesOfItemAtPath:path];
  943. void *buffer = malloc(CHUNK);
  944. if (buffer == NULL)
  945. {
  946. fclose(input);
  947. return NO;
  948. }
  949. int error = _zipOpenEntry(_zip, fileName, &zipInfo, compressionLevel, password, aes);
  950. while (!feof(input) && !ferror(input))
  951. {
  952. unsigned int len = (unsigned int) fread(buffer, 1, CHUNK, input);
  953. zipWriteInFileInZip(_zip, buffer, len);
  954. }
  955. zipCloseFileInZip(_zip);
  956. free(buffer);
  957. fclose(input);
  958. return error == ZIP_OK;
  959. }
  960. - (BOOL)writeData:(NSData *)data filename:(nullable NSString *)filename withPassword:(nullable NSString *)password
  961. {
  962. return [self writeData:data filename:filename compressionLevel:Z_DEFAULT_COMPRESSION password:password AES:YES];
  963. }
  964. - (BOOL)writeData:(NSData *)data filename:(nullable NSString *)filename compressionLevel:(int)compressionLevel password:(nullable NSString *)password AES:(BOOL)aes
  965. {
  966. if (!_zip) {
  967. return NO;
  968. }
  969. if (!data) {
  970. return NO;
  971. }
  972. zip_fileinfo zipInfo = {};
  973. [SSZipArchive zipInfo:&zipInfo setDate:[NSDate date]];
  974. int error = _zipOpenEntry(_zip, filename, &zipInfo, compressionLevel, password, aes);
  975. zipWriteInFileInZip(_zip, data.bytes, (unsigned int)data.length);
  976. zipCloseFileInZip(_zip);
  977. return error == ZIP_OK;
  978. }
  979. - (BOOL)close
  980. {
  981. NSAssert((_zip != NULL), @"[SSZipArchive] Attempting to close an archive which was never opened");
  982. int error = zipClose(_zip, NULL);
  983. _zip = nil;
  984. return error == ZIP_OK;
  985. }
  986. #pragma mark - Private
  987. + (NSString *)_filenameStringWithCString:(const char *)filename
  988. version_made_by:(uint16_t)version_made_by
  989. general_purpose_flag:(uint16_t)flag
  990. size:(uint16_t)size_filename {
  991. // Respect Language encoding flag only reading filename as UTF-8 when this is set
  992. // when file entry created on dos system.
  993. //
  994. // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
  995. // Bit 11: Language encoding flag (EFS). If this bit is set,
  996. // the filename and comment fields for this file
  997. // MUST be encoded using UTF-8. (see APPENDIX D)
  998. uint16_t made_by = version_made_by >> 8;
  999. BOOL made_on_dos = made_by == 0;
  1000. BOOL languageEncoding = (flag & (1 << 11)) != 0;
  1001. if (!languageEncoding && made_on_dos) {
  1002. // APPNOTE.TXT D.1:
  1003. // D.2 If general purpose bit 11 is unset, the file name and comment should conform
  1004. // to the original ZIP character encoding. If general purpose bit 11 is set, the
  1005. // filename and comment must support The Unicode Standard, Version 4.1.0 or
  1006. // greater using the character encoding form defined by the UTF-8 storage
  1007. // specification. The Unicode Standard is published by the The Unicode
  1008. // Consortium (www.unicode.org). UTF-8 encoded data stored within ZIP files
  1009. // is expected to not include a byte order mark (BOM).
  1010. // Code Page 437 corresponds to kCFStringEncodingDOSLatinUS
  1011. NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingDOSLatinUS);
  1012. NSString* strPath = [NSString stringWithCString:filename encoding:encoding];
  1013. if (strPath) {
  1014. return strPath;
  1015. }
  1016. }
  1017. // attempting unicode encoding
  1018. NSString * strPath = @(filename);
  1019. if (strPath) {
  1020. return strPath;
  1021. }
  1022. // if filename is non-unicode, detect and transform Encoding
  1023. NSData *data = [NSData dataWithBytes:(const void *)filename length:sizeof(unsigned char) * size_filename];
  1024. // Testing availability of @available (https://stackoverflow.com/a/46927445/1033581)
  1025. #if __clang_major__ < 9
  1026. // Xcode 8-
  1027. if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber10_9_2) {
  1028. #else
  1029. // Xcode 9+
  1030. if (@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)) {
  1031. #endif
  1032. // supported encodings are in [NSString availableStringEncodings]
  1033. [NSString stringEncodingForData:data encodingOptions:nil convertedString:&strPath usedLossyConversion:nil];
  1034. } else {
  1035. // fallback to a simple manual detect for macOS 10.9 or older
  1036. NSArray<NSNumber *> *encodings = @[@(kCFStringEncodingGB_18030_2000), @(kCFStringEncodingShiftJIS)];
  1037. for (NSNumber *encoding in encodings) {
  1038. strPath = [NSString stringWithCString:filename encoding:(NSStringEncoding)CFStringConvertEncodingToNSStringEncoding(encoding.unsignedIntValue)];
  1039. if (strPath) {
  1040. break;
  1041. }
  1042. }
  1043. }
  1044. if (strPath) {
  1045. return strPath;
  1046. }
  1047. // if filename encoding is non-detected, we default to something based on data
  1048. // _hexString is more readable than _base64RFC4648 for debugging unknown encodings
  1049. strPath = [data _hexString];
  1050. return strPath;
  1051. }
  1052. + (void)zipInfo:(zip_fileinfo *)zipInfo setAttributesOfItemAtPath:(NSString *)path
  1053. {
  1054. NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error: nil];
  1055. if (attr)
  1056. {
  1057. NSDate *fileDate = (NSDate *)[attr objectForKey:NSFileModificationDate];
  1058. if (fileDate)
  1059. {
  1060. [self zipInfo:zipInfo setDate:fileDate];
  1061. }
  1062. // Write permissions into the external attributes, for details on this see here: https://unix.stackexchange.com/a/14727
  1063. // Get the permissions value from the files attributes
  1064. NSNumber *permissionsValue = (NSNumber *)[attr objectForKey:NSFilePosixPermissions];
  1065. if (permissionsValue != nil) {
  1066. // Get the short value for the permissions
  1067. short permissionsShort = permissionsValue.shortValue;
  1068. // Convert this into an octal by adding 010000, 010000 being the flag for a regular file
  1069. NSInteger permissionsOctal = 0100000 + permissionsShort;
  1070. // Convert this into a long value
  1071. uLong permissionsLong = @(permissionsOctal).unsignedLongValue;
  1072. // Store this into the external file attributes once it has been shifted 16 places left to form part of the second from last byte
  1073. // Casted back to an unsigned int to match type of external_fa in minizip
  1074. zipInfo->external_fa = (unsigned int)(permissionsLong << 16L);
  1075. }
  1076. }
  1077. }
  1078. + (void)zipInfo:(zip_fileinfo *)zipInfo setDate:(NSDate *)date
  1079. {
  1080. NSCalendar *currentCalendar = SSZipArchive._gregorian;
  1081. NSCalendarUnit flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  1082. NSDateComponents *components = [currentCalendar components:flags fromDate:date];
  1083. struct tm tmz_date;
  1084. tmz_date.tm_sec = (unsigned int)components.second;
  1085. tmz_date.tm_min = (unsigned int)components.minute;
  1086. tmz_date.tm_hour = (unsigned int)components.hour;
  1087. tmz_date.tm_mday = (unsigned int)components.day;
  1088. // ISO/IEC 9899 struct tm is 0-indexed for January but NSDateComponents for gregorianCalendar is 1-indexed for January
  1089. tmz_date.tm_mon = (unsigned int)components.month - 1;
  1090. // ISO/IEC 9899 struct tm is 0-indexed for AD 1900 but NSDateComponents for gregorianCalendar is 1-indexed for AD 1
  1091. tmz_date.tm_year = (unsigned int)components.year - 1900;
  1092. zipInfo->mz_dos_date = mz_zip_tm_to_dosdate(&tmz_date);
  1093. }
  1094. + (NSCalendar *)_gregorian
  1095. {
  1096. static NSCalendar *gregorian;
  1097. static dispatch_once_t onceToken;
  1098. dispatch_once(&onceToken, ^{
  1099. gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  1100. });
  1101. return gregorian;
  1102. }
  1103. // Format from http://newsgroups.derkeiler.com/Archive/Comp/comp.os.msdos.programmer/2009-04/msg00060.html
  1104. // Two consecutive words, or a longword, YYYYYYYMMMMDDDDD hhhhhmmmmmmsssss
  1105. // YYYYYYY is years from 1980 = 0
  1106. // sssss is (seconds/2).
  1107. //
  1108. // 3658 = 0011 0110 0101 1000 = 0011011 0010 11000 = 27 2 24 = 2007-02-24
  1109. // 7423 = 0111 0100 0010 0011 - 01110 100001 00011 = 14 33 3 = 14:33:06
  1110. + (NSDate *)_dateWithMSDOSFormat:(UInt32)msdosDateTime
  1111. {
  1112. // the whole `_dateWithMSDOSFormat:` method is equivalent but faster than this one line,
  1113. // essentially because `mktime` is slow:
  1114. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:dosdate_to_time_t(msdosDateTime)];
  1115. static const UInt32 kYearMask = 0xFE000000;
  1116. static const UInt32 kMonthMask = 0x1E00000;
  1117. static const UInt32 kDayMask = 0x1F0000;
  1118. static const UInt32 kHourMask = 0xF800;
  1119. static const UInt32 kMinuteMask = 0x7E0;
  1120. static const UInt32 kSecondMask = 0x1F;
  1121. NSAssert(0xFFFFFFFF == (kYearMask | kMonthMask | kDayMask | kHourMask | kMinuteMask | kSecondMask), @"[SSZipArchive] MSDOS date masks don't add up");
  1122. NSDateComponents *components = [[NSDateComponents alloc] init];
  1123. components.year = 1980 + ((msdosDateTime & kYearMask) >> 25);
  1124. components.month = (msdosDateTime & kMonthMask) >> 21;
  1125. components.day = (msdosDateTime & kDayMask) >> 16;
  1126. components.hour = (msdosDateTime & kHourMask) >> 11;
  1127. components.minute = (msdosDateTime & kMinuteMask) >> 5;
  1128. components.second = (msdosDateTime & kSecondMask) * 2;
  1129. NSDate *date = [self._gregorian dateFromComponents:components];
  1130. return date;
  1131. }
  1132. @end
  1133. int _zipOpenEntry(zipFile entry, NSString *name, const zip_fileinfo *zipfi, int level, NSString *password, BOOL aes)
  1134. {
  1135. // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
  1136. uint16_t made_on_darwin = 19 << 8;
  1137. //MZ_ZIP_FLAG_UTF8
  1138. uint16_t flag_base = 1 << 11;
  1139. return zipOpenNewFileInZip5(entry, name.fileSystemRepresentation, zipfi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, level, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password.UTF8String, aes, made_on_darwin, flag_base, 1);
  1140. }
  1141. #pragma mark - Private tools for file info
  1142. BOOL _fileIsSymbolicLink(const unz_file_info *fileInfo)
  1143. {
  1144. //
  1145. // Determine whether this is a symbolic link:
  1146. // - File is stored with 'version made by' value of UNIX (3),
  1147. // as per https://www.pkware.com/documents/casestudies/APPNOTE.TXT
  1148. // in the upper byte of the version field.
  1149. // - BSD4.4 st_mode constants are stored in the high 16 bits of the
  1150. // external file attributes (defacto standard, verified against libarchive)
  1151. //
  1152. // The original constants can be found here:
  1153. // https://minnie.tuhs.org/cgi-bin/utree.pl?file=4.4BSD/usr/include/sys/stat.h
  1154. //
  1155. const uLong ZipUNIXVersion = 3;
  1156. const uLong BSD_SFMT = 0170000;
  1157. const uLong BSD_IFLNK = 0120000;
  1158. BOOL fileIsSymbolicLink = ((fileInfo->version >> 8) == ZipUNIXVersion) && BSD_IFLNK == (BSD_SFMT & (fileInfo->external_fa >> 16));
  1159. return fileIsSymbolicLink;
  1160. }
  1161. #pragma mark - Private tools for unreadable encodings
  1162. @implementation NSData (SSZipArchive)
  1163. // `base64EncodedStringWithOptions` uses a base64 alphabet with '+' and '/'.
  1164. // we got those alternatives to make it compatible with filenames: https://en.wikipedia.org/wiki/Base64
  1165. // * modified Base64 encoding for IMAP mailbox names (RFC 3501): uses '+' and ','
  1166. // * modified Base64 for URL and filenames (RFC 4648): uses '-' and '_'
  1167. - (NSString *)_base64RFC4648
  1168. {
  1169. NSString *strName = [self base64EncodedStringWithOptions:0];
  1170. strName = [strName stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
  1171. strName = [strName stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
  1172. return strName;
  1173. }
  1174. // initWithBytesNoCopy from NSProgrammer, Jan 25 '12: https://stackoverflow.com/a/9009321/1033581
  1175. // hexChars from Peter, Aug 19 '14: https://stackoverflow.com/a/25378464/1033581
  1176. // not implemented as too lengthy: a potential mapping improvement from Moose, Nov 3 '15: https://stackoverflow.com/a/33501154/1033581
  1177. - (NSString *)_hexString
  1178. {
  1179. const char *hexChars = "0123456789ABCDEF";
  1180. NSUInteger length = self.length;
  1181. const unsigned char *bytes = self.bytes;
  1182. char *chars = malloc(length * 2);
  1183. if (chars == NULL) {
  1184. // we directly raise an exception instead of using NSAssert to make sure assertion is not disabled as this is irrecoverable
  1185. [NSException raise:@"NSInternalInconsistencyException" format:@"failed malloc" arguments:nil];
  1186. return nil;
  1187. }
  1188. char *s = chars;
  1189. NSUInteger i = length;
  1190. while (i--) {
  1191. *s++ = hexChars[*bytes >> 4];
  1192. *s++ = hexChars[*bytes & 0xF];
  1193. bytes++;
  1194. }
  1195. NSString *str = [[NSString alloc] initWithBytesNoCopy:chars
  1196. length:length * 2
  1197. encoding:NSASCIIStringEncoding
  1198. freeWhenDone:YES];
  1199. return str;
  1200. }
  1201. @end
  1202. #pragma mark Private tools for security
  1203. @implementation NSString (SSZipArchive)
  1204. // One implementation alternative would be to use the algorithm found at mz_path_resolve from https://github.com/nmoinvaz/minizip/blob/dev/mz_os.c,
  1205. // but making sure to work with unichar values and not ascii values to avoid breaking Unicode characters containing 2E ('.') or 2F ('/') in their decomposition
  1206. /// Sanitize path traversal characters to prevent directory backtracking. Ignoring these characters mimicks the default behavior of the Unarchiving tool on macOS.
  1207. - (NSString *)_sanitizedPath
  1208. {
  1209. // Change Windows paths to Unix paths: https://en.wikipedia.org/wiki/Path_(computing)
  1210. // Possible improvement: only do this if the archive was created on a non-Unix system
  1211. NSString *strPath = [self stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
  1212. // Percent-encode file path (where path is defined by https://tools.ietf.org/html/rfc8089)
  1213. // The key part is to allow characters "." and "/" and disallow "%".
  1214. // CharacterSet.urlPathAllowed seems to do the job
  1215. #if (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 || __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 || __WATCH_OS_VERSION_MIN_REQUIRED >= 20000 || __TV_OS_VERSION_MIN_REQUIRED >= 90000)
  1216. strPath = [strPath stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
  1217. #else
  1218. // Testing availability of @available (https://stackoverflow.com/a/46927445/1033581)
  1219. #if __clang_major__ < 9
  1220. // Xcode 8-
  1221. if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber10_8_4) {
  1222. #else
  1223. // Xcode 9+
  1224. if (@available(macOS 10.9, iOS 7.0, watchOS 2.0, tvOS 9.0, *)) {
  1225. #endif
  1226. strPath = [strPath stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
  1227. } else {
  1228. strPath = [strPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  1229. }
  1230. #endif
  1231. // `NSString.stringByAddingPercentEncodingWithAllowedCharacters:` may theorically fail: https://stackoverflow.com/questions/33558933/
  1232. // But because we auto-detect encoding using `NSString.stringEncodingForData:encodingOptions:convertedString:usedLossyConversion:`,
  1233. // we likely already prevent UTF-16, UTF-32 and invalid Unicode in the form of unpaired surrogate chars: https://stackoverflow.com/questions/53043876/
  1234. // To be on the safe side, we will still perform a guard check.
  1235. if (strPath == nil) {
  1236. return nil;
  1237. }
  1238. // Add scheme "file:///" to support sanitation on names with a colon like "file:a/../../../usr/bin"
  1239. strPath = [@"file:///" stringByAppendingString:strPath];
  1240. // Sanitize path traversal characters to prevent directory backtracking. Ignoring these characters mimicks the default behavior of the Unarchiving tool on macOS.
  1241. // "../../../../../../../../../../../tmp/test.txt" -> "tmp/test.txt"
  1242. // "a/b/../c.txt" -> "a/c.txt"
  1243. strPath = [NSURL URLWithString:strPath].standardizedURL.absoluteString;
  1244. // Remove the "file:///" scheme
  1245. strPath = [strPath substringFromIndex:8];
  1246. // Remove the percent-encoding
  1247. #if (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 || __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 || __WATCH_OS_VERSION_MIN_REQUIRED >= 20000 || __TV_OS_VERSION_MIN_REQUIRED >= 90000)
  1248. strPath = strPath.stringByRemovingPercentEncoding;
  1249. #else
  1250. // Testing availability of @available (https://stackoverflow.com/a/46927445/1033581)
  1251. #if __clang_major__ < 9
  1252. // Xcode 8-
  1253. if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber10_8_4) {
  1254. #else
  1255. // Xcode 9+
  1256. if (@available(macOS 10.9, iOS 7.0, watchOS 2.0, tvOS 9.0, *)) {
  1257. #endif
  1258. strPath = strPath.stringByRemovingPercentEncoding;
  1259. } else {
  1260. strPath = [strPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  1261. }
  1262. #endif
  1263. return strPath;
  1264. }
  1265. @end