暂无描述

SSZipArchive.m 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. #import "zlib.h"
  12. #import "zconf.h"
  13. #include <sys/stat.h>
  14. #define CHUNK 16384
  15. @interface SSZipArchive ()
  16. + (NSDate *)_dateWithMSDOSFormat:(UInt32)msdosDateTime;
  17. @end
  18. @implementation SSZipArchive
  19. {
  20. NSString *_path;
  21. NSString *_filename;
  22. zipFile _zip;
  23. }
  24. #pragma mark - Unzipping
  25. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination
  26. {
  27. return [self unzipFileAtPath:path toDestination:destination delegate:nil];
  28. }
  29. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(NSString *)password error:(NSError **)error
  30. {
  31. return [self unzipFileAtPath:path toDestination:destination overwrite:overwrite password:password error:error delegate:nil progressHandler:nil completionHandler:nil];
  32. }
  33. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination delegate:(id<SSZipArchiveDelegate>)delegate
  34. {
  35. return [self unzipFileAtPath:path toDestination:destination overwrite:YES password:nil error:nil delegate:delegate progressHandler:nil completionHandler:nil];
  36. }
  37. + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(NSString *)password error:(NSError **)error delegate:(id<SSZipArchiveDelegate>)delegate
  38. {
  39. return [self unzipFileAtPath:path toDestination:destination overwrite:overwrite password:password error:error delegate:delegate progressHandler:nil completionHandler:nil];
  40. }
  41. + (BOOL)unzipFileAtPath:(NSString *)path
  42. toDestination:(NSString *)destination
  43. overwrite:(BOOL)overwrite
  44. password:(NSString *)password
  45. progressHandler:(void (^)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  46. completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError *error))completionHandler
  47. {
  48. return [self unzipFileAtPath:path toDestination:destination overwrite:overwrite password:password error:nil delegate:nil progressHandler:progressHandler completionHandler:completionHandler];
  49. }
  50. + (BOOL)unzipFileAtPath:(NSString *)path
  51. toDestination:(NSString *)destination
  52. progressHandler:(void (^)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  53. completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError *error))completionHandler
  54. {
  55. return [self unzipFileAtPath:path toDestination:destination overwrite:YES password:nil error:nil delegate:nil progressHandler:progressHandler completionHandler:completionHandler];
  56. }
  57. + (BOOL)unzipFileAtPath:(NSString *)path
  58. toDestination:(NSString *)destination
  59. overwrite:(BOOL)overwrite
  60. password:(NSString *)password
  61. error:(NSError **)error
  62. delegate:(id<SSZipArchiveDelegate>)delegate
  63. progressHandler:(void (^)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
  64. completionHandler:(void (^)(NSString *path, BOOL succeeded, NSError *error))completionHandler
  65. {
  66. // Begin opening
  67. zipFile zip = unzOpen((const char*)[path UTF8String]);
  68. if (zip == NULL)
  69. {
  70. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"failed to open zip file"};
  71. NSError *err = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:-1 userInfo:userInfo];
  72. if (error)
  73. {
  74. *error = err;
  75. }
  76. if (completionHandler)
  77. {
  78. completionHandler(nil, NO, err);
  79. }
  80. return NO;
  81. }
  82. NSDictionary * fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
  83. unsigned long long fileSize = [fileAttributes[NSFileSize] unsignedLongLongValue];
  84. unsigned long long currentPosition = 0;
  85. unz_global_info globalInfo = {0ul, 0ul};
  86. unzGetGlobalInfo(zip, &globalInfo);
  87. // Begin unzipping
  88. if (unzGoToFirstFile(zip) != UNZ_OK)
  89. {
  90. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"failed to open first file in zip file"};
  91. NSError *err = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:-2 userInfo:userInfo];
  92. if (error)
  93. {
  94. *error = err;
  95. }
  96. if (completionHandler)
  97. {
  98. completionHandler(nil, NO, err);
  99. }
  100. return NO;
  101. }
  102. BOOL success = YES;
  103. BOOL canceled = NO;
  104. int ret = 0;
  105. int crc_ret =0;
  106. unsigned char buffer[4096] = {0};
  107. NSFileManager *fileManager = [NSFileManager defaultManager];
  108. NSMutableSet *directoriesModificationDates = [[NSMutableSet alloc] init];
  109. // Message delegate
  110. if ([delegate respondsToSelector:@selector(zipArchiveWillUnzipArchiveAtPath:zipInfo:)]) {
  111. [delegate zipArchiveWillUnzipArchiveAtPath:path zipInfo:globalInfo];
  112. }
  113. if ([delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  114. [delegate zipArchiveProgressEvent:(NSInteger)currentPosition total:(NSInteger)fileSize];
  115. }
  116. NSInteger currentFileNumber = 0;
  117. do {
  118. @autoreleasepool {
  119. if ([password length] == 0) {
  120. ret = unzOpenCurrentFile(zip);
  121. } else {
  122. ret = unzOpenCurrentFilePassword(zip, [password cStringUsingEncoding:NSASCIIStringEncoding]);
  123. }
  124. if (ret != UNZ_OK) {
  125. success = NO;
  126. break;
  127. }
  128. // Reading data and write to file
  129. unz_file_info fileInfo;
  130. memset(&fileInfo, 0, sizeof(unz_file_info));
  131. ret = unzGetCurrentFileInfo(zip, &fileInfo, NULL, 0, NULL, 0, NULL, 0);
  132. if (ret != UNZ_OK) {
  133. success = NO;
  134. unzCloseCurrentFile(zip);
  135. break;
  136. }
  137. currentPosition += fileInfo.compressed_size;
  138. // Message delegate
  139. if ([delegate respondsToSelector:@selector(zipArchiveShouldUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  140. if (![delegate zipArchiveShouldUnzipFileAtIndex:currentFileNumber
  141. totalFiles:(NSInteger)globalInfo.number_entry
  142. archivePath:path fileInfo:fileInfo]) {
  143. success = NO;
  144. canceled = YES;
  145. break;
  146. }
  147. }
  148. if ([delegate respondsToSelector:@selector(zipArchiveWillUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  149. [delegate zipArchiveWillUnzipFileAtIndex:currentFileNumber totalFiles:(NSInteger)globalInfo.number_entry
  150. archivePath:path fileInfo:fileInfo];
  151. }
  152. if ([delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  153. [delegate zipArchiveProgressEvent:(NSInteger)currentPosition total:(NSInteger)fileSize];
  154. }
  155. char *filename = (char *)malloc(fileInfo.size_filename + 1);
  156. if (filename == NULL)
  157. {
  158. return NO;
  159. }
  160. unzGetCurrentFileInfo(zip, &fileInfo, filename, fileInfo.size_filename + 1, NULL, 0, NULL, 0);
  161. filename[fileInfo.size_filename] = '\0';
  162. //
  163. // Determine whether this is a symbolic link:
  164. // - File is stored with 'version made by' value of UNIX (3),
  165. // as per http://www.pkware.com/documents/casestudies/APPNOTE.TXT
  166. // in the upper byte of the version field.
  167. // - BSD4.4 st_mode constants are stored in the high 16 bits of the
  168. // external file attributes (defacto standard, verified against libarchive)
  169. //
  170. // The original constants can be found here:
  171. // http://minnie.tuhs.org/cgi-bin/utree.pl?file=4.4BSD/usr/include/sys/stat.h
  172. //
  173. const uLong ZipUNIXVersion = 3;
  174. const uLong BSD_SFMT = 0170000;
  175. const uLong BSD_IFLNK = 0120000;
  176. BOOL fileIsSymbolicLink = NO;
  177. if (((fileInfo.version >> 8) == ZipUNIXVersion) && BSD_IFLNK == (BSD_SFMT & (fileInfo.external_fa >> 16))) {
  178. fileIsSymbolicLink = NO;
  179. }
  180. // Check if it contains directory
  181. NSString *strPath = @(filename);
  182. BOOL isDirectory = NO;
  183. if (filename[fileInfo.size_filename-1] == '/' || filename[fileInfo.size_filename-1] == '\\') {
  184. isDirectory = YES;
  185. }
  186. free(filename);
  187. // Contains a path
  188. if ([strPath rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"/\\"]].location != NSNotFound) {
  189. strPath = [strPath stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
  190. }
  191. NSString *fullPath = [destination stringByAppendingPathComponent:strPath];
  192. NSError *err = nil;
  193. NSDate *modDate = [[self class] _dateWithMSDOSFormat:(UInt32)fileInfo.dosDate];
  194. NSDictionary *directoryAttr = @{NSFileCreationDate: modDate, NSFileModificationDate: modDate};
  195. if (isDirectory) {
  196. [fileManager createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:directoryAttr error:&err];
  197. } else {
  198. [fileManager createDirectoryAtPath:[fullPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:directoryAttr error:&err];
  199. }
  200. if (nil != err) {
  201. NSLog(@"[SSZipArchive] Error: %@", err.localizedDescription);
  202. }
  203. if(!fileIsSymbolicLink)
  204. [directoriesModificationDates addObject: @{@"path": fullPath, @"modDate": modDate}];
  205. if ([fileManager fileExistsAtPath:fullPath] && !isDirectory && !overwrite) {
  206. //FIXME: couldBe CRC Check?
  207. unzCloseCurrentFile(zip);
  208. ret = unzGoToNextFile(zip);
  209. continue;
  210. }
  211. if (!fileIsSymbolicLink) {
  212. FILE *fp = fopen((const char*)[fullPath UTF8String], "wb");
  213. while (fp) {
  214. int readBytes = unzReadCurrentFile(zip, buffer, 4096);
  215. if (readBytes > 0) {
  216. fwrite(buffer, readBytes, 1, fp );
  217. } else {
  218. break;
  219. }
  220. }
  221. if (fp) {
  222. if ([[[fullPath pathExtension] lowercaseString] isEqualToString:@"zip"]) {
  223. NSLog(@"Unzipping nested .zip file: %@", [fullPath lastPathComponent]);
  224. if ([self unzipFileAtPath:fullPath toDestination:[fullPath stringByDeletingLastPathComponent] overwrite:overwrite password:password error:nil delegate:nil]) {
  225. [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
  226. }
  227. }
  228. fclose(fp);
  229. // Set the original datetime property
  230. if (fileInfo.dosDate != 0) {
  231. NSDate *orgDate = [[self class] _dateWithMSDOSFormat:(UInt32)fileInfo.dosDate];
  232. NSDictionary *attr = @{NSFileModificationDate: orgDate};
  233. if (attr) {
  234. if ([fileManager setAttributes:attr ofItemAtPath:fullPath error:nil] == NO) {
  235. // Can't set attributes
  236. NSLog(@"[SSZipArchive] Failed to set attributes - whilst setting modification date");
  237. }
  238. }
  239. }
  240. // Set the original permissions on the file
  241. uLong permissions = fileInfo.external_fa >> 16;
  242. if (permissions != 0) {
  243. // Store it into a NSNumber
  244. NSNumber *permissionsValue = @(permissions);
  245. // Retrieve any existing attributes
  246. NSMutableDictionary *attrs = [[NSMutableDictionary alloc] initWithDictionary:[fileManager attributesOfItemAtPath:fullPath error:nil]];
  247. // Set the value in the attributes dict
  248. attrs[NSFilePosixPermissions] = permissionsValue;
  249. // Update attributes
  250. if ([fileManager setAttributes:attrs ofItemAtPath:fullPath error:nil] == NO) {
  251. // Unable to set the permissions attribute
  252. NSLog(@"[SSZipArchive] Failed to set attributes - whilst setting permissions");
  253. }
  254. #if !__has_feature(objc_arc)
  255. [attrs release];
  256. #endif
  257. }
  258. }
  259. }
  260. else
  261. {
  262. // Assemble the path for the symbolic link
  263. NSMutableString* destinationPath = [NSMutableString string];
  264. int bytesRead = 0;
  265. while((bytesRead = unzReadCurrentFile(zip, buffer, 4096)) > 0)
  266. {
  267. buffer[bytesRead] = (int)0;
  268. [destinationPath appendString:@((const char*)buffer)];
  269. }
  270. // Create the symbolic link (making sure it stays relative if it was relative before)
  271. int symlinkError = symlink([destinationPath cStringUsingEncoding:NSUTF8StringEncoding],
  272. [fullPath cStringUsingEncoding:NSUTF8StringEncoding]);
  273. if(symlinkError != 0)
  274. {
  275. NSLog(@"Failed to create symbolic link at \"%@\" to \"%@\". symlink() error code: %d", fullPath, destinationPath, errno);
  276. }
  277. }
  278. crc_ret = unzCloseCurrentFile( zip );
  279. if (crc_ret == UNZ_CRCERROR) {
  280. //CRC ERROR
  281. success = NO;
  282. break;
  283. }
  284. ret = unzGoToNextFile( zip );
  285. // Message delegate
  286. if ([delegate respondsToSelector:@selector(zipArchiveDidUnzipFileAtIndex:totalFiles:archivePath:fileInfo:)]) {
  287. [delegate zipArchiveDidUnzipFileAtIndex:currentFileNumber totalFiles:(NSInteger)globalInfo.number_entry
  288. archivePath:path fileInfo:fileInfo];
  289. } else if ([delegate respondsToSelector: @selector(zipArchiveDidUnzipFileAtIndex:totalFiles:archivePath:unzippedFilePath:)]) {
  290. [delegate zipArchiveDidUnzipFileAtIndex: currentFileNumber totalFiles: (NSInteger)globalInfo.number_entry
  291. archivePath:path unzippedFilePath: fullPath];
  292. }
  293. currentFileNumber++;
  294. if (progressHandler)
  295. {
  296. progressHandler(strPath, fileInfo, currentFileNumber, globalInfo.number_entry);
  297. }
  298. }
  299. } while(ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE);
  300. // Close
  301. unzClose(zip);
  302. // The process of decompressing the .zip archive causes the modification times on the folders
  303. // to be set to the present time. So, when we are done, they need to be explicitly set.
  304. // set the modification date on all of the directories.
  305. NSError * err = nil;
  306. for (NSDictionary * d in directoriesModificationDates) {
  307. if (![[NSFileManager defaultManager] setAttributes:@{NSFileModificationDate: d[@"modDate"]} ofItemAtPath:d[@"path"] error:&err]) {
  308. NSLog(@"[SSZipArchive] Set attributes failed for directory: %@.", d[@"path"]);
  309. }
  310. if (err) {
  311. NSLog(@"[SSZipArchive] Error setting directory file modification date attribute: %@",err.localizedDescription);
  312. }
  313. }
  314. #if !__has_feature(objc_arc)
  315. [directoriesModificationDates release];
  316. #endif
  317. // Message delegate
  318. if (success && [delegate respondsToSelector:@selector(zipArchiveDidUnzipArchiveAtPath:zipInfo:unzippedPath:)]) {
  319. [delegate zipArchiveDidUnzipArchiveAtPath:path zipInfo:globalInfo unzippedPath:destination];
  320. }
  321. // final progress event = 100%
  322. if (!canceled && [delegate respondsToSelector:@selector(zipArchiveProgressEvent:total:)]) {
  323. [delegate zipArchiveProgressEvent:fileSize total:fileSize];
  324. }
  325. NSError *retErr = nil;
  326. if (crc_ret == UNZ_CRCERROR)
  327. {
  328. NSDictionary *userInfo = @{NSLocalizedDescriptionKey: @"crc check failed for file"};
  329. retErr = [NSError errorWithDomain:@"SSZipArchiveErrorDomain" code:-3 userInfo:userInfo];
  330. }
  331. if (error)
  332. {
  333. *error = retErr;
  334. }
  335. if (completionHandler)
  336. {
  337. completionHandler(path, success, retErr);
  338. }
  339. return success;
  340. }
  341. #pragma mark - Zipping
  342. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray *)paths
  343. {
  344. return [SSZipArchive createZipFileAtPath:path withFilesAtPaths:paths withPassword:nil];
  345. }
  346. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath{
  347. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath withPassword:nil];
  348. }
  349. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirector{
  350. return [SSZipArchive createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:keepParentDirector withPassword:nil];
  351. }
  352. + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray *)paths withPassword:(NSString *)password
  353. {
  354. BOOL success = NO;
  355. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  356. if ([zipArchive open]) {
  357. for (NSString *filePath in paths) {
  358. [zipArchive writeFile:filePath withPassword:password];
  359. }
  360. success = [zipArchive close];
  361. }
  362. #if !__has_feature(objc_arc)
  363. [zipArchive release];
  364. #endif
  365. return success;
  366. }
  367. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath withPassword:(NSString *)password{
  368. return [self createZipFileAtPath:path withContentsOfDirectory:directoryPath keepParentDirectory:NO withPassword:password];
  369. }
  370. + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory withPassword:(NSString *)password{
  371. BOOL success = NO;
  372. NSFileManager *fileManager = nil;
  373. SSZipArchive *zipArchive = [[SSZipArchive alloc] initWithPath:path];
  374. if ([zipArchive open]) {
  375. // use a local filemanager (queue/thread compatibility)
  376. fileManager = [[NSFileManager alloc] init];
  377. NSDirectoryEnumerator *dirEnumerator = [fileManager enumeratorAtPath:directoryPath];
  378. NSString *fileName;
  379. while ((fileName = [dirEnumerator nextObject])) {
  380. BOOL isDir;
  381. NSString *fullFilePath = [directoryPath stringByAppendingPathComponent:fileName];
  382. [fileManager fileExistsAtPath:fullFilePath isDirectory:&isDir];
  383. if (!isDir) {
  384. if (keepParentDirectory)
  385. {
  386. fileName = [[directoryPath lastPathComponent] stringByAppendingPathComponent:fileName];
  387. }
  388. [zipArchive writeFileAtPath:fullFilePath withFileName:fileName withPassword:password];
  389. }
  390. else
  391. {
  392. if([[NSFileManager defaultManager] subpathsOfDirectoryAtPath:fullFilePath error:nil].count == 0)
  393. {
  394. NSString *tempName = [fullFilePath stringByAppendingPathComponent:@".DS_Store"];
  395. [@"" writeToFile:tempName atomically:YES encoding:NSUTF8StringEncoding error:nil];
  396. [zipArchive writeFileAtPath:tempName withFileName:[fileName stringByAppendingPathComponent:@".DS_Store"] withPassword:password];
  397. [[NSFileManager defaultManager] removeItemAtPath:tempName error:nil];
  398. }
  399. }
  400. }
  401. success = [zipArchive close];
  402. }
  403. #if !__has_feature(objc_arc)
  404. [fileManager release];
  405. [zipArchive release];
  406. #endif
  407. return success;
  408. }
  409. - (instancetype)initWithPath:(NSString *)path
  410. {
  411. if ((self = [super init])) {
  412. _path = [path copy];
  413. }
  414. return self;
  415. }
  416. #if !__has_feature(objc_arc)
  417. - (void)dealloc
  418. {
  419. [_path release];
  420. [super dealloc];
  421. }
  422. #endif
  423. - (BOOL)open
  424. {
  425. NSAssert((_zip == NULL), @"Attempting open an archive which is already open");
  426. _zip = zipOpen([_path UTF8String], APPEND_STATUS_CREATE);
  427. return (NULL != _zip);
  428. }
  429. - (void)zipInfo:(zip_fileinfo*)zipInfo setDate:(NSDate*)date
  430. {
  431. NSCalendar *currentCalendar = [NSCalendar currentCalendar];
  432. #if defined(__IPHONE_8_0) || defined(__MAC_10_10)
  433. uint flags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
  434. #else
  435. uint flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
  436. #endif
  437. NSDateComponents *components = [currentCalendar components:flags fromDate:date];
  438. zipInfo->tmz_date.tm_sec = (unsigned int)components.second;
  439. zipInfo->tmz_date.tm_min = (unsigned int)components.minute;
  440. zipInfo->tmz_date.tm_hour = (unsigned int)components.hour;
  441. zipInfo->tmz_date.tm_mday = (unsigned int)components.day;
  442. zipInfo->tmz_date.tm_mon = (unsigned int)components.month - 1;
  443. zipInfo->tmz_date.tm_year = (unsigned int)components.year;
  444. }
  445. - (BOOL)writeFolderAtPath:(NSString *)path withFolderName:(NSString *)folderName withPassword:(NSString *)password
  446. {
  447. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  448. zip_fileinfo zipInfo = {{0}};
  449. NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error: nil];
  450. if( attr )
  451. {
  452. NSDate *fileDate = (NSDate *)attr[NSFileModificationDate];
  453. if( fileDate )
  454. {
  455. [self zipInfo:&zipInfo setDate: fileDate ];
  456. }
  457. // Write permissions into the external attributes, for details on this see here: http://unix.stackexchange.com/a/14727
  458. // Get the permissions value from the files attributes
  459. NSNumber *permissionsValue = (NSNumber *)attr[NSFilePosixPermissions];
  460. if (permissionsValue) {
  461. // Get the short value for the permissions
  462. short permissionsShort = permissionsValue.shortValue;
  463. // Convert this into an octal by adding 010000, 010000 being the flag for a regular file
  464. NSInteger permissionsOctal = 0100000 + permissionsShort;
  465. // Convert this into a long value
  466. uLong permissionsLong = @(permissionsOctal).unsignedLongValue;
  467. // Store this into the external file attributes once it has been shifted 16 places left to form part of the second from last byte
  468. zipInfo.external_fa = permissionsLong << 16L;
  469. }
  470. }
  471. unsigned int len = 0;
  472. zipOpenNewFileInZip3(_zip, [[folderName stringByAppendingString:@"/"] UTF8String], &zipInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_NO_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL,
  473. Z_DEFAULT_STRATEGY, [password UTF8String], 0);
  474. zipWriteInFileInZip(_zip, &len, 0);
  475. zipCloseFileInZip(_zip);
  476. return YES;
  477. }
  478. - (BOOL)writeFile:(NSString *)path withPassword:(NSString *)password;
  479. {
  480. return [self writeFileAtPath:path withFileName:nil withPassword:password];
  481. }
  482. // supports writing files with logical folder/directory structure
  483. // *path* is the absolute path of the file that will be compressed
  484. // *fileName* is the relative name of the file how it is stored within the zip e.g. /folder/subfolder/text1.txt
  485. - (BOOL)writeFileAtPath:(NSString *)path withFileName:(NSString *)fileName withPassword:(NSString *)password
  486. {
  487. NSAssert((_zip != NULL), @"Attempting to write to an archive which was never opened");
  488. FILE *input = fopen([path UTF8String], "r");
  489. if (NULL == input) {
  490. return NO;
  491. }
  492. const char *afileName;
  493. if (!fileName) {
  494. afileName = [path.lastPathComponent UTF8String];
  495. }
  496. else {
  497. afileName = [fileName UTF8String];
  498. }
  499. zip_fileinfo zipInfo = {{0}};
  500. NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:path error: nil];
  501. if( attr )
  502. {
  503. NSDate *fileDate = (NSDate *)attr[NSFileModificationDate];
  504. if( fileDate )
  505. {
  506. [self zipInfo:&zipInfo setDate: fileDate ];
  507. }
  508. // Write permissions into the external attributes, for details on this see here: http://unix.stackexchange.com/a/14727
  509. // Get the permissions value from the files attributes
  510. NSNumber *permissionsValue = (NSNumber *)attr[NSFilePosixPermissions];
  511. if (permissionsValue) {
  512. // Get the short value for the permissions
  513. short permissionsShort = permissionsValue.shortValue;
  514. // Convert this into an octal by adding 010000, 010000 being the flag for a regular file
  515. NSInteger permissionsOctal = 0100000 + permissionsShort;
  516. // Convert this into a long value
  517. uLong permissionsLong = @(permissionsOctal).unsignedLongValue;
  518. // Store this into the external file attributes once it has been shifted 16 places left to form part of the second from last byte
  519. zipInfo.external_fa = permissionsLong << 16L;
  520. }
  521. }
  522. void *buffer = malloc(CHUNK);
  523. if (buffer == NULL)
  524. {
  525. return NO;
  526. }
  527. 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);
  528. unsigned int len = 0;
  529. while (!feof(input))
  530. {
  531. len = (unsigned int) fread(buffer, 1, CHUNK, input);
  532. zipWriteInFileInZip(_zip, buffer, len);
  533. }
  534. zipCloseFileInZip(_zip);
  535. free(buffer);
  536. fclose(input);
  537. return YES;
  538. }
  539. - (BOOL)writeData:(NSData *)data filename:(NSString *)filename withPassword:(NSString *)password;
  540. {
  541. if (!_zip) {
  542. return NO;
  543. }
  544. if (!data) {
  545. return NO;
  546. }
  547. zip_fileinfo zipInfo = {{0,0,0,0,0,0},0,0,0};
  548. [self zipInfo:&zipInfo setDate:[NSDate date]];
  549. zipOpenNewFileInZip3(_zip, [filename UTF8String], &zipInfo, NULL, 0, NULL, 0, NULL, Z_DEFLATED, Z_DEFAULT_COMPRESSION, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, [password UTF8String], 0);
  550. zipWriteInFileInZip(_zip, data.bytes, (unsigned int)data.length);
  551. zipCloseFileInZip(_zip);
  552. return YES;
  553. }
  554. - (BOOL)close
  555. {
  556. NSAssert((_zip != NULL), @"[SSZipArchive] Attempting to close an archive which was never opened");
  557. zipClose(_zip, NULL);
  558. return YES;
  559. }
  560. #pragma mark - Private
  561. // Format from http://newsgroups.derkeiler.com/Archive/Comp/comp.os.msdos.programmer/2009-04/msg00060.html
  562. // Two consecutive words, or a longword, YYYYYYYMMMMDDDDD hhhhhmmmmmmsssss
  563. // YYYYYYY is years from 1980 = 0
  564. // sssss is (seconds/2).
  565. //
  566. // 3658 = 0011 0110 0101 1000 = 0011011 0010 11000 = 27 2 24 = 2007-02-24
  567. // 7423 = 0111 0100 0010 0011 - 01110 100001 00011 = 14 33 3 = 14:33:06
  568. + (NSDate *)_dateWithMSDOSFormat:(UInt32)msdosDateTime
  569. {
  570. static const UInt32 kYearMask = 0xFE000000;
  571. static const UInt32 kMonthMask = 0x1E00000;
  572. static const UInt32 kDayMask = 0x1F0000;
  573. static const UInt32 kHourMask = 0xF800;
  574. static const UInt32 kMinuteMask = 0x7E0;
  575. static const UInt32 kSecondMask = 0x1F;
  576. static NSCalendar *gregorian;
  577. static dispatch_once_t onceToken;
  578. dispatch_once(&onceToken, ^{
  579. #if defined(__IPHONE_8_0) || defined(__MAC_10_10)
  580. gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  581. #else
  582. gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
  583. #endif
  584. });
  585. NSDateComponents *components = [[NSDateComponents alloc] init];
  586. NSAssert(0xFFFFFFFF == (kYearMask | kMonthMask | kDayMask | kHourMask | kMinuteMask | kSecondMask), @"[SSZipArchive] MSDOS date masks don't add up");
  587. [components setYear:1980 + ((msdosDateTime & kYearMask) >> 25)];
  588. [components setMonth:(msdosDateTime & kMonthMask) >> 21];
  589. [components setDay:(msdosDateTime & kDayMask) >> 16];
  590. [components setHour:(msdosDateTime & kHourMask) >> 11];
  591. [components setMinute:(msdosDateTime & kMinuteMask) >> 5];
  592. [components setSecond:(msdosDateTime & kSecondMask) * 2];
  593. NSDate *date = [NSDate dateWithTimeInterval:0 sinceDate:[gregorian dateFromComponents:components]];
  594. #if !__has_feature(objc_arc)
  595. [components release];
  596. #endif
  597. return date;
  598. }
  599. @end