-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
SSZipArchiveTests.m
835 lines (614 loc) · 38.8 KB
/
SSZipArchiveTests.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//
// SSZipArchiveTests.m
// SSZipArchiveTests
//
// Created by Sam Soffes on 10/3/11.
// Copyright (c) 2011-2014 Sam Soffes. All rights reserved.
//
#if COCOAPODS
#import <SSZipArchive.h>
#else
#import <ZipArchive.h>
#endif
#import <XCTest/XCTest.h>
#import <CommonCrypto/CommonDigest.h>
#import "CollectingDelegate.h"
#import "CancelDelegate.h"
#import "ProgressDelegate.h"
@interface SSZipArchiveTests : XCTestCase
@end
@interface NSString (SSZipArchive)
- (NSString *)_sanitizedPath;
@end
@implementation SSZipArchiveTests
int twentyMB = 20 * 1024 * 1024;
- (void)setUp {
[super setUp];
}
- (void)tearDown {
[super tearDown];
[[NSFileManager defaultManager] removeItemAtPath:[self _cachesPath:nil] error:nil];
}
- (void)testZipping {
// use extracted files from [-testUnzipping]
[self testUnzipping];
NSString *inputPath = [self _cachesPath:@"Regular"];
NSArray *inputPaths = @[[inputPath stringByAppendingPathComponent:@"Readme.markdown"],
[inputPath stringByAppendingPathComponent:@"LICENSE"]];
NSString *outputPath = [self _cachesPath:@"Zipped"];
NSString *archivePath = [outputPath stringByAppendingPathComponent:@"CreatedArchive.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:inputPaths];
XCTAssertTrue(success, @"create zip failure");
// TODO: Make sure the files are actually zipped. They are, but the test should be better.
XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:archivePath], @"Archive created");
BOOL protected = [SSZipArchive isFilePasswordProtectedAtPath:archivePath];
XCTAssertFalse(protected, @"has no password");
}
- (void)testZippingWithPassword {
// use extracted files from [-testUnzipping]
[self testUnzipping];
NSString *inputPath = [self _cachesPath:@"Regular"];
NSArray *inputPaths = @[[inputPath stringByAppendingPathComponent:@"Readme.markdown"],
[inputPath stringByAppendingPathComponent:@"LICENSE"]];
NSString *outputPath = [self _cachesPath:@"Zipped"];
NSString *archivePath = [outputPath stringByAppendingPathComponent:@"CreatedArchive.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:inputPaths withPassword:@"dolphins🐋"];
XCTAssertTrue(success, @"create zip failure");
// TODO: Make sure the files are actually zipped. They are, but the test should be better.
XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:archivePath], @"Archive created");
BOOL protected = [SSZipArchive isFilePasswordProtectedAtPath:archivePath];
XCTAssertTrue(protected, @"has password");
}
- (void)testZippingWithZeroLengthPassword {
// use extracted files from [-testUnzipping]
[self testUnzipping];
NSString *inputPath = [self _cachesPath:@"Regular"];
NSArray *inputPaths = @[[inputPath stringByAppendingPathComponent:@"Readme.markdown"],
[inputPath stringByAppendingPathComponent:@"LICENSE"]];
NSString *outputPath = [self _cachesPath:@"Zipped"];
NSString *archivePath = [outputPath stringByAppendingPathComponent:@"CreatedArchive.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:inputPaths withPassword:@""];
XCTAssertTrue(success, @"create zip failure");
// TODO: Make sure the files are actually zipped. They are, but the test should be better.
XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:archivePath], @"Archive created");
BOOL protected = [SSZipArchive isFilePasswordProtectedAtPath:archivePath];
XCTAssertTrue(protected, @"has password");
}
- (void)testDirectoryZipping {
// use Unicode as folder (has a file in root and a file in subfolder)
[self testUnzippingWithUnicodeFilenameInside];
NSString *inputPath = [self _cachesPath:@"Unicode"];
NSString *outputPath = [self _cachesPath:@"FolderZipped"];
NSString *archivePath = [outputPath stringByAppendingPathComponent:@"ArchiveWithFolders.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withContentsOfDirectory:inputPath];
XCTAssertTrue(success, @"create zip failure");
XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:archivePath], @"Folder Archive created");
}
- (void)testMultipleZippping{
NSArray *inputPaths = @[[[NSBundle bundleForClass: [self class]]pathForResource:@"0" ofType:@"m4a"],
[[NSBundle bundleForClass: [self class]]pathForResource:@"1" ofType:@"m4a"],
[[NSBundle bundleForClass: [self class]]pathForResource:@"2" ofType:@"m4a"],
[[NSBundle bundleForClass: [self class]]pathForResource:@"3" ofType:@"m4a"],
[[NSBundle bundleForClass: [self class]]pathForResource:@"4" ofType:@"m4a"],
[[NSBundle bundleForClass: [self class]]pathForResource:@"5" ofType:@"m4a"],
[[NSBundle bundleForClass: [self class]]pathForResource:@"6" ofType:@"m4a"],
[[NSBundle bundleForClass: [self class]]pathForResource:@"7" ofType:@"m4a"]
];
NSString *outputPath = [self _cachesPath:@"Zipped"];
// this is a monster
// if testing on iOS, within 30 loops it will fail; however, on OS X, it may take about 900 loops
for (int test = 0; test < 20; test++)
{
// Zipping
NSString *archivePath = [outputPath stringByAppendingPathComponent:[NSString stringWithFormat:@"queue_test_%d.zip", test]];
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:inputPaths];
XCTAssertTrue(success, @"create zip failure");
long long threshold = 510000; // 510kB:size slightly smaller than a successful zip, but much larger than a failed one
long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:archivePath error:nil][NSFileSize] longLongValue];
XCTAssertTrue(fileSize > threshold, @"zipping failed at %@!", archivePath);
}
}
- (void)testUnzipping {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Regular"];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [outputPath stringByAppendingPathComponent:@"Readme.markdown"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"Readme unzipped");
testPath = [outputPath stringByAppendingPathComponent:@"LICENSE"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"LICENSE unzipped");
}
- (void)testSmallFileUnzipping {
NSString *zipPath = [[NSBundle bundleForClass: [self class]] pathForResource:@"TestArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Regular"];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [outputPath stringByAppendingPathComponent:@"Readme.markdown"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"Readme unzipped");
testPath = [outputPath stringByAppendingPathComponent:@"LICENSE"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"LICENSE unzipped");
}
-(void)testAppendingToZip {
// zip files and create "CreatedArchive.zip"
[self testZipping];
NSString *outputPath = [self _cachesPath:@"Zipped"];
NSString *archivePath = [outputPath stringByAppendingPathComponent:@"CreatedArchive.zip"];
long long initialFileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:archivePath error:NULL][NSFileSize] longLongValue];
SSZipArchive* zip = [[SSZipArchive alloc] initWithPath:archivePath];
BOOL didOpenForAppending = [zip openForAppending];
XCTAssertTrue(didOpenForAppending, @"Opened for appending");
NSData* testData = [@"test contents" dataUsingEncoding:NSUTF8StringEncoding];
BOOL didAppendFile = [zip writeData:testData filename:@"testData.txt" withPassword:NULL];
XCTAssertTrue(didAppendFile, @"Did add file");
BOOL didClose = [zip close];
XCTAssertTrue(didClose, @"Can close zip");
// TODO: Make sure the files are actually zipped. They are, but the test should be better.
XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:archivePath], @"Archive created");
long long fileSizeAfterAppend = [[[NSFileManager defaultManager] attributesOfItemAtPath:archivePath error:NULL][NSFileSize] longLongValue];
XCTAssertGreaterThan(fileSizeAfterAppend, initialFileSize);
}
- (void)testUnzippingProgress {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Progress"];
ProgressDelegate *delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
// 4 events: the first, then for each of the two files one, then the final event
XCTAssertTrue(4 == [delegate->progressEvents count], @"Expected 4 progress events");
XCTAssertTrue(0 == [delegate->progressEvents[0] intValue]);
XCTAssertTrue(619 == [delegate->progressEvents[1] intValue]);
XCTAssertTrue(1114 == [delegate->progressEvents[2] intValue]);
XCTAssertTrue(1436 == [delegate->progressEvents[3] intValue]);
}
- (void)testUnzippingWithPassword {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestPasswordArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Password"];
NSError *error = nil;
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath overwrite:YES password:@"passw0rd" error:&error delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [outputPath stringByAppendingPathComponent:@"Readme.markdown"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"Readme unzipped");
testPath = [outputPath stringByAppendingPathComponent:@"LICENSE"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"LICENSE unzipped");
}
- (void)testUnzippingWithAESPassword {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestAESPasswordArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Password"];
NSError *error = nil;
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath overwrite:YES password:@"passw0rd" error:&error delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [outputPath stringByAppendingPathComponent:@"README.md"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"Readme unzipped");
testPath = [outputPath stringByAppendingPathComponent:@"LICENSE.txt"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"LICENSE unzipped");
}
- (void)testUnzippingWithInvalidPassword {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestPasswordArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Password"];
NSError *error = nil;
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath overwrite:YES password:@"passw0rd123" error:&error delegate:delegate];
XCTAssertFalse(success, @"unzip failure");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [outputPath stringByAppendingPathComponent:@"Readme.markdown"];
XCTAssertFalse([fileManager fileExistsAtPath:testPath], @"Readme not unzipped");
testPath = [outputPath stringByAppendingPathComponent:@"LICENSE"];
XCTAssertFalse([fileManager fileExistsAtPath:testPath], @"LICENSE not unzipped");
}
- (void)testIsPasswordInvalidForArchiveAtPath {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestPasswordArchive" ofType:@"zip"];
NSError *error = nil;
BOOL fileHasValidPassword = [SSZipArchive isPasswordValidForArchiveAtPath:zipPath password:@"passw0rd" error:&error];
XCTAssertTrue(fileHasValidPassword, @"Valid password reports false.");
BOOL fileHasInvalidValidPassword = [SSZipArchive isPasswordValidForArchiveAtPath:zipPath password:@"passw0rd123" error:&error];
XCTAssertFalse(fileHasInvalidValidPassword, @"Invalid password reports true.");
}
- (void)testIsFilePasswordProtectedAtPath {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestArchive" ofType:@"zip"];
BOOL protected = [SSZipArchive isFilePasswordProtectedAtPath:zipPath];
XCTAssertFalse(protected, @"has no password");
NSString *zipWithPasswordPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestPasswordArchive" ofType:@"zip"];
protected = [SSZipArchive isFilePasswordProtectedAtPath:zipWithPasswordPath];
XCTAssertTrue(protected, @"has password");
}
- (void)testZippingAndUnzippingWithUnicodePassword {
/********** Zipping ********/
// use extracted files from [-testUnzipping]
[self testUnzipping];
NSString *inputPath = [self _cachesPath:@"Regular"];
NSArray *inputPaths = @[[inputPath stringByAppendingPathComponent:@"Readme.markdown"],
[inputPath stringByAppendingPathComponent:@"LICENSE"]];
NSString *outputPath = [self _cachesPath:@"Zipped"];
NSString *archivePath = [outputPath stringByAppendingPathComponent:@"CreatedUnicodePasswordArchive.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:inputPaths withPassword:@"ꊐ⌒Ⅳ🤐"];
XCTAssertTrue(success, @"create zip failure");
XCTAssertTrue([[NSFileManager defaultManager] fileExistsAtPath:archivePath], @"Archive created");
/********** Unzipping ********/
outputPath = [self _cachesPath:@"UnicodePassword"];
NSError *error = nil;
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
success = [SSZipArchive unzipFileAtPath:archivePath toDestination:outputPath overwrite:YES password:@"ꊐ⌒Ⅳ🤐" error:&error delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testPath = [outputPath stringByAppendingPathComponent:@"Readme.markdown"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"Readme unzipped");
testPath = [outputPath stringByAppendingPathComponent:@"LICENSE"];
XCTAssertTrue([fileManager fileExistsAtPath:testPath], @"LICENSE unzipped");
}
- (void)testUnzippingTruncatedFileFix {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"IncorrectHeaders" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"IncorrectHeaders"];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSString *intendedReadmeTxtSHA256 = @"b389c1b182306c9fa68a38f667a6ac35863b6d670ae98954403c265ffe67e9bc";
NSString *filePath = [outputPath stringByAppendingPathComponent:@"IncorrectHeaders/Readme.txt"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *actualReadmeTxtSHA256 = [self _calculateSHA256Hash:data];
XCTAssertTrue([actualReadmeTxtSHA256 isEqualToString:intendedReadmeTxtSHA256], @"Readme.txt SHA256 digest should match original.");
}
- (void)testUnzippingWithSymlinkedFileInside {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"SymbolicLink" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"SymbolicLink"];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath preserveAttributes:YES overwrite:YES symlinksValidWithin:nil nestedZipLevel:0 password:nil error:nil delegate:delegate progressHandler:nil completionHandler:nil];
XCTAssertTrue(success, @"unzip failure");
NSString *testSymlink = [outputPath stringByAppendingPathComponent:@"SymbolicLink/Xcode.app"];
NSError *error = nil;
NSDictionary *info = [[NSFileManager defaultManager] attributesOfItemAtPath: testSymlink error: &error];
BOOL fileIsSymbolicLink = info[NSFileType] == NSFileTypeSymbolicLink;
XCTAssertTrue(fileIsSymbolicLink, @"Symbolic links should persist from the original archive to the outputted files.");
}
- (void)testUnzippingWithSymlinkedFileEscapingOutputDirectory {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"SymbolicLink" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"SymbolicLink"];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
NSError *error = nil;
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath overwrite:YES password:nil error:&error delegate:delegate];
XCTAssertFalse(success, @"Escaping symlink unpacked");
XCTAssertNotNil(error, @"Error not reported");
XCTAssertEqualObjects(error.domain, SSZipArchiveErrorDomain, @"Invalid error domain");
XCTAssertEqual(error.code, SSZipArchiveErrorCodeSymlinkEscapesTargetDirectory, @"Invalid error code");
}
- (void)testUnzippingWithRelativeSymlink {
NSString *resourceName = @"RelativeSymbolicLink";
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:resourceName ofType:@"zip"];
NSString *outputPath = [self _cachesPath:resourceName];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
// Determine where the symlinks are
NSString *subfolderName = @"symlinks";
NSString *testBasePath = [NSString pathWithComponents:@[outputPath]];
NSString *testSymlinkFolder = [NSString pathWithComponents:@[testBasePath, subfolderName, @"folderSymlink"]];
NSString *testSymlinkFile = [NSString pathWithComponents:@[testBasePath, subfolderName, @"fileSymlink"]];
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:testSymlinkFile error: nil];
BOOL fileIsSymbolicLink = fileAttributes[NSFileType] == NSFileTypeSymbolicLink;
XCTAssertTrue(fileIsSymbolicLink, @"Relative symbolic links should persist from the original archive to the outputted files.");
NSDictionary *folderAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:testSymlinkFolder error: nil];
BOOL folderIsSymbolicLink = folderAttributes[NSFileType] == NSFileTypeSymbolicLink;
XCTAssertTrue(folderIsSymbolicLink, @"Relative symbolic links should persist from the original archive to the outputted files.");
}
- (void)testUnzippingWithUnicodeFilenameInside {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"Unicode" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Unicode"];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
bool unicodeFilenameWasExtracted = [[NSFileManager defaultManager] fileExistsAtPath:[outputPath stringByAppendingPathComponent:@"Accént.txt"]];
bool unicodeFolderWasExtracted = [[NSFileManager defaultManager] fileExistsAtPath:[outputPath stringByAppendingPathComponent:@"Fólder/Nothing.txt"]];
XCTAssertTrue(unicodeFilenameWasExtracted, @"Files with filenames in unicode should be extracted properly.");
XCTAssertTrue(unicodeFolderWasExtracted, @"Folders with names in unicode should be extracted propertly.");
}
/// Issue #507
- (void)testZippingWithUnicodeFilenameInside {
NSString *workPath = [self _cachesPath:@"UnicodeZipping"];
NSString *filePath = [workPath stringByAppendingPathComponent:@"17 What I’ve Been Looking For.pdf"];
NSString *zipPath = [workPath stringByAppendingPathComponent:@"UnicodeZipping.zip"];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
BOOL success = [SSZipArchive createZipFileAtPath:zipPath withFilesAtPaths:@[filePath]];
XCTAssertTrue(success, @"zip failure");
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
success = [SSZipArchive unzipFileAtPath:zipPath toDestination:workPath delegate:nil];
XCTAssertTrue(success, @"unzip failure");
bool unicodeFilenameWasExtracted = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
XCTAssertTrue(unicodeFilenameWasExtracted, @"Files with filenames in unicode should be extracted properly.");
}
- (void)testZippingEmptyArchive {
NSString *inputPath = [self _cachesPath:@"Empty"];
XCTAssert(![[NSFileManager defaultManager] enumeratorAtPath:inputPath].nextObject, @"The Empty cache folder should always be empty.");
NSString *outputPath = [self _cachesPath:@"Zipped"];
NSString *zipPath = [outputPath stringByAppendingPathComponent:@"Empty.zip"];
NSString *zipPath2 = [outputPath stringByAppendingPathComponent:@"EmptyWithParentDirectory.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:zipPath withContentsOfDirectory:inputPath keepParentDirectory:NO];
XCTAssertTrue(success, @"create zip failure");
success = [SSZipArchive createZipFileAtPath:zipPath2 withContentsOfDirectory:inputPath keepParentDirectory:YES];
XCTAssertTrue(success, @"create zip failure");
long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:zipPath error:nil][NSFileSize] longLongValue];
long long fileSize2 = [[[NSFileManager defaultManager] attributesOfItemAtPath:zipPath2 error:nil][NSFileSize] longLongValue];
XCTAssert(fileSize < fileSize2, @"keepParentDirectory should produce a strictly bigger archive.");
}
- (void)testZippingAndUnzippingEmptyDirectoryWithPassword {
NSString *inputPath = [self _cachesPath:@"Empty"];
XCTAssert(![[NSFileManager defaultManager] enumeratorAtPath:inputPath].nextObject, @"The Empty cache folder should always be empty.");
NSString *outputPath = [self _cachesPath:@"Zipped"];
NSString *zipPath = [outputPath stringByAppendingPathComponent:@"EmptyWithParentDirectory.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:zipPath withContentsOfDirectory:inputPath keepParentDirectory:YES withPassword:@"password"];
XCTAssertTrue(success, @"create zip failure");
outputPath = [self _cachesPath:@"EmptyDirectory"];
// unzipping a directory doesn't require a password
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath overwrite:YES password:nil error:nil delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
}
- (void)testUnzippingEmptyArchive {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"Empty" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Empty"];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:nil];
XCTAssertTrue(success, @"unzip failure");
}
- (void)testZippingAndUnzippingForDate {
// use extracted files from [-testUnzipping]
[self testUnzipping];
NSString *inputPath = [self _cachesPath:@"Regular"];
NSArray *inputPaths = @[[inputPath stringByAppendingPathComponent:@"Readme.markdown"]];
NSDictionary *originalFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[inputPath stringByAppendingPathComponent:@"Readme.markdown"] error:nil];
NSString *outputPath = [self _cachesPath:@"ZippedDate"];
NSString *archivePath = [outputPath stringByAppendingPathComponent:@"CreatedArchive.zip"];
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:inputPaths];
XCTAssertTrue(success, @"create zip failure");
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
success = [SSZipArchive unzipFileAtPath:archivePath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSDictionary *createdFileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[outputPath stringByAppendingPathComponent:@"Readme.markdown"] error:nil];
XCTAssertEqualObjects(originalFileAttributes[NSFileCreationDate], createdFileAttributes[@"NSFileCreationDate"], @"Original file creationDate should match created one");
}
- (void)testZippingAndUnzippingForPermissions {
// File we're going to test permissions on before and after zipping
NSString *targetFile = @"/Contents/MacOS/TestProject";
/********** Zipping ********/
// The .app file we're going to zip up
NSString *inputFile = [[NSBundle bundleForClass: [self class]] pathForResource:@"PermissionsTestApp" ofType:@"app"];
// The path to the target file in the app before zipping
NSString *targetFilePreZipPath = [inputFile stringByAppendingPathComponent:targetFile];
// Atribtues for the target file before zipping
NSDictionary *preZipAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:targetFilePreZipPath error:nil];
// Directory to output our created zip file
NSString *outputDir = [self _cachesPath:@"PermissionsTest"];
// The path to where the archive shall be created
NSString *archivePath = [outputDir stringByAppendingPathComponent:@"TestAppArchive.zip"];
// Create the zip file using the contents of the .app file as the input
BOOL success = [SSZipArchive createZipFileAtPath:archivePath withContentsOfDirectory:inputFile];
XCTAssertTrue(success, @"create zip failure");
/********** Un-zipping *******/
// Using this newly created zip file, unzip it
success = [SSZipArchive unzipFileAtPath:archivePath toDestination:outputDir];
XCTAssertTrue(success, @"unzip failure");
// Get the path to the target file after unzipping
NSString *targetFilePath = [outputDir stringByAppendingPathComponent:@"/Contents/MacOS/TestProject"];
// Get the file attributes of the target file following the unzipping
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:targetFilePath error:nil];
NSInteger permissions = ((NSNumber *)fileAttributes[NSFilePosixPermissions]).longValue;
NSInteger preZipPermissions = ((NSNumber *)preZipAttributes[NSFilePosixPermissions]).longValue;
// Compare the value of the permissions attribute to assert equality
XCTAssertEqual(permissions, preZipPermissions, @"File permissions should be retained during compression and de-compression");
}
- (void)testUnzippingWithCancel {
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Cancel1"];
CancelDelegate *delegate = [[CancelDelegate alloc] init];
delegate.numFilesToUnzip = 1;
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertFalse(success);
XCTAssertEqual(delegate.numFilesUnzipped, 1);
XCTAssertFalse(delegate.didUnzipArchive);
XCTAssertNotEqual(delegate.loaded, delegate.total);
outputPath = [self _cachesPath:@"Cancel2"];
delegate = [[CancelDelegate alloc] init];
delegate.numFilesToUnzip = 1000;
success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
XCTAssertEqual(delegate.numFilesUnzipped, 2);
XCTAssertTrue(delegate.didUnzipArchive);
XCTAssertEqual(delegate.loaded, delegate.total);
}
// Commented out to avoid checking in several gig file into the repository. Simply add a file named
// `LargeArchive.zip` to the project and uncomment out these lines to test.
//
//- (void)testUnzippingLargeFiles {
// NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"LargeArchive" ofType:@"zip"];
// NSString *outputPath = [self _cachesPath:@"Large"];
//
// BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath];
// XCTAssertTrue(success, @"unzip failure");
//}
-(void)testShouldProvidePathOfUnzippedFileInDelegateCallback {
CollectingDelegate *collector = [CollectingDelegate new];
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"TestArchive" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Regular"];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:collector];
XCTAssertTrue(success, @"unzip failure");
XCTAssertEqualObjects(collector.files[0], [outputPath stringByAppendingString:@"/LICENSE"]);
XCTAssertEqualObjects(collector.files[1], [outputPath stringByAppendingString:@"/Readme.markdown"]);
}
- (void)testUnzippingFileWithPathTraversalName {
// This zip archive contains a file titled '../../../../../../../../../../..//tmp/test.txt'. SSZipArchive should
// ignore the path traversing and write the file to "tmp/test.txt"
NSString *zipPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"PathTraversal" ofType:@"zip"];
NSString *outputPath = [self _cachesPath:@"Traversal"];
id<SSZipArchiveDelegate> delegate = [ProgressDelegate new];
BOOL success = [SSZipArchive unzipFileAtPath:zipPath toDestination:outputPath delegate:delegate];
XCTAssertTrue(success, @"unzip failure");
NSString *expectedFile = [outputPath stringByAppendingPathComponent:@"tmp/test.txt"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:expectedFile];
XCTAssertTrue(fileExists, @"Path traversal characters should not be followed when unarchiving a file");
}
- (void)testPathSanitation {
NSDictionary<NSString *, NSString *> *tests =
@{
// path traversal
@"../../../../../../../../../../../tmp/test.txt": @"tmp/test.txt",
// path traversal, Windows style
@"..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\..\\tmp\\test.txt": @"tmp/test.txt",
// relative path
@"a/b/../c.txt": @"a/c.txt",
// path traversal without slash
@"..": @"",
// permissions override
@"./": @"",
@".": @"",
// unicode and spaces in folder name and file name
@"example/../à: 𝚨 /你 好.txt": @"à: 𝚨 /你 好.txt",
// unicode that looks like '.' or '/' in ascii decomposition
@"a/ğ/../b": @"a/b",
@"a/⸮/b/.ⸯ/c/⼮./d": @"a/⸮/b/.ⸯ/c/⼮./d",
// scheme in name
@"file:a/../../../usr/bin": @"usr/bin",
};
for (NSString *str in tests) {
//NSLog(@"%@", str);
XCTAssertTrue([tests[str] isEqualToString:[str _sanitizedPath]], @"Path should be sanitized for traversal");
}
}
// This tests whether the payload size of the zip file containing 4.8Gb of files with compression 0 is correct,
// and creates a zip file containing 240 20Mb sized files with multiple compression levels. It then unpacks the file and checks whether
// the same number of files is present in the unpacked folder.
- (void)testPayloadSizeCorrectAndUnpackFileNo {
long long int iterations = 240;
NSString *unpackPath = [self _cachesPath:@"Unpacked/testFile"];
NSNumber *goldenSize = [NSNumber numberWithLongLong:iterations * twentyMB];
NSData *data = [self get20MbNSData];
NSString *filenName = @"TestFile.zip";
NSString *filePath = [NSString stringWithFormat:@"%@%@", [self _cachesPath:@""], filenName];
NSString *password = @"TestPW";
SSZipArchive *archive = [[SSZipArchive alloc] initWithPath:filePath];
[archive open];
for (int i = 0; i < iterations; i++) {
NSString *fileName = [NSString stringWithFormat:@"File_%i", i];
[archive writeData:data filename:fileName compressionLevel:0 password:password AES:true];
}
bool close = [archive close];
NSNumber *fileSize = [SSZipArchive payloadSizeForArchiveAtPath:filePath error:nil];
XCTAssertTrue(close, "Should be able to close the archive.");
XCTAssertTrue(fileSize.longLongValue == goldenSize.longLongValue,
"Payload size should be equal to the sum of the size of all files included.");
[SSZipArchive unzipFileAtPath:filePath toDestination:unpackPath overwrite:true password:password error:nil];
long int noFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:unpackPath error:nil].count;
XCTAssertTrue(iterations == noFiles, "All files should be present in the exported directory");
}
//PR #560
- (void)testSymlinkZippingWithFilesAtPaths {
NSString *outputDir = [self _cachesPath:@"ZippingSymlinkWithFilesAtPaths"];
//directory
NSString *directory = [outputDir stringByAppendingPathComponent:@"directory"];
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL];
XCTAssertTrue(success);
//write real file
NSString *realFilePath = [directory stringByAppendingPathComponent:@"originfile"];
success = [@"Hello World!" writeToFile:realFilePath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
XCTAssertTrue(success);
//create symlink to real file
NSString *symlinkPath = [directory stringByAppendingPathComponent:@"linkfile"];
success = [[NSFileManager defaultManager] createSymbolicLinkAtPath:symlinkPath withDestinationPath:realFilePath error:NULL];
XCTAssertTrue(success);
NSArray *files = @[realFilePath,symlinkPath];
//zipping
NSString *archivePath = [outputDir stringByAppendingPathComponent:@"SymlinkZippingWithFilesAtPaths.zip"];
success = [SSZipArchive createZipFileAtPath:archivePath withFilesAtPaths:files withPassword:nil keepSymlinks:YES];
XCTAssertTrue(success);
//remove files in directory dir, to make sure what we check is unzipped
success = [[NSFileManager defaultManager] removeItemAtPath:directory error:NULL];
XCTAssertTrue(success);
success = [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL];
XCTAssertTrue(success);
//unzip
success = [SSZipArchive unzipFileAtPath:archivePath toDestination:directory];
XCTAssertTrue(success);
//check if it's still a symlink
NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:symlinkPath error:NULL];
NSString *fileType = attr[NSFileType];
XCTAssertTrue([fileType isEqualToString:NSFileTypeSymbolicLink]);
//check symlink points correctly
NSString *realFilePathUnzip = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath:symlinkPath error:NULL];
XCTAssertEqualObjects(realFilePath, realFilePathUnzip);
}
//PR #560
- (void)testSymlinkZippingWithContentsOfDirectory {
NSString *outputDir = [self _cachesPath:@"ZippingSymlinkWithContentsOfDirectory"];
//directory
NSString *directory = [outputDir stringByAppendingPathComponent:@"directory"];
BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL];
XCTAssertTrue(success);
//write real file
NSString *realFilePath = [directory stringByAppendingPathComponent:@"origin"];
success = [@"Hello World!" writeToFile:realFilePath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
XCTAssertTrue(success);
//create symlink to real file
NSString *symlinkPath = [directory stringByAppendingPathComponent:@"link"];
success = [[NSFileManager defaultManager] createSymbolicLinkAtPath:symlinkPath withDestinationPath:realFilePath error:NULL];
XCTAssertTrue(success);
//zipping
NSString *archivePath = [outputDir stringByAppendingPathComponent:@"SymlinkZippingWithContentsOfDirectory.zip"];
success = [SSZipArchive createZipFileAtPath:archivePath
withContentsOfDirectory:directory
keepParentDirectory:NO
compressionLevel:-1
password:nil
AES:YES
progressHandler:nil
keepSymlinks:YES];
XCTAssertTrue(success);
//remove files in directory dir, to make sure what we check is unzipped
success = [[NSFileManager defaultManager] removeItemAtPath:directory error:NULL];
XCTAssertTrue(success);
success = [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:NULL];
XCTAssertTrue(success);
//unzip
success = [SSZipArchive unzipFileAtPath:archivePath toDestination:directory];
XCTAssertTrue(success);
//check if it's still a symlink
NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:symlinkPath error:NULL];
NSString *fileType = attr[NSFileType];
XCTAssertTrue([fileType isEqualToString:NSFileTypeSymbolicLink]);
//check symlink points correctly
NSString *realFilePathUnzip = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath:symlinkPath error:NULL];
XCTAssertEqualObjects(realFilePath, realFilePathUnzip);
}
#pragma mark - Private
// Returns 20Mb of data
-(NSData*)get20MbNSData {
NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMB];
for (long long int i = 0; i < twentyMB/4; i++) {
u_int32_t randomBits = arc4random();
[theData appendBytes:(void *)&randomBits length:4];
}
return theData;
}
- (NSString *)_cachesPath:(NSString *)directory {
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject
stringByAppendingPathComponent:@"com.samsoffes.ssziparchive.tests"];
if (directory) {
path = [path stringByAppendingPathComponent:directory];
}
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
return path;
}
- (NSString *)_calculateSHA256Hash:(NSData *)data {
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(data.bytes, (CC_LONG) data.length, digest);
//convert the SHA hash to a string
NSMutableString* ms = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH];
for(int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[ms appendFormat:@"%02x", digest[i]];
}
return [ms copy];
}
@end