-
Notifications
You must be signed in to change notification settings - Fork 419
/
HFFileReference.m
408 lines (352 loc) · 12 KB
/
HFFileReference.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
//
// HFFileReference.m
// HexFiend_2
//
// Copyright 2008 ridiculous_fish. All rights reserved.
//
#import <HexFiend/HFFileReference.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/disk.h>
#ifndef HF_NO_PRIVILEGED_FILE_OPERATIONS
#import "HFPrivilegedHelperConnection.h"
#endif
#define USE_STAT64 0
/* The return code is just to quiet the static analyzer */
static BOOL returnReadError(NSError **error) {
if (! error) return NO;
int posixCode = errno;
NSInteger cocoaCode = 0;
switch (posixCode) {
case ENOENT: cocoaCode = NSFileReadNoSuchFileError; break;
case EPERM:
case EACCES: cocoaCode = NSFileReadNoPermissionError; break;
case ENAMETOOLONG: cocoaCode = NSFileReadInvalidFileNameError; break;
}
if (cocoaCode != 0) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:cocoaCode userInfo:nil];
}
else {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:posixCode userInfo:nil];
}
return NO;
}
static BOOL returnUnsupportedFileTypeError(NSError **error, mode_t mode) {
if (! error) return NO;
printf("TYPE: %o\n", mode);
NSString *fileType;
if (S_ISBLK(mode)) {
fileType = @"special block file";
}
else if (S_ISCHR(mode)) {
fileType = @"special character file";
}
else if (S_ISDIR(mode)) {
fileType = @"directory";
}
else if (S_ISFIFO(mode)) {
fileType = @"named pipe (fifo)";
}
else if (S_ISSOCK(mode)) {
fileType = @"socket";
}
else if (S_ISWHT(mode)) {
fileType = @"whiteout";
}
else {
fileType = [NSString stringWithFormat:@"unknown type (mode 0x%lx)", (long)mode];
}
NSString *errorDescription = [NSString stringWithFormat:@"The file is a %@ which is not a supported type.", fileType];
NSDictionary *errorDict = [NSDictionary dictionaryWithObjectsAndKeys:errorDescription, NSLocalizedDescriptionKey, nil];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:errorDict];
return NO;
}
static BOOL returnFortunateSonError(NSError **error) {
if (! error) return NO;
NSString *errorDescription = @"There was an error communicating with the privileged helper process.";
NSDictionary *errorDict = [NSDictionary dictionaryWithObjectsAndKeys:errorDescription, NSLocalizedDescriptionKey, nil];
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:errorDict];
return NO;
}
static BOOL isFileTypeSupported(mode_t mode) {
/* We support regular and block file types */
return S_ISREG(mode) || S_ISBLK(mode) || S_ISCHR(mode);
}
static BOOL isFileTypeWritable(mode_t mode) {
/* We only support writing to regular files */
return S_ISREG(mode) || S_ISBLK(mode) || S_ISCHR(mode);
}
static BOOL returnFTruncateError(NSError **error) {
if (error) {
int posixCode = errno;
NSInteger cocoaCode = 0;
switch (posixCode) {
case ENOSPC: cocoaCode = NSFileWriteOutOfSpaceError; break;
case EROFS: cocoaCode = NSFileWriteVolumeReadOnlyError; break;
}
if (cocoaCode != 0) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:cocoaCode userInfo:nil];
}
else {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:posixCode userInfo:nil];
}
}
return YES;
}
@implementation HFFileReference
@synthesize isPrivileged, isFixedLength;
- (void)close { UNIMPLEMENTED_VOID(); }
- (void)readBytes:(unsigned char *)buff length:(NSUInteger)length from:(unsigned long long)offset {USE(buff); USE(length); USE(offset); UNIMPLEMENTED_VOID(); }
- (int)writeBytes:(const unsigned char *)buff length:(NSUInteger)length to:(unsigned long long)offset {USE(buff); USE(length); USE(offset); UNIMPLEMENTED(); }
- (BOOL)setLength:(unsigned long long)length error:(NSError **)error { USE(length); USE(error); UNIMPLEMENTED(); }
- (unsigned long long)length {
return fileLength;
}
/* Must be overridden - do not call super */
- (BOOL)initSharedWithPath:(NSString *)path error:(NSError **)error { USE(path); USE(error); UNIMPLEMENTED(); }
- (NSUInteger)hash {
return (NSUInteger)inode;
}
- (BOOL)isEqual:(id)val {
if (! [val isKindOfClass:[HFFileReference class]]) return NO;
HFFileReference *ref = (HFFileReference *)val;
return ref->device == device && ref->inode == inode;
}
+ allocWithZone:(NSZone *)zone {
if (self == [HFFileReference class]) {
/* Default to HFConcreteFileReference */
return [HFConcreteFileReference allocWithZone:zone];
}
else {
return [super allocWithZone:zone];
}
}
- (BOOL)validateWithError:(NSError **)error {
/* If this file is not a supported file type, then we fail validation */
if (! isFileTypeSupported(fileMode) || (isWritable && ! isFileTypeWritable(fileMode))) {
returnUnsupportedFileTypeError(error, fileMode);
return NO;
}
return YES;
}
- initWithPath:(NSString *)path error:(NSError **)error {
self = [super init];
isWritable = NO;
fileDescriptor = -1;
if (! ([self initSharedWithPath:path error:error] && [self validateWithError:error])) {
[self close];
[self release];
self = nil;
}
return self;
}
- initWritableWithPath:(NSString *)path error:(NSError **)error{
self = [super init];
isWritable = YES;
fileDescriptor = -1;
if (! ([self initSharedWithPath:path error:error] && [self validateWithError:error])) {
[self close];
[self release];
self = nil;
}
return self;
}
- (void)finalize {
[self close];
[super finalize];
}
- (void)dealloc {
[self close];
[super dealloc];
}
@end
@implementation HFConcreteFileReference
- (BOOL)initSharedWithPath:(NSString *)path error:(NSError **)error {
int result;
REQUIRE_NOT_NULL(path);
const char* p = [path fileSystemRepresentation];
if (isWritable) {
fileDescriptor = open(p, O_RDWR | O_CREAT, 0744);
}
else {
fileDescriptor = open(p, O_RDONLY, 0);
}
#ifndef HF_NO_PRIVILEGED_FILE_OPERATIONS
if (fileDescriptor < 0 && errno == EACCES) {
if ([[HFPrivilegedHelperConnection sharedConnection] openFileAtPath:p writable:isWritable fileDescriptor:&fileDescriptor error:error]) {
isPrivileged = YES;
} else {
fileDescriptor = -1;
errno = EACCES;
}
}
#endif
if (fileDescriptor < 0) {
returnReadError(error);
return NO;
}
#if USE_STAT64
struct stat64 sb;
result = fstat64(fileDescriptor, &sb);
#else
struct stat sb;
result = fstat(fileDescriptor, &sb);
#endif
if (result != 0) {
int err = errno;
returnReadError(error);
NSLog(@"Unable to fstat64 file %@. %s.", path, strerror(err));
return NO;
}
if (!sb.st_size && (S_ISCHR(sb.st_mode) || S_ISBLK(sb.st_mode))) {
uint64_t blockCount;
if (ioctl(fileDescriptor, DKIOCGETBLOCKSIZE, &blockSize) < 0
|| ioctl(fileDescriptor, DKIOCGETBLOCKCOUNT, &blockCount) < 0) {
int err = errno;
returnReadError(error);
NSLog(@"Unable to get block size/count file %@. %s.", path, strerror(err));
return NO;
}
fileLength = blockSize * blockCount;
isFixedLength = YES;
}
else {
fileLength = sb.st_size;
}
fileMode = sb.st_mode;
inode = sb.st_ino;
device = sb.st_dev;
HFSetFDShouldCache(fileDescriptor, NO);
return YES;
}
- (void)readBytes:(unsigned char*)buff length:(NSUInteger)length from:(unsigned long long)pos {
if (! length) return;
REQUIRE_NOT_NULL(buff);
HFASSERT(length <= LONG_MAX);
HFASSERT(pos <= fileLength);
HFASSERT(length <= fileLength - pos);
if (fileDescriptor < 0) [NSException raise:NSInvalidArgumentException format:@"File has already been closed."];
NSUInteger lastBlockLen = 0;
void *tempBuf = NULL;
if (S_ISCHR(fileMode) && blockSize) {
// We have to make sure all accesses are aligned
void *tempBuf = NULL;
unsigned prePad = (unsigned)(pos % blockSize);
if (prePad) {
// Deal with the first unaligned block
tempBuf = malloc(blockSize);
ssize_t result = pread(fileDescriptor, tempBuf, blockSize, pos - prePad);
if (result != (ssize_t)blockSize) {
[NSException raise:NSGenericException format:@"Read result: %d expected: %u error: %s", result, blockSize, strerror(errno)];
}
NSUInteger toCopy = blockSize - prePad;
if (toCopy > length)
toCopy = length;
memcpy(buff, tempBuf + prePad, toCopy);
length -= toCopy;
pos += toCopy;
buff += toCopy;
}
lastBlockLen = length % blockSize;
length -= lastBlockLen;
}
ssize_t result = pread(fileDescriptor, buff, length, pos);
if (result != (long)length) {
[NSException raise:NSGenericException format:@"Read result: %d expected: %u error: %s", result, length, strerror(errno)];
}
if (lastBlockLen) {
if (!tempBuf)
tempBuf = malloc(blockSize);
result = pread(fileDescriptor, tempBuf, blockSize, pos + length);
if (result != (ssize_t)blockSize) {
[NSException raise:NSGenericException format:@"Read result: %d expected: %u error: %s", result, blockSize, strerror(errno)];
}
memcpy(buff + length, tempBuf, lastBlockLen);
}
free (tempBuf);
}
- (int)writeBytes:(const unsigned char *)buff length:(NSUInteger)length to:(unsigned long long)offset {
HFASSERT(isWritable);
HFASSERT(fileDescriptor >= 0);
if (! length) return 0;
REQUIRE_NOT_NULL(buff);
HFASSERT(offset <= fileLength);
HFASSERT(length <= LONG_MAX);
HFASSERT(offset <= LLONG_MAX);
NSUInteger lastBlockLen = 0;
void *tempBuf = NULL;
if (S_ISCHR(fileMode) && blockSize) {
// We have to make sure all accesses are aligned
void *tempBuf = NULL;
unsigned prePad = (unsigned)(offset % blockSize);
if (prePad) {
// Deal with the first unaligned block
tempBuf = malloc(blockSize);
ssize_t result = pread(fileDescriptor, tempBuf, blockSize, offset - prePad);
if (result != (ssize_t)blockSize) {
[NSException raise:NSGenericException format:@"Read result: %d expected: %u error: %s", result, blockSize, strerror(errno)];
}
NSUInteger toCopy = blockSize - prePad;
if (toCopy > length)
toCopy = length;
memcpy(tempBuf + prePad, buff, toCopy);
result = pwrite(fileDescriptor, tempBuf, blockSize, offset - prePad);
if (result < 0)
return errno;
HFASSERT(result == (ssize_t)blockSize);
if (!(length -= toCopy))
return 0;
offset += toCopy;
buff += toCopy;
}
lastBlockLen = length % blockSize;
length -= lastBlockLen;
}
ssize_t result = pwrite(fileDescriptor, buff, (size_t)length, (off_t)offset);
if (result < 0)
return errno;
HFASSERT(result == (ssize_t)length);
if (lastBlockLen) {
offset += length;
buff += length;
if (!tempBuf)
tempBuf = malloc(blockSize);
result = pread(fileDescriptor, tempBuf, blockSize, offset);
if (result != (ssize_t)blockSize) {
[NSException raise:NSGenericException format:@"Read result: %d expected: %u error: %s", result, blockSize, strerror(errno)];
}
memcpy(tempBuf, buff, lastBlockLen);
result = pwrite(fileDescriptor, tempBuf, blockSize, offset);
if (result < 0)
return errno;
HFASSERT(result == (ssize_t)blockSize);
}
free(tempBuf);
return 0;
}
- (void)close {
if (fileDescriptor >= 0) {
close(fileDescriptor);
fileDescriptor = -1;
}
}
- (BOOL)setLength:(unsigned long long)length error:(NSError **)error {
HFASSERT(isWritable);
HFASSERT(fileDescriptor >= 0);
if (length > LLONG_MAX) { //largest file we can make is LLONG_MAX, because off_t has type long long
if (error) *error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteOutOfSpaceError userInfo:nil];
return NO;
}
int result = ftruncate(fileDescriptor, (off_t)length);
HFASSERT(result <= 0);
if (result < 0) {
returnFTruncateError(error);
}
else {
fileLength = length;
}
return result == 0;
}
@end