SSZipArchive.m 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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 "minizip/mz_compat.h"
  10. #include "minizip/mz_zip.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. {
  682. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  683. BOOL success = [zipArchive open];
  684. if (success) {
  685. for (NSString *filePath in paths) {
  686. success &= [zipArchive writeFile:filePath withPassword:password];
  687. }
  688. success &= [zipArchive close];
  689. }
  690. return success;
  691. }
  692. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath withPassword:(nullable NSString *)password {
  693. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:NO withPassword:password];
  694. }
  695. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory withPassword:(nullable NSString *)password {
  696. return [SSZipArchive createZipFileAtPath:path
  697. withContentsOfDirectory:directoryPath
  698. keepParentDirectory:keepParentDirectory
  699. withPassword:password
  700. andProgressHandler:nil
  701. ];
  702. }
  703. + (BOOL)createZipFileAtPath:(NSString *)path
  704. withContentsOfDirectory:(NSString *)directoryPath
  705. keepParentDirectory:(BOOL)keepParentDirectory
  706. withPassword:(nullable NSString *)password
  707. andProgressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler {
  708. return [self createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:keepParentDirectory compressionLevel:Z_DEFAULT_COMPRESSION password:password AES:YES progressHandler:progressHandler];
  709. }
  710. + (BOOL)createZipFileAtPath:(NSString *)path
  711. withContentsOfDirectory:(NSString *)directoryPath
  712. keepParentDirectory:(BOOL)keepParentDirectory
  713. compressionLevel:(int)compressionLevel
  714. password:(nullable NSString *)password
  715. AES:(BOOL)aes
  716. progressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler {
  717. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  718. BOOL success = [zipArchive open];
  719. if (success) {
  720. // use a local fileManager (queue/thread compatibility)
  721. NSFileManager *fileManager = [[NSFileManager alloc] init];
  722. NSDirectoryEnumerator *dirEnumerator = [fileManager enumeratorAtPath:directoryPath];
  723. NSArray<NSString *> *allObjects = dirEnumerator.allObjects;
  724. NSUInteger total = allObjects.count, complete = 0;
  725. if (keepParentDirectory && !total) {
  726. allObjects = @[@""];
  727. total = 1;
  728. }
  729. for (__strong NSString *fileName in allObjects) {
  730. NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:fileName];
  731. if ([fullFilePath isEqualToString:path]) {
  732. NSLog(@"[SSZipArchive] the archive path and the file path: %@ are the same, which is forbidden.", fullFilePath);
  733. continue;
  734. }
  735. if (keepParentDirectory) {
  736. fileName = [directoryPath.lastPathComponent stringByAppendingPathComponent:fileName];
  737. }
  738. BOOL isDir;
  739. [fileManager fileExistsAtPath:fullFilePath isDirectory:&isDir];
  740. if (!isDir) {
  741. // file
  742. success &= [zipArchive writeFileAtPath:fullFilePath withFileName:fileName compressionLevel:compressionLevel password:password AES:aes];
  743. } else {
  744. // directory
  745. if (![fileManager enumeratorAtPath:fullFilePath].nextObject) {
  746. // empty directory
  747. success &= [zipArchive writeFolderAtPath:fullFilePath withFolderName:fileName withPassword:password];
  748. }
  749. }
  750. if (progressHandler) {
  751. complete++;
  752. progressHandler(complete, total);
  753. }
  754. }
  755. success &= [zipArchive close];
  756. }
  757. return success;
  758. }
  759. // disabling `init` because designated initializer is `initWithPath:`
  760. - (instancetype)init { @throw nil; }
  761. // designated initializer
  762. - (instancetype)initWithPath:(NSString *)path
  763. {
  764. if ((self = [super init])) {
  765. _path = [path copy];
  766. }
  767. return self;
  768. }
  769. - (BOOL)open
  770. {
  771. NSAssert((_zip == NULL), @"Attempting to open an archive which is already open");
  772. _zip = zipOpen(_path.fileSystemRepresentation, APPEND_STATUS_CREATE);
  773. return (NULL != _zip);
  774. }
  775. - (BOOL)writeFolderAtPath:(NSString *)path withFolderName:(NSString *)folderName withPassword:(nullable NSString *)password
  776. {
  777. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  778. zip_fileinfo zipInfo = {};
  779. [SSZipArchive zipInfo:&zipInfo setAttributesOfItemAtPath:path];
  780. int error = _zipOpenEntry(_zip, [folderName stringByAppendingString:@"/"], &zipInfo, Z_NO_COMPRESSION, password, NO);
  781. const void *buffer = NULL;
  782. zipWriteInFileInZip(_zip, buffer, 0);
  783. zipCloseFileInZip(_zip);
  784. return error == ZIP_OK;
  785. }
  786. - (BOOL)writeFile:(NSString *)path withPassword:(nullable NSString *)password
  787. {
  788. return [self writeFileAtPath:path withFileName:nil withPassword:password];
  789. }
  790. - (BOOL)writeFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName withPassword:(nullable NSString *)password
  791. {
  792. return [self writeFileAtPath:path withFileName:fileName compressionLevel:Z_DEFAULT_COMPRESSION password:password AES:YES];
  793. }
  794. // supports writing files with logical folder/directory structure
  795. // *path* is the absolute path of the file that will be compressed
  796. // *fileName* is the relative name of the file how it is stored within the zip e.g. /folder/subfolder/text1.txt
  797. - (BOOL)writeFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName compressionLevel:(int)compressionLevel password:(nullable NSString *)password AES:(BOOL)aes
  798. {
  799. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  800. FILE *input = fopen(path.fileSystemRepresentation, "r");
  801. if (NULL == input) {
  802. return NO;
  803. }
  804. if (!fileName) {
  805. fileName = path.lastPathComponent;
  806. }
  807. zip_fileinfo zipInfo = {};
  808. [SSZipArchive zipInfo:&zipInfo setAttributesOfItemAtPath:path];
  809. void *buffer = malloc(CHUNK);
  810. if (buffer == NULL)
  811. {
  812. fclose(input);
  813. return NO;
  814. }
  815. int error = _zipOpenEntry(_zip, fileName, &zipInfo, compressionLevel, password, aes);
  816. while (!feof(input) && !ferror(input))
  817. {
  818. unsigned int len = (unsigned int) fread(buffer, 1, CHUNK, input);
  819. zipWriteInFileInZip(_zip, buffer, len);
  820. }
  821. zipCloseFileInZip(_zip);
  822. free(buffer);
  823. fclose(input);
  824. return error == ZIP_OK;
  825. }
  826. - (BOOL)writeData:(NSData *)data filename:(nullable NSString *)filename withPassword:(nullable NSString *)password
  827. {
  828. return [self writeData:data filename:filename compressionLevel:Z_DEFAULT_COMPRESSION password:password AES:YES];
  829. }
  830. - (BOOL)writeData:(NSData *)data filename:(nullable NSString *)filename compressionLevel:(int)compressionLevel password:(nullable NSString *)password AES:(BOOL)aes
  831. {
  832. if (!_zip) {
  833. return NO;
  834. }
  835. if (!data) {
  836. return NO;
  837. }
  838. zip_fileinfo zipInfo = {};
  839. [SSZipArchive zipInfo:&zipInfo setDate:[NSDate date]];
  840. int error = _zipOpenEntry(_zip, filename, &zipInfo, compressionLevel, password, aes);
  841. zipWriteInFileInZip(_zip, data.bytes, (unsigned int)data.length);
  842. zipCloseFileInZip(_zip);
  843. return error == ZIP_OK;
  844. }
  845. - (BOOL)close
  846. {
  847. NSAssert((_zip != NULL), @"[SSZipArchive] Attempting to close an archive which was never opened");
  848. int error = zipClose(_zip, NULL);
  849. _zip = nil;
  850. return error == ZIP_OK;
  851. }
  852. #pragma mark - Private
  853. + (NSString *)_filenameStringWithCString:(const char *)filename
  854. version_made_by:(uint16_t)version_made_by
  855. general_purpose_flag:(uint16_t)flag
  856. size:(uint16_t)size_filename {
  857. // Respect Language encoding flag only reading filename as UTF-8 when this is set
  858. // when file entry created on dos system.
  859. //
  860. // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
  861. // Bit 11: Language encoding flag (EFS). If this bit is set,
  862. // the filename and comment fields for this file
  863. // MUST be encoded using UTF-8. (see APPENDIX D)
  864. uint16_t made_by = version_made_by >> 8;
  865. BOOL made_on_dos = made_by == 0;
  866. BOOL languageEncoding = (flag & (1 << 11)) != 0;
  867. if (!languageEncoding && made_on_dos) {
  868. // APPNOTE.TXT D.1:
  869. // D.2 If general purpose bit 11 is unset, the file name and comment should conform
  870. // to the original ZIP character encoding. If general purpose bit 11 is set, the
  871. // filename and comment must support The Unicode Standard, Version 4.1.0 or
  872. // greater using the character encoding form defined by the UTF-8 storage
  873. // specification. The Unicode Standard is published by the The Unicode
  874. // Consortium (www.unicode.org). UTF-8 encoded data stored within ZIP files
  875. // is expected to not include a byte order mark (BOM).
  876. // Code Page 437 corresponds to kCFStringEncodingDOSLatinUS
  877. NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingDOSLatinUS);
  878. NSString* strPath = [NSString stringWithCString:filename encoding:encoding];
  879. if (strPath) {
  880. return strPath;
  881. }
  882. }
  883. // attempting unicode encoding
  884. NSString * strPath = @(filename);
  885. if (strPath) {
  886. return strPath;
  887. }
  888. // if filename is non-unicode, detect and transform Encoding
  889. NSData *data = [NSData dataWithBytes:(const void *)filename length:sizeof(unsigned char) * size_filename];
  890. // Testing availability of @available (https://stackoverflow.com/a/46927445/1033581)
  891. #if __clang_major__ < 9
  892. // Xcode 8-
  893. if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber10_9_2) {
  894. #else
  895. // Xcode 9+
  896. if (@available(macOS 10.10, iOS 8.0, watchOS 2.0, tvOS 9.0, *)) {
  897. #endif
  898. // supported encodings are in [NSString availableStringEncodings]
  899. [NSString stringEncodingForData:data encodingOptions:nil convertedString:&strPath usedLossyConversion:nil];
  900. } else {
  901. // fallback to a simple manual detect for macOS 10.9 or older
  902. NSArray<NSNumber *> *encodings = @[@(kCFStringEncodingGB_18030_2000), @(kCFStringEncodingShiftJIS)];
  903. for (NSNumber *encoding in encodings) {
  904. strPath = [NSString stringWithCString:filename encoding:(NSStringEncoding)CFStringConvertEncodingToNSStringEncoding(encoding.unsignedIntValue)];
  905. if (strPath) {
  906. break;
  907. }
  908. }
  909. }
  910. if (strPath) {
  911. return strPath;
  912. }
  913. // if filename encoding is non-detected, we default to something based on data
  914. // _hexString is more readable than _base64RFC4648 for debugging unknown encodings
  915. strPath = [data _hexString];
  916. return strPath;
  917. }
  918. + (void)zipInfo:(zip_fileinfo *)zipInfo setAttributesOfItemAtPath:(NSString *)path
  919. {
  920. NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error: nil];
  921. if (attr)
  922. {
  923. NSDate *fileDate = (NSDate *)[attr objectForKey:NSFileModificationDate];
  924. if (fileDate)
  925. {
  926. [self zipInfo:zipInfo setDate:fileDate];
  927. }
  928. // Write permissions into the external attributes, for details on this see here: https://unix.stackexchange.com/a/14727
  929. // Get the permissions value from the files attributes
  930. NSNumber *permissionsValue = (NSNumber *)[attr objectForKey:NSFilePosixPermissions];
  931. if (permissionsValue != nil) {
  932. // Get the short value for the permissions
  933. short permissionsShort = permissionsValue.shortValue;
  934. // Convert this into an octal by adding 010000, 010000 being the flag for a regular file
  935. NSInteger permissionsOctal = 0100000 + permissionsShort;
  936. // Convert this into a long value
  937. uLong permissionsLong = @(permissionsOctal).unsignedLongValue;
  938. // Store this into the external file attributes once it has been shifted 16 places left to form part of the second from last byte
  939. // Casted back to an unsigned int to match type of external_fa in minizip
  940. zipInfo->external_fa = (unsigned int)(permissionsLong << 16L);
  941. }
  942. }
  943. }
  944. + (void)zipInfo:(zip_fileinfo *)zipInfo setDate:(NSDate *)date
  945. {
  946. NSCalendar *currentCalendar = SSZipArchive._gregorian;
  947. NSCalendarUnit flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  948. NSDateComponents *components = [currentCalendar components:flags fromDate:date];
  949. struct tm tmz_date;
  950. tmz_date.tm_sec = (unsigned int)components.second;
  951. tmz_date.tm_min = (unsigned int)components.minute;
  952. tmz_date.tm_hour = (unsigned int)components.hour;
  953. tmz_date.tm_mday = (unsigned int)components.day;
  954. // ISO/IEC 9899 struct tm is 0-indexed for January but NSDateComponents for gregorianCalendar is 1-indexed for January
  955. tmz_date.tm_mon = (unsigned int)components.month - 1;
  956. // ISO/IEC 9899 struct tm is 0-indexed for AD 1900 but NSDateComponents for gregorianCalendar is 1-indexed for AD 1
  957. tmz_date.tm_year = (unsigned int)components.year - 1900;
  958. zipInfo->mz_dos_date = mz_zip_tm_to_dosdate(&tmz_date);
  959. }
  960. + (NSCalendar *)_gregorian
  961. {
  962. static NSCalendar *gregorian;
  963. static dispatch_once_t onceToken;
  964. dispatch_once(&onceToken, ^{
  965. gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  966. });
  967. return gregorian;
  968. }
  969. // Format from http://newsgroups.derkeiler.com/Archive/Comp/comp.os.msdos.programmer/2009-04/msg00060.html
  970. // Two consecutive words, or a longword, YYYYYYYMMMMDDDDD hhhhhmmmmmmsssss
  971. // YYYYYYY is years from 1980 = 0
  972. // sssss is (seconds/2).
  973. //
  974. // 3658 = 0011 0110 0101 1000 = 0011011 0010 11000 = 27 2 24 = 2007-02-24
  975. // 7423 = 0111 0100 0010 0011 - 01110 100001 00011 = 14 33 3 = 14:33:06
  976. + (NSDate *)_dateWithMSDOSFormat:(UInt32)msdosDateTime
  977. {
  978. // the whole `_dateWithMSDOSFormat:` method is equivalent but faster than this one line,
  979. // essentially because `mktime` is slow:
  980. //NSDate *date = [NSDate dateWithTimeIntervalSince1970:dosdate_to_time_t(msdosDateTime)];
  981. static const UInt32 kYearMask = 0xFE000000;
  982. static const UInt32 kMonthMask = 0x1E00000;
  983. static const UInt32 kDayMask = 0x1F0000;
  984. static const UInt32 kHourMask = 0xF800;
  985. static const UInt32 kMinuteMask = 0x7E0;
  986. static const UInt32 kSecondMask = 0x1F;
  987. NSAssert(0xFFFFFFFF == (kYearMask | kMonthMask | kDayMask | kHourMask | kMinuteMask | kSecondMask), @"[SSZipArchive] MSDOS date masks don't add up");
  988. NSDateComponents *components = [[NSDateComponents alloc] init];
  989. components.year = 1980 + ((msdosDateTime & kYearMask) >> 25);
  990. components.month = (msdosDateTime & kMonthMask) >> 21;
  991. components.day = (msdosDateTime & kDayMask) >> 16;
  992. components.hour = (msdosDateTime & kHourMask) >> 11;
  993. components.minute = (msdosDateTime & kMinuteMask) >> 5;
  994. components.second = (msdosDateTime & kSecondMask) * 2;
  995. NSDate *date = [self._gregorian dateFromComponents:components];
  996. return date;
  997. }
  998. @end
  999. int _zipOpenEntry(zipFile entry, NSString *name, const zip_fileinfo *zipfi, int level, NSString *password, BOOL aes)
  1000. {
  1001. // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
  1002. uint16_t made_on_darwin = 19 << 8;
  1003. //MZ_ZIP_FLAG_UTF8
  1004. uint16_t flag_base = 1 << 11;
  1005. 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);
  1006. }
  1007. #pragma mark - Private tools for file info
  1008. BOOL _fileIsSymbolicLink(const unz_file_info *fileInfo)
  1009. {
  1010. //
  1011. // Determine whether this is a symbolic link:
  1012. // - File is stored with 'version made by' value of UNIX (3),
  1013. // as per https://www.pkware.com/documents/casestudies/APPNOTE.TXT
  1014. // in the upper byte of the version field.
  1015. // - BSD4.4 st_mode constants are stored in the high 16 bits of the
  1016. // external file attributes (defacto standard, verified against libarchive)
  1017. //
  1018. // The original constants can be found here:
  1019. // https://minnie.tuhs.org/cgi-bin/utree.pl?file=4.4BSD/usr/include/sys/stat.h
  1020. //
  1021. const uLong ZipUNIXVersion = 3;
  1022. const uLong BSD_SFMT = 0170000;
  1023. const uLong BSD_IFLNK = 0120000;
  1024. BOOL fileIsSymbolicLink = ((fileInfo->version >> 8) == ZipUNIXVersion) && BSD_IFLNK == (BSD_SFMT & (fileInfo->external_fa >> 16));
  1025. return fileIsSymbolicLink;
  1026. }
  1027. #pragma mark - Private tools for unreadable encodings
  1028. @implementation NSData (SSZipArchive)
  1029. // `base64EncodedStringWithOptions` uses a base64 alphabet with '+' and '/'.
  1030. // we got those alternatives to make it compatible with filenames: https://en.wikipedia.org/wiki/Base64
  1031. // * modified Base64 encoding for IMAP mailbox names (RFC 3501): uses '+' and ','
  1032. // * modified Base64 for URL and filenames (RFC 4648): uses '-' and '_'
  1033. - (NSString *)_base64RFC4648
  1034. {
  1035. NSString *strName = [self base64EncodedStringWithOptions:0];
  1036. strName = [strName stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
  1037. strName = [strName stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
  1038. return strName;
  1039. }
  1040. // initWithBytesNoCopy from NSProgrammer, Jan 25 '12: https://stackoverflow.com/a/9009321/1033581
  1041. // hexChars from Peter, Aug 19 '14: https://stackoverflow.com/a/25378464/1033581
  1042. // not implemented as too lengthy: a potential mapping improvement from Moose, Nov 3 '15: https://stackoverflow.com/a/33501154/1033581
  1043. - (NSString *)_hexString
  1044. {
  1045. const char *hexChars = "0123456789ABCDEF";
  1046. NSUInteger length = self.length;
  1047. const unsigned char *bytes = self.bytes;
  1048. char *chars = malloc(length * 2);
  1049. if (chars == NULL) {
  1050. // we directly raise an exception instead of using NSAssert to make sure assertion is not disabled as this is irrecoverable
  1051. [NSException raise:@"NSInternalInconsistencyException" format:@"failed malloc" arguments:nil];
  1052. return nil;
  1053. }
  1054. char *s = chars;
  1055. NSUInteger i = length;
  1056. while (i--) {
  1057. *s++ = hexChars[*bytes >> 4];
  1058. *s++ = hexChars[*bytes & 0xF];
  1059. bytes++;
  1060. }
  1061. NSString *str = [[NSString alloc] initWithBytesNoCopy:chars
  1062. length:length * 2
  1063. encoding:NSASCIIStringEncoding
  1064. freeWhenDone:YES];
  1065. return str;
  1066. }
  1067. @end
  1068. #pragma mark Private tools for security
  1069. @implementation NSString (SSZipArchive)
  1070. // 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,
  1071. // but making sure to work with unichar values and not ascii values to avoid breaking Unicode characters containing 2E ('.') or 2F ('/') in their decomposition
  1072. /// Sanitize path traversal characters to prevent directory backtracking. Ignoring these characters mimicks the default behavior of the Unarchiving tool on macOS.
  1073. - (NSString *)_sanitizedPath
  1074. {
  1075. // Change Windows paths to Unix paths: https://en.wikipedia.org/wiki/Path_(computing)
  1076. // Possible improvement: only do this if the archive was created on a non-Unix system
  1077. NSString *strPath = [self stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
  1078. // Percent-encode file path (where path is defined by https://tools.ietf.org/html/rfc8089)
  1079. // The key part is to allow characters "." and "/" and disallow "%".
  1080. // CharacterSet.urlPathAllowed seems to do the job
  1081. #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)
  1082. strPath = [strPath stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
  1083. #else
  1084. // Testing availability of @available (https://stackoverflow.com/a/46927445/1033581)
  1085. #if __clang_major__ < 9
  1086. // Xcode 8-
  1087. if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber10_8_4) {
  1088. #else
  1089. // Xcode 9+
  1090. if (@available(macOS 10.9, iOS 7.0, watchOS 2.0, tvOS 9.0, *)) {
  1091. #endif
  1092. strPath = [strPath stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
  1093. } else {
  1094. strPath = [strPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  1095. }
  1096. #endif
  1097. // `NSString.stringByAddingPercentEncodingWithAllowedCharacters:` may theorically fail: https://stackoverflow.com/questions/33558933/
  1098. // But because we auto-detect encoding using `NSString.stringEncodingForData:encodingOptions:convertedString:usedLossyConversion:`,
  1099. // we likely already prevent UTF-16, UTF-32 and invalid Unicode in the form of unpaired surrogate chars: https://stackoverflow.com/questions/53043876/
  1100. // To be on the safe side, we will still perform a guard check.
  1101. if (strPath == nil) {
  1102. return nil;
  1103. }
  1104. // Add scheme "file:///" to support sanitation on names with a colon like "file:a/../../../usr/bin"
  1105. strPath = [@"file:///" stringByAppendingString:strPath];
  1106. // Sanitize path traversal characters to prevent directory backtracking. Ignoring these characters mimicks the default behavior of the Unarchiving tool on macOS.
  1107. // "../../../../../../../../../../../tmp/test.txt" -> "tmp/test.txt"
  1108. // "a/b/../c.txt" -> "a/c.txt"
  1109. strPath = [NSURL URLWithString:strPath].standardizedURL.absoluteString;
  1110. // Remove the "file:///" scheme
  1111. strPath = [strPath substringFromIndex:8];
  1112. // Remove the percent-encoding
  1113. #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)
  1114. strPath = strPath.stringByRemovingPercentEncoding;
  1115. #else
  1116. // Testing availability of @available (https://stackoverflow.com/a/46927445/1033581)
  1117. #if __clang_major__ < 9
  1118. // Xcode 8-
  1119. if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber10_8_4) {
  1120. #else
  1121. // Xcode 9+
  1122. if (@available(macOS 10.9, iOS 7.0, watchOS 2.0, tvOS 9.0, *)) {
  1123. #endif
  1124. strPath = strPath.stringByRemovingPercentEncoding;
  1125. } else {
  1126. strPath = [strPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  1127. }
  1128. #endif
  1129. return strPath;
  1130. }
  1131. @end