forked from osxfuse/framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GMUserFileSystem.m
2402 lines (2124 loc) · 85.4 KB
/
GMUserFileSystem.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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// GMUserFileSystem.m
// OSXFUSE
//
// Copyright (c) 2011-2016 Benjamin Fleischer.
// All rights reserved.
// OSXFUSE.framework is based on MacFUSE.framework. MacFUSE.framework is
// covered under the following BSD-style license:
//
// Copyright (c) 2007 Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// Based on FUSEFileSystem originally by alcor.
#import "GMUserFileSystem.h"
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <fuse/fuse_lowlevel.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/sysctl.h>
#include <sys/utsname.h>
#include <sys/vnode.h>
#import <Foundation/Foundation.h>
#import "GMFinderInfo.h"
#import "GMResourceFork.h"
#import "GMDataBackedFileDelegate.h"
#import "GMDTrace.h"
#define GM_EXPORT __attribute__((visibility("default")))
// Creates a dtrace-ready string with any newlines removed.
#define DTRACE_STRING(s) \
((char *)[[s stringByReplacingOccurrencesOfString:@"\n" withString:@" "] UTF8String])
// Operation Context
GM_EXPORT NSString* const kGMUserFileSystemContextUserIDKey = @"kGMUserFileSystemContextUserIDKey";
GM_EXPORT NSString* const kGMUserFileSystemContextGroupIDKey = @"kGMUserFileSystemContextGroupIDKey";
GM_EXPORT NSString* const kGMUserFileSystemContextProcessIDKey = @"kGMUserFileSystemContextProcessIDKey";
// Notifications
GM_EXPORT NSString* const kGMUserFileSystemErrorDomain = @"GMUserFileSystemErrorDomain";
GM_EXPORT NSString* const kGMUserFileSystemMountPathKey = @"mountPath";
GM_EXPORT NSString* const kGMUserFileSystemErrorKey = @"error";
GM_EXPORT NSString* const kGMUserFileSystemMountFailed = @"kGMUserFileSystemMountFailed";
GM_EXPORT NSString* const kGMUserFileSystemDidMount = @"kGMUserFileSystemDidMount";
GM_EXPORT NSString* const kGMUserFileSystemDidUnmount = @"kGMUserFileSystemDidUnmount";
// Attribute keys
GM_EXPORT NSString* const kGMUserFileSystemFileFlagsKey = @"kGMUserFileSystemFileFlagsKey";
GM_EXPORT NSString* const kGMUserFileSystemFileAccessDateKey = @"kGMUserFileSystemFileAccessDateKey";
GM_EXPORT NSString* const kGMUserFileSystemFileChangeDateKey = @"kGMUserFileSystemFileChangeDateKey";
GM_EXPORT NSString* const kGMUserFileSystemFileBackupDateKey = @"kGMUserFileSystemFileBackupDateKey";
GM_EXPORT NSString* const kGMUserFileSystemFileSizeInBlocksKey = @"kGMUserFileSystemFileSizeInBlocksKey";
GM_EXPORT NSString* const kGMUserFileSystemFileOptimalIOSizeKey = @"kGMUserFileSystemFileOptimalIOSizeKey";
GM_EXPORT NSString* const kGMUserFileSystemVolumeSupportsAllocateKey = @"kGMUserFileSystemVolumeSupportsAllocateKey";
GM_EXPORT NSString* const kGMUserFileSystemVolumeSupportsCaseSensitiveNamesKey = @"kGMUserFileSystemVolumeSupportsCaseSensitiveNamesKey";
GM_EXPORT NSString* const kGMUserFileSystemVolumeSupportsExchangeDataKey = @"kGMUserFileSystemVolumeSupportsExchangeDataKey";
GM_EXPORT NSString* const kGMUserFileSystemVolumeSupportsExtendedDatesKey = @"kGMUserFileSystemVolumeSupportsExtendedDatesKey";
GM_EXPORT NSString* const kGMUserFileSystemVolumeMaxFilenameLengthKey = @"kGMUserFileSystemVolumeMaxFilenameLengthKey";
GM_EXPORT NSString* const kGMUserFileSystemVolumeFileSystemBlockSizeKey = @"kGMUserFileSystemVolumeFileSystemBlockSizeKey";
// TODO: Remove comment on EXPORT if/when setvolname is supported.
/* GM_EXPORT */ NSString* const kGMUserFileSystemVolumeSupportsSetVolumeNameKey = @"kGMUserFileSystemVolumeSupportsSetVolumeNameKey";
/* GM_EXPORT */ NSString* const kGMUserFileSystemVolumeNameKey = @"kGMUserFileSystemVolumeNameKey";
// FinderInfo and ResourceFork keys
GM_EXPORT NSString* const kGMUserFileSystemFinderFlagsKey = @"kGMUserFileSystemFinderFlagsKey";
GM_EXPORT NSString* const kGMUserFileSystemFinderExtendedFlagsKey = @"kGMUserFileSystemFinderExtendedFlagsKey";
GM_EXPORT NSString* const kGMUserFileSystemCustomIconDataKey = @"kGMUserFileSystemCustomIconDataKey";
GM_EXPORT NSString* const kGMUserFileSystemWeblocURLKey = @"kGMUserFileSystemWeblocURLKey";
// Used for time conversions to/from tv_nsec.
static const double kNanoSecondsPerSecond = 1000000000.0;
typedef enum {
// Unable to unmount a dead FUSE files system located at mount point.
GMUserFileSystem_ERROR_UNMOUNT_DEADFS = 1000,
// Gave up waiting for system removal of existing dir in /Volumes/x after
// unmounting a dead FUSE file system.
GMUserFileSystem_ERROR_UNMOUNT_DEADFS_RMDIR = 1001,
// The mount point did not exist, and we were unable to mkdir it.
GMUserFileSystem_ERROR_MOUNT_MKDIR = 1002,
// fuse_main returned while trying to mount and don't know why.
GMUserFileSystem_ERROR_MOUNT_FUSE_MAIN_INTERNAL = 1003,
} GMUserFileSystemErrorCode;
typedef enum {
GMUserFileSystem_NOT_MOUNTED, // Not mounted.
GMUserFileSystem_MOUNTING, // In the process of mounting.
GMUserFileSystem_INITIALIZING, // Almost done mounting.
GMUserFileSystem_MOUNTED, // Confirmed to be mounted.
GMUserFileSystem_UNMOUNTING, // In the process of unmounting.
GMUserFileSystem_FAILURE, // Failed state; probably a mount failure.
} GMUserFileSystemStatus;
@interface GMUserFileSystemInternal : NSObject {
NSString* mountPath_;
GMUserFileSystemStatus status_;
BOOL shouldCheckForResource_; // Try to handle FinderInfo/Resource Forks?
BOOL isThreadSafe_; // Is the delegate thread-safe?
BOOL supportsAllocate_; // Delegate supports preallocation of files?
BOOL supportsCaseSensitiveNames_; // Delegate supports case sensitive names?
BOOL supportsExchangeData_; // Delegate supports exchange data?
BOOL supportsExtendedTimes_; // Delegate supports create and backup times?
BOOL supportsSetVolumeName_; // Delegate supports setvolname?
BOOL isReadOnly_; // Is this mounted read-only?
id delegate_;
}
- (id)initWithDelegate:(id)delegate isThreadSafe:(BOOL)isThreadSafe;
- (void)setDelegate:(id)delegate;
@end
@implementation GMUserFileSystemInternal
- (id)init {
return [self initWithDelegate:nil isThreadSafe:NO];
}
- (id)initWithDelegate:(id)delegate isThreadSafe:(BOOL)isThreadSafe {
self = [super init];
if (self) {
status_ = GMUserFileSystem_NOT_MOUNTED;
isThreadSafe_ = isThreadSafe;
supportsAllocate_ = NO;
supportsCaseSensitiveNames_ = YES;
supportsExchangeData_ = NO;
supportsExtendedTimes_ = NO;
supportsSetVolumeName_ = NO;
isReadOnly_ = NO;
[self setDelegate:delegate];
}
return self;
}
- (void)dealloc {
[mountPath_ release];
[super dealloc];
}
- (NSString *)mountPath { return mountPath_; }
- (void)setMountPath:(NSString *)mountPath {
[mountPath_ autorelease];
mountPath_ = [mountPath copy];
}
- (GMUserFileSystemStatus)status { return status_; }
- (void)setStatus:(GMUserFileSystemStatus)status { status_ = status; }
- (BOOL)isThreadSafe { return isThreadSafe_; }
- (BOOL)supportsAllocate { return supportsAllocate_; };
- (void)setSupportsAllocate:(BOOL)val { supportsAllocate_ = val; }
- (BOOL)supportsCaseSensitiveNames { return supportsCaseSensitiveNames_; }
- (void)setSupportsCaseSensitiveNames:(BOOL)val { supportsCaseSensitiveNames_ = val; }
- (BOOL)supportsExchangeData { return supportsExchangeData_; }
- (void)setSupportsExchangeData:(BOOL)val { supportsExchangeData_ = val; }
- (BOOL)supportsExtendedTimes { return supportsExtendedTimes_; }
- (void)setSupportsExtendedTimes:(BOOL)val { supportsExtendedTimes_ = val; }
- (BOOL)supportsSetVolumeName { return supportsSetVolumeName_; }
- (void)setSupportsSetVolumeName:(BOOL)val { supportsSetVolumeName_ = val; }
- (BOOL)shouldCheckForResource { return shouldCheckForResource_; }
- (BOOL)isReadOnly { return isReadOnly_; }
- (void)setIsReadOnly:(BOOL)val { isReadOnly_ = val; }
- (id)delegate { return delegate_; }
- (void)setDelegate:(id)delegate {
delegate_ = delegate;
shouldCheckForResource_ =
[delegate_ respondsToSelector:@selector(finderAttributesAtPath:error:)] ||
[delegate_ respondsToSelector:@selector(resourceAttributesAtPath:error:)];
// Check for deprecated methods.
SEL deprecatedMethods[] = {
@selector(createFileAtPath:attributes:userData:error:)
};
for (int i = 0; i < sizeof(deprecatedMethods) / sizeof(SEL); ++i) {
SEL sel = deprecatedMethods[i];
if ([delegate_ respondsToSelector:sel]) {
NSLog(@"*** WARNING: GMUserFileSystem delegate implements deprecated "
@"selector: %@", NSStringFromSelector(sel));
}
}
}
@end
// Deprecated delegate methods that we still support for backward compatibility
// with previously compiled file systems. This will be actively trimmed as
// new releases occur.
@interface NSObject (GMUserFileSystemDeprecated)
- (BOOL)createFileAtPath:(NSString *)path
attributes:(NSDictionary *)attributes
userData:(id *)userData
error:(NSError **)error;
@end
@interface GMUserFileSystem (GMUserFileSystemPrivate)
// The file system for the current thread. Valid only during a FUSE callback.
+ (GMUserFileSystem *)currentFS;
// Convenience method to creates an autoreleased NSError in the
// NSPOSIXErrorDomain. Filesystem errors returned by the delegate must be
// standard posix errno values.
+ (NSError *)errorWithCode:(int)code;
- (void)mount:(NSDictionary *)args;
- (void)waitUntilMounted:(NSNumber *)fileDescriptor;
- (NSDictionary *)finderAttributesAtPath:(NSString *)path;
- (NSDictionary *)resourceAttributesAtPath:(NSString *)path;
- (BOOL)hasCustomIconAtPath:(NSString *)path;
- (BOOL)isDirectoryIconAtPath:(NSString *)path dirPath:(NSString **)dirPath;
- (NSData *)finderDataForAttributes:(NSDictionary *)attributes;
- (NSData *)resourceDataForAttributes:(NSDictionary *)attributes;
- (NSDictionary *)defaultAttributesOfItemAtPath:(NSString *)path
userData:userData
error:(NSError **)error;
- (BOOL)fillStatBuffer:(struct stat *)stbuf
forPath:(NSString *)path
userData:(id)userData
error:(NSError **)error;
- (BOOL)fillStatfsBuffer:(struct statfs *)stbuf
forPath:(NSString *)path
error:(NSError **)error;
- (void)fuseInit;
- (void)fuseDestroy;
@end
@implementation GMUserFileSystem
+ (NSDictionary *)currentContext {
struct fuse_context* context = fuse_get_context();
if (!context) {
return nil;
}
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithUnsignedInt:context->uid]
forKey:kGMUserFileSystemContextUserIDKey];
[dict setObject:[NSNumber numberWithUnsignedInt:context->gid]
forKey:kGMUserFileSystemContextGroupIDKey];
[dict setObject:[NSNumber numberWithInt:context->pid]
forKey:kGMUserFileSystemContextProcessIDKey];
return [dict autorelease];
}
- (id)init {
return [self initWithDelegate:nil isThreadSafe:NO];
}
- (id)initWithDelegate:(id)delegate isThreadSafe:(BOOL)isThreadSafe {
self = [super init];
if (self) {
internal_ = [[GMUserFileSystemInternal alloc] initWithDelegate:delegate
isThreadSafe:isThreadSafe];
}
return self;
}
- (void)dealloc {
[internal_ release];
[super dealloc];
}
- (void)setDelegate:(id)delegate {
[internal_ setDelegate:delegate];
}
- (id)delegate {
return [internal_ delegate];
}
- (BOOL)enableAllocate {
return [internal_ supportsAllocate];
}
- (BOOL)enableCaseSensitiveNames {
return [internal_ supportsCaseSensitiveNames];
}
- (BOOL)enableExchangeData {
return [internal_ supportsExchangeData];
}
- (BOOL)enableExtendedTimes {
return [internal_ supportsExtendedTimes];
}
- (BOOL)enableSetVolumeName {
return [internal_ supportsSetVolumeName];
}
- (void)mountAtPath:(NSString *)mountPath
withOptions:(NSArray *)options {
[self mountAtPath:mountPath
withOptions:options
shouldForeground:YES
detachNewThread:YES];
}
- (void)mountAtPath:(NSString *)mountPath
withOptions:(NSArray *)options
shouldForeground:(BOOL)shouldForeground
detachNewThread:(BOOL)detachNewThread {
[internal_ setMountPath:mountPath];
NSMutableArray* optionsCopy = [NSMutableArray array];
for (int i = 0; i < [options count]; ++i) {
NSString* option = [options objectAtIndex:i];
NSString* optionLowercase = [option lowercaseString];
if ([optionLowercase compare:@"rdonly"] == NSOrderedSame ||
[optionLowercase compare:@"ro"] == NSOrderedSame) {
[internal_ setIsReadOnly:YES];
}
[optionsCopy addObject:[[option copy] autorelease]];
}
NSDictionary* args =
[[NSDictionary alloc] initWithObjectsAndKeys:
optionsCopy, @"options",
[NSNumber numberWithBool:shouldForeground], @"shouldForeground",
nil, nil];
if (detachNewThread) {
[NSThread detachNewThreadSelector:@selector(mount:)
toTarget:self
withObject:args];
} else {
[self mount:args];
}
}
- (void)unmount {
if ([internal_ status] == GMUserFileSystem_MOUNTED) {
NSArray* args = [NSArray arrayWithObjects:@"-v", [internal_ mountPath], nil];
NSTask* unmountTask = [NSTask launchedTaskWithLaunchPath:@"/sbin/umount"
arguments:args];
[unmountTask waitUntilExit];
}
}
+ (NSError *)errorWithCode:(int)code {
return [NSError errorWithDomain:NSPOSIXErrorDomain code:code userInfo:nil];
}
+ (GMUserFileSystem *)currentFS {
struct fuse_context* context = fuse_get_context();
assert(context);
return (GMUserFileSystem *)context->private_data;
}
#define FUSEDEVIOCGETHANDSHAKECOMPLETE _IOR('F', 2, u_int32_t)
static const int kMaxWaitForMountTries = 50;
static const int kWaitForMountUSleepInterval = 100000; // 100 ms
- (void)waitUntilMounted:(NSNumber *)fileDescriptor {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
for (int i = 0; i < kMaxWaitForMountTries; ++i) {
UInt32 handShakeComplete = 0;
int ret = ioctl([fileDescriptor intValue], FUSEDEVIOCGETHANDSHAKECOMPLETE,
&handShakeComplete);
if (ret == 0 && handShakeComplete) {
[internal_ setStatus:GMUserFileSystem_MOUNTED];
// Successfully mounted, so post notification.
NSDictionary* userInfo =
[NSDictionary dictionaryWithObjectsAndKeys:
[internal_ mountPath], kGMUserFileSystemMountPathKey,
nil];
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotificationName:kGMUserFileSystemDidMount object:self
userInfo:userInfo];
[pool release];
return;
}
usleep(kWaitForMountUSleepInterval);
}
// Tried for a long time and no luck :-(
// Unmount and report failure?
[pool release];
}
- (void)fuseInit {
[internal_ setStatus:GMUserFileSystem_INITIALIZING];
NSError* error = nil;
NSDictionary* attribs = [self attributesOfFileSystemForPath:@"/" error:&error];
if (attribs) {
NSNumber* supports = nil;
supports = [attribs objectForKey:kGMUserFileSystemVolumeSupportsAllocateKey];
if (supports) {
[internal_ setSupportsAllocate:[supports boolValue]];
}
supports = [attribs objectForKey:kGMUserFileSystemVolumeSupportsCaseSensitiveNamesKey];
if (supports) {
[internal_ setSupportsCaseSensitiveNames:[supports boolValue]];
}
supports = [attribs objectForKey:kGMUserFileSystemVolumeSupportsExchangeDataKey];
if (supports) {
[internal_ setSupportsExchangeData:[supports boolValue]];
}
supports = [attribs objectForKey:kGMUserFileSystemVolumeSupportsExtendedDatesKey];
if (supports) {
[internal_ setSupportsExtendedTimes:[supports boolValue]];
}
supports = [attribs objectForKey:kGMUserFileSystemVolumeSupportsSetVolumeNameKey];
if (supports) {
[internal_ setSupportsSetVolumeName:[supports boolValue]];
}
}
// The mount point won't actually show up until this winds its way
// back through the kernel after this routine returns. In order to post
// the kGMUserFileSystemDidMount notification we start a new thread that will
// poll until it is mounted.
struct fuse_context* context = fuse_get_context();
struct fuse_session* se = fuse_get_session(context->fuse);
struct fuse_chan* chan = fuse_session_next_chan(se, NULL);
int fd = fuse_chan_fd(chan);
[NSThread detachNewThreadSelector:@selector(waitUntilMounted:)
toTarget:self
withObject:[NSNumber numberWithInteger:fd]];
}
- (void)fuseDestroy {
if ([[internal_ delegate] respondsToSelector:@selector(willUnmount)]) {
[[internal_ delegate] willUnmount];
}
[internal_ setStatus:GMUserFileSystem_UNMOUNTING];
NSDictionary* userInfo =
[NSDictionary dictionaryWithObjectsAndKeys:
[internal_ mountPath], kGMUserFileSystemMountPathKey,
nil];
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center postNotificationName:kGMUserFileSystemDidUnmount object:self
userInfo:userInfo];
[internal_ setStatus:GMUserFileSystem_NOT_MOUNTED];
}
#pragma mark Finder Info, Resource Forks and HFS headers
- (NSDictionary *)finderAttributesAtPath:(NSString *)path {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(path));
}
UInt16 flags = 0;
// If a directory icon, we'll make invisible and update the path to parent.
if ([self isDirectoryIconAtPath:path dirPath:&path]) {
flags |= kIsInvisible;
}
id delegate = [internal_ delegate];
if ([delegate respondsToSelector:@selector(finderAttributesAtPath:error:)]) {
NSError* error = nil;
NSDictionary* dict = [delegate finderAttributesAtPath:path error:&error];
if (dict != nil) {
if ([dict objectForKey:kGMUserFileSystemCustomIconDataKey]) {
// They have custom icon data, so make sure the FinderFlags bit is set.
flags |= kHasCustomIcon;
}
if (flags != 0) {
// May need to update kGMUserFileSystemFinderFlagsKey if different.
NSNumber* finderFlags = [dict objectForKey:kGMUserFileSystemFinderFlagsKey];
if (finderFlags != nil) {
UInt16 tmp = (UInt16)[finderFlags longValue];
if (flags == tmp) {
return dict; // They already have our desired flags.
}
flags |= tmp;
}
// Doh! We need to create a new dict with the updated flags key.
NSMutableDictionary* newDict =
[NSMutableDictionary dictionaryWithDictionary:dict];
[newDict setObject:[NSNumber numberWithLong:flags]
forKey:kGMUserFileSystemFinderFlagsKey];
return newDict;
}
return dict;
}
// Fall through and create dictionary based on flags if necessary.
}
if (flags != 0) {
return [NSDictionary dictionaryWithObject:[NSNumber numberWithLong:flags]
forKey:kGMUserFileSystemFinderFlagsKey];
}
return nil;
}
- (NSDictionary *)resourceAttributesAtPath:(NSString *)path {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(path));
}
id delegate = [internal_ delegate];
if ([delegate respondsToSelector:@selector(resourceAttributesAtPath:error:)]) {
NSError* error = nil;
return [delegate resourceAttributesAtPath:path error:&error];
}
return nil;
}
- (BOOL)hasCustomIconAtPath:(NSString *)path {
if ([path isEqualToString:@"/"]) {
return NO; // For a volume icon they should use the volicon= option.
}
NSDictionary* finderAttribs = [self finderAttributesAtPath:path];
if (finderAttribs) {
NSNumber* finderFlags =
[finderAttribs objectForKey:kGMUserFileSystemFinderFlagsKey];
if (finderFlags) {
UInt16 flags = (UInt16)[finderFlags longValue];
return (flags & kHasCustomIcon) == kHasCustomIcon;
}
}
return NO;
}
- (BOOL)isDirectoryIconAtPath:(NSString *)path dirPath:(NSString **)dirPath {
NSString* name = [path lastPathComponent];
if ([name isEqualToString:@"Icon\r"]) {
if (dirPath) {
*dirPath = [path stringByDeletingLastPathComponent];
}
return YES;
}
return NO;
}
// If the given attribs dictionary contains any FinderInfo attributes then
// returns NSData for FinderInfo; otherwise returns nil.
- (NSData *)finderDataForAttributes:(NSDictionary *)attribs {
if (!attribs) {
return nil;
}
GMFinderInfo* info = [GMFinderInfo finderInfo];
BOOL attributeFound = NO; // Have we found at least one relevant attribute?
NSNumber* flags = [attribs objectForKey:kGMUserFileSystemFinderFlagsKey];
if (flags) {
attributeFound = YES;
[info setFlags:(UInt16)[flags longValue]];
}
NSNumber* extendedFlags =
[attribs objectForKey:kGMUserFileSystemFinderExtendedFlagsKey];
if (extendedFlags) {
attributeFound = YES;
[info setExtendedFlags:(UInt16)[extendedFlags longValue]];
}
NSNumber* typeCode = [attribs objectForKey:NSFileHFSTypeCode];
if (typeCode) {
attributeFound = YES;
[info setTypeCode:(OSType)[typeCode longValue]];
}
NSNumber* creatorCode = [attribs objectForKey:NSFileHFSCreatorCode];
if (creatorCode) {
attributeFound = YES;
[info setCreatorCode:(OSType)[creatorCode longValue]];
}
return attributeFound ? [info data] : nil;
}
// If the given attribs dictionary contains any ResourceFork attributes then
// returns NSData for the ResourceFork; otherwise returns nil.
- (NSData *)resourceDataForAttributes:(NSDictionary *)attribs {
if (!attribs) {
return nil;
}
GMResourceFork* fork = [GMResourceFork resourceFork];
BOOL attributeFound = NO; // Have we found at least one relevant attribute?
NSData* imageData = [attribs objectForKey:kGMUserFileSystemCustomIconDataKey];
if (imageData) {
attributeFound = YES;
[fork addResourceWithType:'icns'
resID:kCustomIconResource // -16455
name:nil
data:imageData];
}
NSURL* url = [attribs objectForKey:kGMUserFileSystemWeblocURLKey];
if (url) {
attributeFound = YES;
NSString* urlString = [url absoluteString];
NSData* data = [urlString dataUsingEncoding:NSUTF8StringEncoding];
[fork addResourceWithType:'url '
resID:256
name:nil
data:data];
}
return attributeFound ? [fork data] : nil;
}
#pragma mark Internal Stat Operations
- (BOOL)fillStatfsBuffer:(struct statfs *)stbuf
forPath:(NSString *)path
error:(NSError **)error {
NSDictionary* attributes = [self attributesOfFileSystemForPath:path error:error];
if (!attributes) {
return NO;
}
// Block size
NSNumber* blocksize = [attributes objectForKey:kGMUserFileSystemVolumeFileSystemBlockSizeKey];
assert(blocksize);
stbuf->f_bsize = (uint32_t)[blocksize unsignedIntValue];
stbuf->f_iosize = (int32_t)[blocksize intValue];
// Size in blocks
NSNumber* size = [attributes objectForKey:NSFileSystemSize];
assert(size);
stbuf->f_blocks = (uint64_t)([size unsignedLongLongValue] / stbuf->f_bsize);
// Number of free / available blocks
NSNumber* freeSize = [attributes objectForKey:NSFileSystemFreeSize];
assert(freeSize);
stbuf->f_bavail = stbuf->f_bfree =
(uint64_t)([freeSize unsignedLongLongValue] / stbuf->f_bsize);
// Number of nodes
NSNumber* numNodes = [attributes objectForKey:NSFileSystemNodes];
assert(numNodes);
stbuf->f_files = (uint64_t)[numNodes unsignedLongLongValue];
// Number of free / available nodes
NSNumber* freeNodes = [attributes objectForKey:NSFileSystemFreeNodes];
assert(freeNodes);
stbuf->f_ffree = (uint64_t)[freeNodes unsignedLongLongValue];
return YES;
}
- (BOOL)fillStatBuffer:(struct stat *)stbuf
forPath:(NSString *)path
userData:(id)userData
error:(NSError **)error {
NSDictionary* attributes = [self defaultAttributesOfItemAtPath:path
userData:userData
error:error];
if (!attributes) {
return NO;
}
// Inode
NSNumber* inode = [attributes objectForKey:NSFileSystemFileNumber];
if (inode) {
stbuf->st_ino = [inode longLongValue];
}
// Permissions (mode)
NSNumber* perm = [attributes objectForKey:NSFilePosixPermissions];
stbuf->st_mode = [perm longValue];
NSString* fileType = [attributes objectForKey:NSFileType];
if ([fileType isEqualToString:NSFileTypeDirectory ]) {
stbuf->st_mode |= S_IFDIR;
} else if ([fileType isEqualToString:NSFileTypeRegular]) {
stbuf->st_mode |= S_IFREG;
} else if ([fileType isEqualToString:NSFileTypeSymbolicLink]) {
stbuf->st_mode |= S_IFLNK;
} else {
*error = [GMUserFileSystem errorWithCode:EFTYPE];
return NO;
}
// Owner and Group
// Note that if the owner or group IDs are not specified, the effective
// user and group IDs for the current process are used as defaults.
NSNumber* uid = [attributes objectForKey:NSFileOwnerAccountID];
NSNumber* gid = [attributes objectForKey:NSFileGroupOwnerAccountID];
stbuf->st_uid = uid ? [uid longValue] : geteuid();
stbuf->st_gid = gid ? [gid longValue] : getegid();
// nlink
NSNumber* nlink = [attributes objectForKey:NSFileReferenceCount];
stbuf->st_nlink = [nlink longValue];
// flags
NSNumber* flags = [attributes objectForKey:kGMUserFileSystemFileFlagsKey];
if (flags) {
stbuf->st_flags = [flags longValue];
} else {
// Just in case they tried to use NSFileImmutable or NSFileAppendOnly
NSNumber* immutableFlag = [attributes objectForKey:NSFileImmutable];
if (immutableFlag && [immutableFlag boolValue]) {
stbuf->st_flags |= UF_IMMUTABLE;
}
NSNumber* appendFlag = [attributes objectForKey:NSFileAppendOnly];
if (appendFlag && [appendFlag boolValue]) {
stbuf->st_flags |= UF_APPEND;
}
}
// Note: We default atime, ctime to mtime if it is provided.
NSDate* mdate = [attributes objectForKey:NSFileModificationDate];
if (mdate) {
const double seconds_dp = [mdate timeIntervalSince1970];
const time_t t_sec = (time_t) seconds_dp;
const double nanoseconds_dp = ((seconds_dp - t_sec) * kNanoSecondsPerSecond);
const long t_nsec = (nanoseconds_dp > 0 ) ? nanoseconds_dp : 0;
stbuf->st_mtimespec.tv_sec = t_sec;
stbuf->st_mtimespec.tv_nsec = t_nsec;
stbuf->st_atimespec = stbuf->st_mtimespec; // Default to mtime
stbuf->st_ctimespec = stbuf->st_mtimespec; // Default to mtime
}
NSDate* adate = [attributes objectForKey:kGMUserFileSystemFileAccessDateKey];
if (adate) {
const double seconds_dp = [adate timeIntervalSince1970];
const time_t t_sec = (time_t) seconds_dp;
const double nanoseconds_dp = ((seconds_dp - t_sec) * kNanoSecondsPerSecond);
const long t_nsec = (nanoseconds_dp > 0 ) ? nanoseconds_dp : 0;
stbuf->st_atimespec.tv_sec = t_sec;
stbuf->st_atimespec.tv_nsec = t_nsec;
}
NSDate* cdate = [attributes objectForKey:kGMUserFileSystemFileChangeDateKey];
if (cdate) {
const double seconds_dp = [cdate timeIntervalSince1970];
const time_t t_sec = (time_t) seconds_dp;
const double nanoseconds_dp = ((seconds_dp - t_sec) * kNanoSecondsPerSecond);
const long t_nsec = (nanoseconds_dp > 0 ) ? nanoseconds_dp : 0;
stbuf->st_ctimespec.tv_sec = t_sec;
stbuf->st_ctimespec.tv_nsec = t_nsec;
}
#ifdef _DARWIN_USE_64_BIT_INODE
NSDate* bdate = [attributes objectForKey:NSFileCreationDate];
if (bdate) {
const double seconds_dp = [bdate timeIntervalSince1970];
const time_t t_sec = (time_t) seconds_dp;
const double nanoseconds_dp = ((seconds_dp - t_sec) * kNanoSecondsPerSecond);
const long t_nsec = (nanoseconds_dp > 0 ) ? nanoseconds_dp : 0;
stbuf->st_birthtimespec.tv_sec = t_sec;
stbuf->st_birthtimespec.tv_nsec = t_nsec;
}
#endif
// File size
// Note that the actual file size of a directory depends on the internal
// representation of directories in the particular file system. In general
// this is not the combined size of the files in that directory.
NSNumber* size = [attributes objectForKey:NSFileSize];
if (size) {
stbuf->st_size = [size longLongValue];
}
// Set the number of blocks used so that Finder will display size on disk
// properly. The man page says that this is in terms of 512 byte blocks.
NSNumber* blocks = [attributes objectForKey:kGMUserFileSystemFileSizeInBlocksKey];
if (blocks) {
stbuf->st_blocks = [blocks longLongValue];
} else if (stbuf->st_size > 0) {
stbuf->st_blocks = stbuf->st_size / 512;
if (stbuf->st_size % 512) {
++(stbuf->st_blocks);
}
}
// Optimal file I/O size
NSNumber *ioSize = [attributes objectForKey:kGMUserFileSystemFileOptimalIOSizeKey];
if (ioSize) {
stbuf->st_blksize = [ioSize intValue];
}
return YES;
}
#pragma mark Creating an Item
- (BOOL)createDirectoryAtPath:(NSString *)path
attributes:(NSDictionary *)attributes
error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
NSMutableString* traceinfo =
[NSMutableString stringWithFormat:@"%@ [%@]", path, attributes];
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(traceinfo));
}
if ([[internal_ delegate] respondsToSelector:@selector(createDirectoryAtPath:attributes:error:)]) {
return [[internal_ delegate] createDirectoryAtPath:path attributes:attributes error:error];
}
*error = [GMUserFileSystem errorWithCode:EACCES];
return NO;
}
- (BOOL)createFileAtPath:(NSString *)path
attributes:(NSDictionary *)attributes
flags:(int)flags
userData:(id *)userData
error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
NSString* traceinfo = [NSString stringWithFormat:@"%@ [%@]", path, attributes];
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(traceinfo));
}
if ([[internal_ delegate] respondsToSelector:@selector(createFileAtPath:attributes:flags:userData:error:)]) {
return [[internal_ delegate] createFileAtPath:path
attributes:attributes
flags:flags
userData:userData
error:error];
} else if ([[internal_ delegate] respondsToSelector:@selector(createFileAtPath:attributes:userData:error:)]) {
return [[internal_ delegate] createFileAtPath:path
attributes:attributes
userData:userData
error:error];
}
*error = [GMUserFileSystem errorWithCode:EACCES];
return NO;
}
#pragma mark Removing an Item
- (BOOL)removeDirectoryAtPath:(NSString *)path error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(path));
}
if ([[internal_ delegate] respondsToSelector:@selector(removeDirectoryAtPath:error:)]) {
return [[internal_ delegate] removeDirectoryAtPath:path error:error];
}
return [self removeItemAtPath:path error:error];
}
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(path));
}
if ([[internal_ delegate] respondsToSelector:@selector(removeItemAtPath:error:)]) {
return [[internal_ delegate] removeItemAtPath:path error:error];
}
*error = [GMUserFileSystem errorWithCode:EACCES];
return NO;
}
#pragma mark Moving an Item
- (BOOL)moveItemAtPath:(NSString *)source
toPath:(NSString *)destination
error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
NSString* traceinfo =
[NSString stringWithFormat:@"%@ -> %@", source, destination];
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(traceinfo));
}
if ([[internal_ delegate] respondsToSelector:@selector(moveItemAtPath:toPath:error:)]) {
return [[internal_ delegate] moveItemAtPath:source toPath:destination error:error];
}
*error = [GMUserFileSystem errorWithCode:EACCES];
return NO;
}
#pragma mark Linking an Item
- (BOOL)linkItemAtPath:(NSString *)path
toPath:(NSString *)otherPath
error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
NSString* traceinfo = [NSString stringWithFormat:@"%@ -> %@", path, otherPath];
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(traceinfo));
}
if ([[internal_ delegate] respondsToSelector:@selector(linkItemAtPath:toPath:error:)]) {
return [[internal_ delegate] linkItemAtPath:path toPath:otherPath error:error];
}
*error = [GMUserFileSystem errorWithCode:ENOTSUP]; // Note: error not in man page.
return NO;
}
#pragma mark Symbolic Links
- (BOOL)createSymbolicLinkAtPath:(NSString *)path
withDestinationPath:(NSString *)otherPath
error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
NSString* traceinfo = [NSString stringWithFormat:@"%@ -> %@", path, otherPath];
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(traceinfo));
}
if ([[internal_ delegate] respondsToSelector:@selector(createSymbolicLinkAtPath:withDestinationPath:error:)]) {
return [[internal_ delegate] createSymbolicLinkAtPath:path
withDestinationPath:otherPath
error:error];
}
*error = [GMUserFileSystem errorWithCode:ENOTSUP]; // Note: error not in man page.
return NO;
}
- (NSString *)destinationOfSymbolicLinkAtPath:(NSString *)path
error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(path));
}
if ([[internal_ delegate] respondsToSelector:@selector(destinationOfSymbolicLinkAtPath:error:)]) {
return [[internal_ delegate] destinationOfSymbolicLinkAtPath:path error:error];
}
*error = [GMUserFileSystem errorWithCode:ENOENT];
return nil;
}
#pragma mark Directory Contents
- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(path));
}
NSArray* contents = nil;
if ([[internal_ delegate] respondsToSelector:@selector(contentsOfDirectoryAtPath:error:)]) {
contents = [[internal_ delegate] contentsOfDirectoryAtPath:path error:error];
} else if ([path isEqualToString:@"/"]) {
contents = [NSArray array]; // Give them an empty root directory for free.
}
return contents;
}
#pragma mark File Contents
// Note: Only call this if the delegate does indeed support this method.
- (NSData *)contentsAtPath:(NSString *)path {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(path));
}
id delegate = [internal_ delegate];
return [delegate contentsAtPath:path];
}
- (BOOL)openFileAtPath:(NSString *)path
mode:(int)mode
userData:(id *)userData
error:(NSError **)error {
if (OSXFUSE_OBJC_DELEGATE_ENTRY_ENABLED()) {
NSString* traceinfo = [NSString stringWithFormat:@"%@, mode=0x%x", path, mode];
OSXFUSE_OBJC_DELEGATE_ENTRY(DTRACE_STRING(traceinfo));
}