-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArchiveWrapper.m
446 lines (358 loc) · 10.3 KB
/
ArchiveWrapper.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
/* Copyright (c) 2010 Per Johansson, per at morth.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#import "ArchiveWrapper.h"
#include <archive.h>
#include <archive_entry.h>
NSString * const ArchiveMemberInfoNotAvailableException = @"ArchiveMemberInfoNotAvailableException";
NSString * const ArchiveMemberDataNotAvailableException = @"ArchiveMemberDataNotAvailableException";
NSString * const ArchiveErrorDomain = @"ArchiveErrorDomain";
@interface ArchiveWrapper (Errors)
+ (NSError*)archiveError:(struct archive *)archive code:(NSInteger)code;
+ (NSError*)errorWithCode:(NSInteger)code eno:(int)eno string:(NSString*)str;
@end
@implementation ArchiveWrapper (Errors)
+ (NSError*)archiveError:(struct archive *)archive code:(NSInteger)code
{
/*
* XXX NSASCIIStringEncoding is based on looking at libarchive source code.
* It's conceivable that they'll use catalogs sometime in the future, in case
* that might be wrong.
* I can't find a useable encoding for that, might not exist one.
*/
return [NSError errorWithDomain:ArchiveErrorDomain
code:code
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:archive_errno(archive)], @"errno",
[NSString stringWithCString:archive_error_string (archive)
encoding:NSASCIIStringEncoding], @"error_string",
nil]];
}
+ (NSError*)errorWithCode:(NSInteger)code eno:(int)eno string:(NSString*)str
{
return [NSError errorWithDomain:ArchiveErrorDomain
code:code
userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:eno], @"errno",
str, @"error_string",
nil]];
}
@end
@implementation ArchiveMember
- (id)initWithWrapper:(ArchiveWrapper *)w archive:(struct archive *)a encoding:(NSStringEncoding)enc error:(NSError**)error
{
self = [super init];
if (self)
{
int r;
wrapper = w;
archive = a;
encoding = enc;
if ((r = archive_read_next_header(a, &entry)) != ARCHIVE_OK)
{
entry = NULL;
if (error)
{
if (r == ARCHIVE_EOF)
*error = nil;
else
*error = [ArchiveWrapper archiveError:archive code:r];
}
return nil;
}
entry = archive_entry_clone(entry);
if (!entry)
{
if (error)
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:nil];
return nil;
}
dataAvailable = YES;
data = nil;
}
return self;
}
- (void)dealloc
{
if (entry)
archive_entry_free (entry);
}
@synthesize entry;
@synthesize encoding;
- (BOOL)pathnameAvailable
{
return archive_entry_pathname (entry) != NULL;
}
- (NSString*)pathname
{
const char *pn = archive_entry_pathname (entry);
if (!pn)
[NSException raise:ArchiveMemberInfoNotAvailableException format:@"pathname is not set"];
return [NSString stringWithCString:pn encoding:encoding];
}
- (const char*)cPathname
{
const char *pn = archive_entry_pathname (entry);
if (!pn)
[NSException raise:ArchiveMemberInfoNotAvailableException format:@"pathname is not set"];
return pn;
}
- (BOOL)sizeAvailable
{
return archive_entry_size_is_set (entry);
}
- (int64_t)size
{
if (!archive_entry_size_is_set (entry))
[NSException raise:ArchiveMemberInfoNotAvailableException format:@"size is not set"];
return archive_entry_size (entry);
}
- (BOOL)fetchDataWithError:(NSError **)error
{
NSMutableData *mutableData;
const void *buf;
size_t len;
off_t offset;
int r;
if (data)
{
if (error)
*error = nil;
return YES;
}
if (!dataAvailable)
{
if (error)
*error = nil;
return NO;
}
if (self.sizeAvailable)
{
mutableData = [NSMutableData dataWithLength:(NSUInteger)self.size];
int idx = 0;
while ((r = archive_read_data_block (archive, &buf, &len, &offset)) == ARCHIVE_OK)
{
[mutableData replaceBytesInRange:(NSRange){(NSUInteger)offset, (NSUInteger)len} withBytes:buf];
if (++idx % 300 == 0 && wrapper)
wrapper.uncompressedOffset = archive_filter_bytes(archive, 0);
}
}
else
{
mutableData = [NSMutableData data];
int idx = 0;
while ((r = archive_read_data_block (archive, &buf, &len, &offset)) == ARCHIVE_OK)
{
if (offset > (off_t)[data length])
[mutableData increaseLengthBy:(NSUInteger)offset - [data length]];
[mutableData appendBytes:buf length:len];
if (++idx % 300 == 0 && wrapper)
wrapper.uncompressedOffset = archive_filter_bytes(archive, 0);
}
}
if (r != ARCHIVE_EOF && r != ARCHIVE_WARN)
{
if (error)
*error = [ArchiveWrapper archiveError:archive code:r];
return NO;
}
if (error)
{
if (r == ARCHIVE_WARN)
*error = [ArchiveWrapper archiveError:archive code:r];
else
*error = nil;
}
[self willChangeValueForKey:@"data"];
data = mutableData;
[self didChangeValueForKey:@"data"];
return YES;
}
- (BOOL)skipDataWithError:(NSError **)error
{
int r;
if (data)
{
if (error)
*error = nil;
return NO;
}
r = archive_read_data_skip (archive);
[self willChangeValueForKey:@"dataAvailable"];
dataAvailable = NO;
[self didChangeValueForKey:@"dataAvailable"];
if (wrapper)
wrapper.uncompressedOffset = archive_filter_bytes(archive, 0);
if (r != ARCHIVE_OK && r != ARCHIVE_WARN)
{
if (error)
*error = [ArchiveWrapper archiveError:archive code:r];
return NO;
}
if (r == ARCHIVE_WARN && error)
*error = [ArchiveWrapper archiveError:archive code:r];
return YES;
}
@synthesize dataAvailable;
- (NSData *)data
{
if (!data)
{
NSError *err = nil;
if (![self fetchDataWithError:&err])
{
if (err)
@throw [NSException exceptionWithName:ArchiveMemberDataNotAvailableException
reason:@"loadData failed"
userInfo:[NSDictionary dictionaryWithObject:err
forKey:NSUnderlyingErrorKey]];
return nil;
}
}
return data;
}
- (BOOL)extractToURL:(NSURL *)dst createDirectories:(BOOL)create error:(NSError **)error
{
if (!dataAvailable)
{
/* XXX Should probably use exception here. */
if (error)
*error = nil;
return NO;
}
if (create)
{
NSURL *dir = [dst URLByDeletingLastPathComponent];
if (![dir checkResourceIsReachableAndReturnError:nil])
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:[dir path] withIntermediateDirectories:YES attributes:nil error:error])
return NO;
}
}
if (data)
return [data writeToURL:dst options:NSDataWritingAtomic error:error];
[[NSFileManager defaultManager] createFileAtPath:[dst path] contents:nil attributes:nil];
NSFileHandle *fh = [NSFileHandle fileHandleForWritingToURL:dst error:error];
int r;
const void *buf;
size_t len;
off_t offset;
if (!fh)
return NO;
[self willChangeValueForKey:@"dataAvailable"];
dataAvailable = NO;
[self didChangeValueForKey:@"dataAvailable"];
int idx = 0;
while ((r = archive_read_data_block (archive, &buf, &len, &offset)) == ARCHIVE_OK)
{
if (offset > (off_t)[fh offsetInFile])
[fh truncateFileAtOffset:offset];
[fh writeData:[NSData dataWithBytesNoCopy:(void*)buf length:len freeWhenDone:NO]];
if (++idx % 300 == 0 && wrapper)
wrapper.uncompressedOffset = archive_filter_bytes(archive, 0);
}
[fh closeFile];
if (r != ARCHIVE_EOF && r != ARCHIVE_WARN)
{
if (error)
*error = [ArchiveWrapper archiveError:archive code:r];
return NO;
}
if (error)
{
if (r == ARCHIVE_WARN)
*error = [ArchiveWrapper archiveError:archive code:r];
else
*error = nil;
}
return YES;
}
@end
@implementation ArchiveWrapper
+ (ArchiveWrapper*)archiveForReadingFromURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
{
return [[self alloc] initForReadingFromURL:url encoding:enc error:error];
}
- (id)initForReadingFromURL:(NSURL *)url encoding:(NSStringEncoding)enc error:(NSError **)error
{
self = [self init];
if (self)
{
int r;
if (![url isFileURL])
{
/* XXX maybe use exception here. */
if (error)
*error = [ArchiveWrapper errorWithCode:ARCHIVE_FATAL eno:EINVAL string:@"Only file URLs supported for now"];
return nil;
}
archive = archive_read_new ();
archive_read_support_filter_all (archive);
archive_read_support_format_all (archive);
if ((r = archive_read_open_filename (archive, [[url path] fileSystemRepresentation],
10 * 1024) != ARCHIVE_OK))
{
if (error)
*error = [ArchiveWrapper archiveError:archive code:r];
if (r != ARCHIVE_WARN)
return nil;
}
encoding = enc;
lastMember = nil;
self.uncompressedOffset = archive_filter_bytes(archive, 0);
}
return self;
}
- (void)dealloc
{
if (archive)
archive_read_free (archive);
}
- (Class)memberClass
{
return [ArchiveMember class];
}
- (ArchiveMember *)nextMemberWithError:(NSError**)error
{
if (lastMember)
[lastMember skipDataWithError:error];
lastMember = [[[self memberClass] alloc] initWithWrapper:self archive:archive encoding:encoding error:error];
self.uncompressedOffset = archive_filter_bytes(archive, 0);
if (!lastMember)
archive_read_close (archive);
return lastMember;
}
- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])stackbuf count:(NSUInteger)len
{
ArchiveMember *res = [self nextMemberWithError:nil];
if (!state->state)
{
state->mutationsPtr = &state->extra[0];
state->state = 1;
}
if (!res)
return 0;
NSAssert(len >= 1, @"len < 1!?");
stackbuf[0] = res;
state->itemsPtr = stackbuf;
return 1;
}
@synthesize uncompressedOffset;
@end