SSZipArchive.m 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. //
  2. // SSZipArchive.m
  3. // SSZipArchive
  4. //
  5. // Created by Sam Soffes on 7/21/10.
  6. // Copyright (c) Sam Soffes 2010-2015. All rights reserved.
  7. //
  8. #import "SSZipArchive.h"
  9. #include "unzip.h"
  10. #include "zip.h"
  11. #include "minishared.h"
  12. #include <sys/stat.h>
  13. NSString *const SSZipArchiveErrorDomain = @"SSZipArchiveErrorDomain";
  14. #define CHUNK 16384
  15. #ifndef API_AVAILABLE
  16. // Xcode 7- compatibility
  17. #define API_AVAILABLE(...)
  18. #endif
  19. @interface NSData(SSZipArchive)
  20. - (NSString *)_base64RFC4648 API_AVAILABLE(macos(10.9), ios(7.0), watchos(2.0), tvos(9.0));
  21. - (NSString *)_hexString;
  22. @end
  23. @interface SSZipArchive ()
  24. - (instancetype)init NS_DESIGNATED_INITIALIZER;
  25. @end
  26. @implementation SSZipArchive
  27. {
  28. /// path for zip file
  29. NSString *_path;
  30. zipFile _zip;
  31. }
  32. #pragma mark - Password check
  33. + (BOOL)isFilePasswordProtectedAtPath:(NSString *)path {
  34. // Begin opening
  35. zipFile zip = unzOpen(path.fileSystemRepresentation);
  36. if (zip == NULL) {
  37. return NO;
  38. }
  39. int ret = unzGoToFirstFile(zip);
  40. if (ret == UNZ_OK) {
  41. do {
  42. ret = unzOpenCurrentFile(zip);
  43. if (ret != UNZ_OK) {
  44. return NO;
  45. }
  46. unz_file_info fileInfo = {0};
  47. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  48. if (ret != UNZ_OK) {
  49. return NO;
  50. } else if ((fileInfo.flag & 1) == 1) {
  51. return YES;
  52. }
  53. unzCloseCurrentFile(zip);
  54. ret = unzGoToNextFile(zip);
  55. } while (ret == UNZ_OK && UNZ_OK != UNZ_END_OF_LIST_OF_FILE);
  56. }
  57. return NO;
  58. }
  59. + (BOOL)isPasswordValidForArchiveAtPath:(NSString *)path password:(NSString *)pw error:(NSError **)error {
  60. if (error) {
  61. *error = nil;
  62. }
  63. zipFile zip = unzOpen(path.fileSystemRepresentation);
  64. if (zip == NULL) {
  65. if (error) {
  66. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  67. code:SSZipArchiveErrorCodeFailedOpenZipFile
  68. userInfo:@{NSLocalizedDescriptionKey: @"failed to open zip file"}];
  69. }
  70. return NO;
  71. }
  72. int ret = unzGoToFirstFile(zip);
  73. if (ret == UNZ_OK) {
  74. do {
  75. if (pw.length == 0) {
  76. ret = unzOpenCurrentFile(zip);
  77. } else {
  78. ret = unzOpenCurrentFilePassword(zip, [pw cStringUsingEncoding:NSUTF8StringEncoding]);
  79. }
  80. if (ret != UNZ_OK) {
  81. if (ret != UNZ_BADPASSWORD) {
  82. if (error) {
  83. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  84. code:SSZipArchiveErrorCodeFailedOpenFileInZip
  85. userInfo:@{NSLocalizedDescriptionKey: @"failed to open first file in zip file"}];
  86. }
  87. }
  88. return NO;
  89. }
  90. unz_file_info fileInfo = {0};
  91. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  92. if (ret != UNZ_OK) {
  93. if (error) {
  94. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  95. code:SSZipArchiveErrorCodeFileInfoNotLoadable
  96. userInfo:@{NSLocalizedDescriptionKey: @"failed to retrieve info for file"}];
  97. }
  98. return NO;
  99. } else if ((fileInfo.flag & 1) == 1) {
  100. unsigned char buffer[10] = {0};
  101. int readBytes = unzReadCurrentFile(zip, buffer, (unsigned)MIN(10UL,fileInfo.uncompressed_size));
  102. if (readBytes < 0) {
  103. // Let's assume the invalid password caused this error
  104. if (readBytes != Z_DATA_ERROR) {
  105. if (error) {
  106. *error = [NSError errorWithDomain:SSZipArchiveErrorDomain
  107. code:SSZipArchiveErrorCodeFileContentNotReadable
  108. userInfo:@{NSLocalizedDescriptionKey: @"failed to read contents of file entry"}];
  109. }
  110. }
  111. return NO;
  112. }
  113. return YES;
  114. }
  115. unzCloseCurrentFile(zip);
  116. ret = unzGoToNextFile(zip);
  117. } while (ret == UNZ_OK && UNZ_OK != UNZ_END_OF_LIST_OF_FILE);
  118. }
  119. // No password required
  120. return YES;
  121. }
  122. #pragma mark - Unzipping
  123. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination
  124. {
  125. return [self unzipFileAtPath:path toDestination:destination delegate:nil];
  126. }
  127. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(nullable NSString *)password error:(NSError **)error
  128. {
  129. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:overwrite password:password error:error delegate:nil progressHandler:nil completionHandler:nil];
  130. }
  131. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination delegate:(nullable id<SSZipArchiveDelegate>)delegate
  132. {
  133. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:YES password:nil error:nil delegate:delegate progressHandler:nil completionHandler:nil];
  134. }
  135. + (BOOL)unzipFileAtPath:(NSString *)path
  136. toDestination:(NSString *)destination
  137. overwrite:(BOOL)overwrite
  138. password:(nullable NSString *)password
  139. error:(NSError **)error
  140. delegate:(nullable id<SSZipArchiveDelegate>)delegate
  141. {
  142. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:overwrite password:password error:error delegate:delegate progressHandler:nil completionHandler:nil];
  143. }
  144. + (BOOL)unzipFileAtPath:(NSString *)path
  145. toDestination:(NSString *)destination
  146. overwrite:(BOOL)overwrite
  147. password:(NSString *)password
  148. progressHandler:(void (^)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  149. completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler
  150. {
  151. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:overwrite password:password error:nil delegate:nil progressHandler:progressHandler completionHandler:completionHandler];
  152. }
  153. + (BOOL)unzipFileAtPath:(NSString *)path
  154. toDestination:(NSString *)destination
  155. progressHandler:(void (^)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  156. completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler
  157. {
  158. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:YES overwrite:YES password:nil error:nil delegate:nil progressHandler:progressHandler completionHandler:completionHandler];
  159. }
  160. + (BOOL)unzipFileAtPath:(NSString *)path
  161. toDestination:(NSString *)destination
  162. preserveAttributes:(BOOL)preserveAttributes
  163. overwrite:(BOOL)overwrite
  164. password:(nullable NSString *)password
  165. error:(NSError * *)error
  166. delegate:(nullable id<SSZipArchiveDelegate>)delegate
  167. {
  168. return [self unzipFileAtPath:path toDestination:destination preserveAttributes:preserveAttributes overwrite:overwrite password:password error:error delegate:delegate progressHandler:nil completionHandler:nil];
  169. }
  170. + (BOOL)unzipFileAtPath:(NSString *)path
  171. toDestination:(NSString *)destination
  172. preserveAttributes:(BOOL)preserveAttributes
  173. overwrite:(BOOL)overwrite
  174. password:(nullable NSString *)password
  175. error:(NSError **)error
  176. delegate:(id<SSZipArchiveDelegate>)delegate
  177. progressHandler:(void (^)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  178. completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler
  179. {
  180. // Guard against empty strings
  181. if (path.length == 0 || destination.length == 0)
  182. {
  183. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"received invalid argument(s)"};
  184. NSError *err = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeInvalidArguments userInfo:userInfo];
  185. if (error)
  186. {
  187. *error = err;
  188. }
  189. if (completionHandler)
  190. {
  191. completionHandler(nil, NO, err);
  192. }
  193. return NO;
  194. }
  195. // Begin opening
  196. zipFile zip = unzOpen(path.fileSystemRepresentation);
  197. if (zip == NULL)
  198. {
  199. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"failed to open zip file"};
  200. NSError *err = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeFailedOpenZipFile userInfo:userInfo];
  201. if (error)
  202. {
  203. *error = err;
  204. }
  205. if (completionHandler)
  206. {
  207. completionHandler(nil, NO, err);
  208. }
  209. return NO;
  210. }
  211. NSDictionary * fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
  212. unsigned long long fileSize = [fileAttributes[NSFileSize] unsignedLongLongValue];
  213. unsigned long long currentPosition = 0;
  214. unz_global_info globalInfo = {0ul, 0ul};
  215. unzGetGlobalInfo(zip, &globalInfo);
  216. // Begin unzipping
  217. if (unzGoToFirstFile(zip) != UNZ_OK)
  218. {
  219. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"failed to open first file in zip file"};
  220. NSError *err = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeFailedOpenFileInZip userInfo:userInfo];
  221. if (error)
  222. {
  223. *error = err;
  224. }
  225. if (completionHandler)
  226. {
  227. completionHandler(nil, NO, err);
  228. }
  229. return NO;
  230. }
  231. BOOL success = YES;
  232. BOOL canceled = NO;
  233. int ret = 0;
  234. int crc_ret = 0;
  235. unsigned char buffer[4096] = {0};
  236. NSFileManager *fileManager = [NSFileManager defaultManager];
  237. NSMutableArray<NSDictionary *> *directoriesModificationDates = [[NSMutableArray alloc] init];
  238. // Message delegate
  239. if ([delegate respondsToSelector:@selector(zipArchiveWillUnzipArchiveAtPath:zipInfo:)]) {
  240. [delegate zipArchiveWillUnzipArchiveAtPath:path zipInfo:globalInfo];
  241. }
  242. if ([delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  243. [delegate zipArchiveProgressEvent:currentPosition total:fileSize];
  244. }
  245. NSInteger currentFileNumber = 0;
  246. NSError *unzippingError;
  247. do {
  248. @autoreleasepool {
  249. if (password.length == 0) {
  250. ret = unzOpenCurrentFile(zip);
  251. } else {
  252. ret = unzOpenCurrentFilePassword(zip, [password cStringUsingEncoding:NSUTF8StringEncoding]);
  253. }
  254. if (ret != UNZ_OK) {
  255. unzippingError = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:SSZipArchiveErrorCodeFailedOpenFileInZip userInfo:@{NSLocalizedDescriptionKey: @"failed to open file in zip file"}];
  256. success = NO;
  257. break;
  258. }
  259. // Reading data and write to file
  260. unz_file_info fileInfo;
  261. memset(&fileInfo, 0, sizeof(unz_file_info));
  262. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  263. if (ret != UNZ_OK) {
  264. unzippingError = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:SSZipArchiveErrorCodeFileInfoNotLoadable userInfo:@{NSLocalizedDescriptionKey: @"failed to retrieve info for file"}];
  265. success = NO;
  266. unzCloseCurrentFile(zip);
  267. break;
  268. }
  269. currentPosition += fileInfo.compressed_size;
  270. // Message delegate
  271. if ([delegate respondsToSelector:@selector(zipArchiveShouldUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  272. if (![delegate zipArchiveShouldUnzipFileAtIndex:currentFileNumber
  273. totalFiles:(NSInteger)globalInfo.number_entry
  274. archivePath:path fileInfo:fileInfo]) {
  275. success = NO;
  276. canceled = YES;
  277. break;
  278. }
  279. }
  280. if ([delegate respondsToSelector:@selector(zipArchiveWillUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  281. [delegate zipArchiveWillUnzipFileAtIndex:currentFileNumber totalFiles:(NSInteger)globalInfo.number_entry
  282. archivePath:path fileInfo:fileInfo];
  283. }
  284. if ([delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  285. [delegate zipArchiveProgressEvent:(NSInteger)currentPosition total:(NSInteger)fileSize];
  286. }
  287. char *filename = (char *)malloc(fileInfo.size_filename + 1);
  288. if (filename == NULL)
  289. {
  290. success = NO;
  291. break;
  292. }
  293. unzGetCurrentFileInfo(zip, &fileInfo, filename, fileInfo.size_filename + 1, NULL, 0, NULL, 0);
  294. filename[fileInfo.size_filename] = '\0';
  295. //
  296. // Determine whether this is a symbolic link:
  297. // - File is stored with 'version made by' value of UNIX (3),
  298. // as per http://www.pkware.com/documents/casestudies/APPNOTE.TXT
  299. // in the upper byte of the version field.
  300. // - BSD4.4 st_mode constants are stored in the high 16 bits of the
  301. // external file attributes (defacto standard, verified against libarchive)
  302. //
  303. // The original constants can be found here:
  304. // http://minnie.tuhs.org/cgi-bin/utree.pl?file=4.4BSD/usr/include/sys/stat.h
  305. //
  306. const uLong ZipUNIXVersion = 3;
  307. const uLong BSD_SFMT = 0170000;
  308. const uLong BSD_IFLNK = 0120000;
  309. BOOL fileIsSymbolicLink = NO;
  310. if (((fileInfo.version >> 8) == ZipUNIXVersion) && BSD_IFLNK == (BSD_SFMT & (fileInfo.external_fa >> 16))) {
  311. fileIsSymbolicLink = YES;
  312. }
  313. NSString * strPath = @(filename);
  314. if (!strPath) {
  315. // if filename is non-unicode, detect and transform Encoding
  316. NSData *data = [NSData dataWithBytes:(const void *)filename length:sizeof(unsigned char) * fileInfo.size_filename];
  317. #ifdef __MAC_10_13
  318. // Xcode 9+
  319. if (@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)) {
  320. #else
  321. // Xcode 8-
  322. if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber10_9_2) {
  323. #endif
  324. // supported encodings are in [NSString availableStringEncodings]
  325. NSArray<NSNumber *> *encodings = @[@(kCFStringEncodingMacChineseSimp), @(kCFStringEncodingShiftJIS)];
  326. for (NSNumber *encoding in encodings) {
  327. strPath = [NSString stringWithCString:filename encoding:(NSStringEncoding)CFStringConvertEncodingToNSStringEncoding(encoding.unsignedIntValue)];
  328. if (strPath) {
  329. break;
  330. }
  331. }
  332. } else {
  333. // fallback to a simple manual detect for macOS 10.9 or older
  334. NSArray<NSNumber *> *encodings = @[@(kCFStringEncodingMacChineseSimp), @(kCFStringEncodingShiftJIS)];
  335. for (NSNumber *encoding in encodings) {
  336. strPath = [NSString stringWithCString:filename encoding:(NSStringEncoding)CFStringConvertEncodingToNSStringEncoding(encoding.unsignedIntValue)];
  337. if (strPath) {
  338. break;
  339. }
  340. }
  341. }
  342. if (!strPath) {
  343. // if filename encoding is non-detected, we default to something based on data
  344. // _hexString is more readable than _base64RFC4648 for debugging unknown encodings
  345. strPath = [data _hexString];
  346. }
  347. }
  348. if (!strPath.length) {
  349. // if filename data is unsalvageable, we default to currentFileNumber
  350. strPath = @(currentFileNumber).stringValue;
  351. }
  352. // Check if it contains directory
  353. BOOL isDirectory = NO;
  354. if (filename[fileInfo.size_filename-1] == '/' || filename[fileInfo.size_filename-1] == '\\') {
  355. isDirectory = YES;
  356. }
  357. free(filename);
  358. // Contains a path
  359. if ([strPath rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"/\\"]].location != NSNotFound) {
  360. strPath = [strPath stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
  361. }
  362. NSString *fullPath = [destination stringByAppendingPathComponent:strPath];
  363. NSError *err = nil;
  364. NSDictionary *directoryAttr;
  365. if (preserveAttributes) {
  366. NSDate *modDate = [[self class] _dateWithMSDOSFormat:(UInt32)fileInfo.dos_date];
  367. directoryAttr = @{NSFileCreationDate: modDate, NSFileModificationDate: modDate};
  368. [directoriesModificationDates addObject: @{@"path": fullPath, @"modDate": modDate}];
  369. }
  370. if (isDirectory) {
  371. [fileManager createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:directoryAttr error:&err];
  372. } else {
  373. [fileManager createDirectoryAtPath:fullPath.stringByDeletingLastPathComponent withIntermediateDirectories:YES attributes:directoryAttr error:&err];
  374. }
  375. if (nil != err) {
  376. if ([err.domain isEqualToString:NSCocoaErrorDomain] &&
  377. err.code == 640) {
  378. unzippingError = err;
  379. unzCloseCurrentFile(zip);
  380. success = NO;
  381. break;
  382. }
  383. NSLog(@"[SSZipArchive] Error: %@", err.localizedDescription);
  384. }
  385. if ([fileManager fileExistsAtPath:fullPath] && !isDirectory && !overwrite) {
  386. //FIXME: couldBe CRC Check?
  387. unzCloseCurrentFile(zip);
  388. ret = unzGoToNextFile(zip);
  389. continue;
  390. }
  391. if (!fileIsSymbolicLink) {
  392. // ensure we are not creating stale file entries
  393. int readBytes = unzReadCurrentFile(zip, buffer, 4096);
  394. if (readBytes >= 0) {
  395. FILE *fp = fopen(fullPath.fileSystemRepresentation, "wb");
  396. while (fp) {
  397. if (readBytes > 0) {
  398. if (0 == fwrite(buffer, readBytes, 1, fp)) {
  399. if (ferror(fp)) {
  400. NSString *message = [NSString stringWithFormat:@"Failed to write file (check your free space)"];
  401. NSLog(@"[SSZipArchive] %@", message);
  402. success = NO;
  403. unzippingError = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:SSZipArchiveErrorCodeFailedToWriteFile userInfo:@{NSLocalizedDescriptionKey: message}];
  404. break;
  405. }
  406. }
  407. } else {
  408. break;
  409. }
  410. readBytes = unzReadCurrentFile(zip, buffer, 4096);
  411. }
  412. if (fp) {
  413. if ([fullPath.pathExtension.lowercaseString isEqualToString:@"zip"]) {
  414. NSLog(@"Unzipping nested .zip file: %@", fullPath.lastPathComponent);
  415. if ([self unzipFileAtPath:fullPath toDestination:fullPath.stringByDeletingLastPathComponent overwrite:overwrite password:password error:nil delegate:nil]) {
  416. [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
  417. }
  418. }
  419. fclose(fp);
  420. if (preserveAttributes) {
  421. // Set the original datetime property
  422. if (fileInfo.dos_date != 0) {
  423. NSDate *orgDate = [[self class] _dateWithMSDOSFormat:(UInt32)fileInfo.dos_date];
  424. NSDictionary *attr = @{NSFileModificationDate: orgDate};
  425. if (attr) {
  426. if (![fileManager setAttributes:attr ofItemAtPath:fullPath error:nil]) {
  427. // Can't set attributes
  428. NSLog(@"[SSZipArchive] Failed to set attributes - whilst setting modification date");
  429. }
  430. }
  431. }
  432. // Set the original permissions on the file (+read/write to solve #293)
  433. uLong permissions = fileInfo.external_fa >> 16 | 0b110000000;
  434. if (permissions != 0) {
  435. // Store it into a NSNumber
  436. NSNumber *permissionsValue = @(permissions);
  437. // Retrieve any existing attributes
  438. NSMutableDictionary *attrs = [[NSMutableDictionary alloc] initWithDictionary:[fileManager attributesOfItemAtPath:fullPath error:nil]];
  439. // Set the value in the attributes dict
  440. attrs[NSFilePosixPermissions] = permissionsValue;
  441. // Update attributes
  442. if (![fileManager setAttributes:attrs ofItemAtPath:fullPath error:nil]) {
  443. // Unable to set the permissions attribute
  444. NSLog(@"[SSZipArchive] Failed to set attributes - whilst setting permissions");
  445. }
  446. }
  447. }
  448. }
  449. else
  450. {
  451. // if we couldn't open file descriptor we can validate global errno to see the reason
  452. if (errno == ENOSPC) {
  453. NSError *enospcError = [NSError errorWithDomain:NSPOSIXErrorDomain
  454. code:ENOSPC
  455. userInfo:nil];
  456. unzippingError = enospcError;
  457. unzCloseCurrentFile(zip);
  458. success = NO;
  459. break;
  460. }
  461. }
  462. }
  463. }
  464. else
  465. {
  466. // Assemble the path for the symbolic link
  467. NSMutableString *destinationPath = [NSMutableString string];
  468. int bytesRead = 0;
  469. while ((bytesRead = unzReadCurrentFile(zip, buffer, 4096)) > 0)
  470. {
  471. buffer[bytesRead] = (int)0;
  472. [destinationPath appendString:@((const char *)buffer)];
  473. }
  474. // Check if the symlink exists and delete it if we're overwriting
  475. if (overwrite)
  476. {
  477. if ([fileManager fileExistsAtPath:fullPath])
  478. {
  479. NSError *error = nil;
  480. BOOL removeSuccess = [fileManager removeItemAtPath:fullPath error:&error];
  481. if (!removeSuccess)
  482. {
  483. NSString *message = [NSString stringWithFormat:@"Failed to delete existing symbolic link at \"%@\"", error.localizedDescription];
  484. NSLog(@"[SSZipArchive] %@", message);
  485. success = NO;
  486. unzippingError = [NSError errorWithDomain:SSZipArchiveErrorDomain code:error.code userInfo:@{NSLocalizedDescriptionKey: message}];
  487. }
  488. }
  489. }
  490. // Create the symbolic link (making sure it stays relative if it was relative before)
  491. int symlinkError = symlink([destinationPath cStringUsingEncoding:NSUTF8StringEncoding],
  492. [fullPath cStringUsingEncoding:NSUTF8StringEncoding]);
  493. if (symlinkError != 0)
  494. {
  495. // Bubble the error up to the completion handler
  496. NSString *message = [NSString stringWithFormat:@"Failed to create symbolic link at \"%@\" to \"%@\" - symlink() error code: %d", fullPath, destinationPath, errno];
  497. NSLog(@"[SSZipArchive] %@", message);
  498. success = NO;
  499. unzippingError = [NSError errorWithDomain:NSPOSIXErrorDomain code:symlinkError userInfo:@{NSLocalizedDescriptionKey: message}];
  500. }
  501. }
  502. crc_ret = unzCloseCurrentFile(zip);
  503. if (crc_ret == UNZ_CRCERROR) {
  504. //CRC ERROR
  505. success = NO;
  506. break;
  507. }
  508. ret = unzGoToNextFile(zip);
  509. // Message delegate
  510. if ([delegate respondsToSelector:@selector(zipArchiveDidUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  511. [delegate zipArchiveDidUnzipFileAtIndex:currentFileNumber totalFiles:(NSInteger)globalInfo.number_entry
  512. archivePath:path fileInfo:fileInfo];
  513. } else if ([delegate respondsToSelector: @selector(zipArchiveDidUnzipFileAtIndex:totalFiles:archivePath:unzippedFilePath:)]) {
  514. [delegate zipArchiveDidUnzipFileAtIndex: currentFileNumber totalFiles: (NSInteger)globalInfo.number_entry
  515. archivePath:path unzippedFilePath: fullPath];
  516. }
  517. currentFileNumber++;
  518. if (progressHandler)
  519. {
  520. progressHandler(strPath, fileInfo, currentFileNumber, globalInfo.number_entry);
  521. }
  522. }
  523. } while (ret == UNZ_OK && success);
  524. // Close
  525. unzClose(zip);
  526. // The process of decompressing the .zip archive causes the modification times on the folders
  527. // to be set to the present time. So, when we are done, they need to be explicitly set.
  528. // set the modification date on all of the directories.
  529. if (success && preserveAttributes) {
  530. NSError * err = nil;
  531. for (NSDictionary * d in directoriesModificationDates) {
  532. if (![[NSFileManager defaultManager] setAttributes:@{NSFileModificationDate: d[@"modDate"]} ofItemAtPath:d[@"path"] error:&err]) {
  533. NSLog(@"[SSZipArchive] Set attributes failed for directory: %@.", d[@"path"]);
  534. }
  535. if (err) {
  536. NSLog(@"[SSZipArchive] Error setting directory file modification date attribute: %@", err.localizedDescription);
  537. }
  538. }
  539. }
  540. // Message delegate
  541. if (success && [delegate respondsToSelector:@selector(zipArchiveDidUnzipArchiveAtPath:zipInfo:unzippedPath:)]) {
  542. [delegate zipArchiveDidUnzipArchiveAtPath:path zipInfo:globalInfo unzippedPath:destination];
  543. }
  544. // final progress event = 100%
  545. if (!canceled && [delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  546. [delegate zipArchiveProgressEvent:fileSize total:fileSize];
  547. }
  548. NSError *retErr = nil;
  549. if (crc_ret == UNZ_CRCERROR)
  550. {
  551. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"crc check failed for file"};
  552. retErr = [NSError errorWithDomain:SSZipArchiveErrorDomain code:SSZipArchiveErrorCodeFileInfoNotLoadable userInfo:userInfo];
  553. }
  554. if (error) {
  555. if (unzippingError) {
  556. *error = unzippingError;
  557. }
  558. else {
  559. *error = retErr;
  560. }
  561. }
  562. if (completionHandler)
  563. {
  564. if (unzippingError) {
  565. completionHandler(path, success, unzippingError);
  566. }
  567. else
  568. {
  569. completionHandler(path, success, retErr);
  570. }
  571. }
  572. return success;
  573. }
  574. #pragma mark - Zipping
  575. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray<NSString *> *)paths
  576. {
  577. return [SSZipArchive createZipFileAtPath:path withFilesAtPaths:paths withPassword:nil];
  578. }
  579. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath {
  580. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath withPassword:nil];
  581. }
  582. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory {
  583. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:keepParentDirectory withPassword:nil];
  584. }
  585. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray<NSString *> *)paths withPassword:(NSString *)password
  586. {
  587. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  588. BOOL success = [zipArchive open];
  589. if (success) {
  590. for (NSString *filePath in paths) {
  591. success &= [zipArchive writeFile:filePath withPassword:password];
  592. }
  593. success &= [zipArchive close];
  594. }
  595. return success;
  596. }
  597. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath withPassword:(nullable NSString *)password {
  598. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:NO withPassword:password];
  599. }
  600. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory withPassword:(nullable NSString *)password {
  601. return [SSZipArchive createZipFileAtPath:path
  602. withContentsOfDirectory:directoryPath
  603. keepParentDirectory:keepParentDirectory
  604. withPassword:password
  605. andProgressHandler:nil
  606. ];
  607. }
  608. + (BOOL)createZipFileAtPath:(NSString *)path
  609. withContentsOfDirectory:(NSString *)directoryPath
  610. keepParentDirectory:(BOOL)keepParentDirectory
  611. withPassword:(nullable NSString *)password
  612. andProgressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler {
  613. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  614. BOOL success = [zipArchive open];
  615. if (success) {
  616. // use a local fileManager (queue/thread compatibility)
  617. NSFileManager *fileManager = [[NSFileManager alloc] init];
  618. NSDirectoryEnumerator *dirEnumerator = [fileManager enumeratorAtPath:directoryPath];
  619. NSArray<NSString *> *allObjects = dirEnumerator.allObjects;
  620. NSUInteger total = allObjects.count, complete = 0;
  621. NSString *fileName;
  622. for (fileName in allObjects) {
  623. BOOL isDir;
  624. NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:fileName];
  625. [fileManager fileExistsAtPath:fullFilePath isDirectory:&isDir];
  626. if (keepParentDirectory)
  627. {
  628. fileName = [directoryPath.lastPathComponent stringByAppendingPathComponent:fileName];
  629. }
  630. if (!isDir) {
  631. success &= [zipArchive writeFileAtPath:fullFilePath withFileName:fileName withPassword:password];
  632. }
  633. else
  634. {
  635. if ([[NSFileManager defaultManager] subpathsOfDirectoryAtPath:fullFilePath error:nil].count == 0)
  636. {
  637. NSString *tempFilePath = [self _temporaryPathForDiscardableFile];
  638. NSString *tempFileFilename = [fileName stringByAppendingPathComponent:tempFilePath.lastPathComponent];
  639. success &= [zipArchive writeFileAtPath:tempFilePath withFileName:tempFileFilename withPassword:password];
  640. }
  641. }
  642. complete++;
  643. if (progressHandler) {
  644. progressHandler(complete, total);
  645. }
  646. }
  647. success &= [zipArchive close];
  648. }
  649. return success;
  650. }
  651. // disabling `init` because designated initializer is `initWithPath:`
  652. - (instancetype)init { @throw nil; }
  653. // designated initializer
  654. - (instancetype)initWithPath:(NSString *)path
  655. {
  656. if ((self = [super init])) {
  657. _path = [path copy];
  658. }
  659. return self;
  660. }
  661. - (BOOL)open
  662. {
  663. NSAssert((_zip == NULL), @"Attempting to open an archive which is already open");
  664. _zip = zipOpen(_path.fileSystemRepresentation, APPEND_STATUS_CREATE);
  665. return (NULL != _zip);
  666. }
  667. - (void)zipInfo:(zip_fileinfo *)zipInfo setDate:(NSDate *)date
  668. {
  669. NSCalendar *currentCalendar = SSZipArchive._gregorian;
  670. NSCalendarUnit flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  671. NSDateComponents *components = [currentCalendar components:flags fromDate:date];
  672. struct tm tmz_date;
  673. tmz_date.tm_sec = (unsigned int)components.second;
  674. tmz_date.tm_min = (unsigned int)components.minute;
  675. tmz_date.tm_hour = (unsigned int)components.hour;
  676. tmz_date.tm_mday = (unsigned int)components.day;
  677. // ISO/IEC 9899 struct tm is 0-indexed for January but NSDateComponents for gregorianCalendar is 1-indexed for January
  678. tmz_date.tm_mon = (unsigned int)components.month - 1;
  679. // ISO/IEC 9899 struct tm is 0-indexed for AD 1900 but NSDateComponents for gregorianCalendar is 1-indexed for AD 1
  680. tmz_date.tm_year = (unsigned int)components.year - 1900;
  681. zipInfo->dos_date = tm_to_dosdate(&tmz_date);
  682. }
  683. - (BOOL)writeFolderAtPath:(NSString *)path withFolderName:(NSString *)folderName withPassword:(nullable NSString *)password
  684. {
  685. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  686. zip_fileinfo zipInfo = {0,0,0};
  687. NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error: nil];
  688. if (attr)
  689. {
  690. NSDate *fileDate = (NSDate *)attr[NSFileModificationDate];
  691. if (fileDate)
  692. {
  693. [self zipInfo:&zipInfo setDate: fileDate];
  694. }
  695. // Write permissions into the external attributes, for details on this see here: http://unix.stackexchange.com/a/14727
  696. // Get the permissions value from the files attributes
  697. NSNumber *permissionsValue = (NSNumber *)attr[NSFilePosixPermissions];
  698. if (permissionsValue != nil) {
  699. // Get the short value for the permissions
  700. short permissionsShort = permissionsValue.shortValue;
  701. // Convert this into an octal by adding 010000, 010000 being the flag for a regular file
  702. NSInteger permissionsOctal = 0100000 + permissionsShort;
  703. // Convert this into a long value
  704. uLong permissionsLong = @(permissionsOctal).unsignedLongValue;
  705. // Store this into the external file attributes once it has been shifted 16 places left to form part of the second from last byte
  706. // Casted back to an unsigned int to match type of external_fa in minizip
  707. zipInfo.external_fa = (unsigned int)(permissionsLong << 16L);
  708. }
  709. }
  710. unsigned int len = 0;
  711. zipOpenNewFileInZip3(_zip, [folderName stringByAppendingString:@"/"].fileSystemRepresentation, &zipInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_NO_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL,
  712. Z_DEFAULT_STRATEGY, password.UTF8String, 0);
  713. zipWriteInFileInZip(_zip, &len, 0);
  714. zipCloseFileInZip(_zip);
  715. return YES;
  716. }
  717. - (BOOL)writeFile:(NSString *)path withPassword:(nullable NSString *)password;
  718. {
  719. return [self writeFileAtPath:path withFileName:nil withPassword:password];
  720. }
  721. // supports writing files with logical folder/directory structure
  722. // *path* is the absolute path of the file that will be compressed
  723. // *fileName* is the relative name of the file how it is stored within the zip e.g. /folder/subfolder/text1.txt
  724. - (BOOL)writeFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName withPassword:(nullable NSString *)password
  725. {
  726. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  727. FILE *input = fopen(path.fileSystemRepresentation, "r");
  728. if (NULL == input) {
  729. return NO;
  730. }
  731. const char *aFileName;
  732. if (!fileName) {
  733. aFileName = path.lastPathComponent.fileSystemRepresentation;
  734. }
  735. else {
  736. aFileName = fileName.fileSystemRepresentation;
  737. }
  738. zip_fileinfo zipInfo = {0,0,0};
  739. NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error: nil];
  740. if (attr)
  741. {
  742. NSDate *fileDate = (NSDate *)attr[NSFileModificationDate];
  743. if (fileDate)
  744. {
  745. [self zipInfo:&zipInfo setDate: fileDate];
  746. }
  747. // Write permissions into the external attributes, for details on this see here: http://unix.stackexchange.com/a/14727
  748. // Get the permissions value from the files attributes
  749. NSNumber *permissionsValue = (NSNumber *)attr[NSFilePosixPermissions];
  750. if (permissionsValue != nil) {
  751. // Get the short value for the permissions
  752. short permissionsShort = permissionsValue.shortValue;
  753. // Convert this into an octal by adding 010000, 010000 being the flag for a regular file
  754. NSInteger permissionsOctal = 0100000 + permissionsShort;
  755. // Convert this into a long value
  756. uLong permissionsLong = @(permissionsOctal).unsignedLongValue;
  757. // Store this into the external file attributes once it has been shifted 16 places left to form part of the second from last byte
  758. // Casted back to an unsigned int to match type of external_fa in minizip
  759. zipInfo.external_fa = (unsigned int)(permissionsLong << 16L);
  760. }
  761. }
  762. void *buffer = malloc(CHUNK);
  763. if (buffer == NULL)
  764. {
  765. return NO;
  766. }
  767. zipOpenNewFileInZip3(_zip, aFileName, &zipInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password.UTF8String, 0);
  768. unsigned int len = 0;
  769. while (!feof(input) && !ferror(input))
  770. {
  771. len = (unsigned int) fread(buffer, 1, CHUNK, input);
  772. zipWriteInFileInZip(_zip, buffer, len);
  773. }
  774. zipCloseFileInZip(_zip);
  775. free(buffer);
  776. fclose(input);
  777. return YES;
  778. }
  779. - (BOOL)writeData:(NSData *)data filename:(nullable NSString *)filename withPassword:(nullable NSString *)password;
  780. {
  781. if (!_zip) {
  782. return NO;
  783. }
  784. if (!data) {
  785. return NO;
  786. }
  787. zip_fileinfo zipInfo = {0,0,0};
  788. [self zipInfo:&zipInfo setDate:[NSDate date]];
  789. zipOpenNewFileInZip3(_zip, filename.fileSystemRepresentation, &zipInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password.UTF8String, 0);
  790. zipWriteInFileInZip(_zip, data.bytes, (unsigned int)data.length);
  791. zipCloseFileInZip(_zip);
  792. return YES;
  793. }
  794. - (BOOL)close
  795. {
  796. NSAssert((_zip != NULL), @"[SSZipArchive] Attempting to close an archive which was never opened");
  797. int error = zipClose(_zip, NULL);
  798. _zip = nil;
  799. return error == UNZ_OK;
  800. }
  801. #pragma mark - Private
  802. + (NSString *)_temporaryPathForDiscardableFile
  803. {
  804. static NSString *discardableFileName = @".DS_Store";
  805. static NSString *discardableFilePath = nil;
  806. static dispatch_once_t onceToken;
  807. dispatch_once(&onceToken, ^{
  808. NSString *temporaryDirectoryName = [NSUUID UUID].UUIDString;
  809. NSString *temporaryDirectory = [NSTemporaryDirectory() stringByAppendingPathComponent:temporaryDirectoryName];
  810. BOOL directoryCreated = [[NSFileManager defaultManager] createDirectoryAtPath:temporaryDirectory withIntermediateDirectories:YES attributes:nil error:nil];
  811. if (directoryCreated) {
  812. discardableFilePath = [temporaryDirectory stringByAppendingPathComponent:discardableFileName];
  813. [@"" writeToFile:discardableFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
  814. }
  815. });
  816. return discardableFilePath;
  817. }
  818. + (NSCalendar *)_gregorian
  819. {
  820. static NSCalendar *gregorian;
  821. static dispatch_once_t onceToken;
  822. dispatch_once(&onceToken, ^{
  823. gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  824. });
  825. return gregorian;
  826. }
  827. // Format from http://newsgroups.derkeiler.com/Archive/Comp/comp.os.msdos.programmer/2009-04/msg00060.html
  828. // Two consecutive words, or a longword, YYYYYYYMMMMDDDDD hhhhhmmmmmmsssss
  829. // YYYYYYY is years from 1980 = 0
  830. // sssss is (seconds/2).
  831. //
  832. // 3658 = 0011 0110 0101 1000 = 0011011 0010 11000 = 27 2 24 = 2007-02-24
  833. // 7423 = 0111 0100 0010 0011 - 01110 100001 00011 = 14 33 3 = 14:33:06
  834. + (NSDate *)_dateWithMSDOSFormat:(UInt32)msdosDateTime
  835. {
  836. /*
  837. // the whole `_dateWithMSDOSFormat:` method is equivalent but faster than this one line,
  838. // essentially because `mktime` is slow:
  839. NSDate *date = [NSDate dateWithTimeIntervalSince1970:dosdate_to_time_t(msdosDateTime)];
  840. */
  841. static const UInt32 kYearMask = 0xFE000000;
  842. static const UInt32 kMonthMask = 0x1E00000;
  843. static const UInt32 kDayMask = 0x1F0000;
  844. static const UInt32 kHourMask = 0xF800;
  845. static const UInt32 kMinuteMask = 0x7E0;
  846. static const UInt32 kSecondMask = 0x1F;
  847. NSAssert(0xFFFFFFFF == (kYearMask | kMonthMask | kDayMask | kHourMask | kMinuteMask | kSecondMask), @"[SSZipArchive] MSDOS date masks don't add up");
  848. NSDateComponents *components = [[NSDateComponents alloc] init];
  849. components.year = 1980 + ((msdosDateTime & kYearMask) >> 25);
  850. components.month = (msdosDateTime & kMonthMask) >> 21;
  851. components.day = (msdosDateTime & kDayMask) >> 16;
  852. components.hour = (msdosDateTime & kHourMask) >> 11;
  853. components.minute = (msdosDateTime & kMinuteMask) >> 5;
  854. components.second = (msdosDateTime & kSecondMask) * 2;
  855. NSDate *date = [self._gregorian dateFromComponents:components];
  856. return date;
  857. }
  858. @end
  859. #pragma mark - Private tools for unreadable data
  860. @implementation NSData (SSZipArchive)
  861. // `base64EncodedStringWithOptions` uses a base64 alphabet with '+' and '/'.
  862. // we got those alternatives to make it compatible with filenames: https://en.wikipedia.org/wiki/Base64
  863. // * modified Base64 encoding for IMAP mailbox names (RFC 3501): uses '+' and ','
  864. // * modified Base64 for URL and filenames (RFC 4648): uses '-' and '_'
  865. - (NSString *)_base64RFC4648
  866. {
  867. NSString *strName = [self base64EncodedStringWithOptions:0];
  868. strName = [strName stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
  869. strName = [strName stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
  870. return strName;
  871. }
  872. // initWithBytesNoCopy from NSProgrammer, Jan 25 '12: https://stackoverflow.com/a/9009321/1033581
  873. // hexChars from Peter, Aug 19 '14: https://stackoverflow.com/a/25378464/1033581
  874. // not implemented as too lengthy: a potential mapping improvement from Moose, Nov 3 '15: https://stackoverflow.com/a/33501154/1033581
  875. - (NSString *)_hexString
  876. {
  877. const char *hexChars = "0123456789ABCDEF";
  878. NSUInteger length = self.length;
  879. const unsigned char *bytes = self.bytes;
  880. char *chars = malloc(length * 2);
  881. char *s = chars;
  882. NSUInteger i = length;
  883. while (i--) {
  884. *s++ = hexChars[*bytes >> 4];
  885. *s++ = hexChars[*bytes & 0xF];
  886. bytes++;
  887. }
  888. NSString *str = [[NSString alloc] initWithBytesNoCopy:chars
  889. length:length * 2
  890. encoding:NSASCIIStringEncoding
  891. freeWhenDone:YES];
  892. return str;
  893. }
  894. @end