-
Notifications
You must be signed in to change notification settings - Fork 92
/
KxSMBProvider.m
2532 lines (1985 loc) · 79.2 KB
/
KxSMBProvider.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
//
// KxSambaProvider.m
// kxsmb project
// https://github.com/kolyvan/kxsmb/
//
// Created by Kolyvan on 28.03.13.
//
/*
Copyright (c) 2013 Konstantin Bukreev All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- 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.
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 HOLDER 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.
*/
#import "KxSMBProvider.h"
#import "libsmbclient.h"
#import "talloc_stack.h"
///////////////////////////////////////////////////////////////////////////////
NSString * const KxSMBErrorDomain = @"ru.kolyvan.KxSMB";
static NSString * KxSMBErrorMessage (KxSMBError errorCode)
{
switch (errorCode) {
case KxSMBErrorUnknown: return NSLocalizedString(@"SMB Error", nil);
case KxSMBErrorInvalidArg: return NSLocalizedString(@"SMB Invalid argument", nil);
case KxSMBErrorInvalidProtocol: return NSLocalizedString(@"SMB Invalid protocol", nil);
case KxSMBErrorOutOfMemory: return NSLocalizedString(@"SMB Out of memory", nil);
case KxSMBErrorAccessDenied: return NSLocalizedString(@"SMB Access Denied", nil);
case KxSMBErrorInvalidPath: return NSLocalizedString(@"SMB No such file or directory", nil);
case KxSMBErrorPathIsNotDir: return NSLocalizedString(@"SMB Not a directory", nil);
case KxSMBErrorPathIsDir: return NSLocalizedString(@"SMB Is a directory", nil);
case KxSMBErrorWorkgroupNotFound: return NSLocalizedString(@"SMB Workgroup not found", nil);
case KxSMBErrorShareDoesNotExist: return NSLocalizedString(@"SMB Share does not exist", nil);
case KxSMBErrorItemAlreadyExists: return NSLocalizedString(@"SMB Item already exists", nil);
case KxSMBErrorDirNotEmpty: return NSLocalizedString(@"SMB Directory not empty", nil);
case KxSMBErrorFileIO: return NSLocalizedString(@"SMB File I/O failure", nil);
case KxSMBErrorConnRefused: return NSLocalizedString(@"SMB Connection refused", nil);
case KxSMBErrorOpNotPermited: return NSLocalizedString(@"SMB Operation not permitted", nil);
}
}
static NSError * mkKxSMBError(KxSMBError error, NSString *format, ...)
{
NSDictionary *userInfo = nil;
NSString *reason = nil;
if (format) {
va_list args;
va_start(args, format);
reason = [[NSString alloc] initWithFormat:format arguments:args];
va_end(args);
}
if (reason) {
userInfo = @{
NSLocalizedDescriptionKey : KxSMBErrorMessage(error),
NSLocalizedFailureReasonErrorKey : reason
};
} else {
userInfo = @{ NSLocalizedDescriptionKey : KxSMBErrorMessage(error) };
}
return [NSError errorWithDomain:KxSMBErrorDomain
code:error
userInfo:userInfo];
}
static KxSMBError errnoToSMBErr(int err)
{
switch (err) {
case EINVAL: return KxSMBErrorInvalidArg;
case ENOMEM: return KxSMBErrorOutOfMemory;
case EACCES: return KxSMBErrorAccessDenied;
case ENOENT: return KxSMBErrorInvalidPath;
case ENOTDIR: return KxSMBErrorPathIsNotDir;
case EISDIR: return KxSMBErrorPathIsDir;
case EPERM: return KxSMBErrorOpNotPermited;
case ENODEV: return KxSMBErrorShareDoesNotExist;
case EEXIST: return KxSMBErrorItemAlreadyExists;
case ENOTEMPTY: return KxSMBErrorDirNotEmpty;
case ECONNREFUSED: return KxSMBErrorConnRefused;
default: return KxSMBErrorUnknown;
}
}
///////////////////////////////////////////////////////////////////////////////
@implementation KxSMBAuth
+ (instancetype) smbAuthWorkgroup:(NSString *)workgroup
username:(NSString *)username
password:(NSString *)password
{
KxSMBAuth *auth = [[KxSMBAuth alloc] init];
auth.workgroup = workgroup;
auth.username = username;
auth.password = password;
return auth;
}
@end
///////////////////////////////////////////////////////////////////////////////
@interface KxSMBItemStat ()
@property(readwrite, nonatomic, strong) NSDate *lastModified;
@property(readwrite, nonatomic, strong) NSDate *lastAccess;
@property(readwrite, nonatomic, strong) NSDate *creationTime;
@property(readwrite, nonatomic) SInt64 size;
@property(readwrite, nonatomic) UInt16 mode;
@end
@implementation KxSMBItemStat
@end
@implementation KxSMBItem
- (id) initWithType:(KxSMBItemType) type
path:(NSString *) path
stat:(KxSMBItemStat *)stat
auth:(KxSMBAuth *)auth
{
self = [super init];
if (self) {
_type = type;
_path = path;
_stat = stat;
_auth = auth;
}
return self;
}
- (NSString *) description
{
NSString *stype = @"";
switch (_type) {
case KxSMBItemTypeUnknown: stype = @"?"; break;
case KxSMBItemTypeWorkgroup: stype = @"group"; break;
case KxSMBItemTypeServer: stype = @"server"; break;
case KxSMBItemTypeFileShare: stype = @"fileshare"; break;
case KxSMBItemTypePrinter: stype = @"printer"; break;
case KxSMBItemTypeComms: stype = @"comms"; break;
case KxSMBItemTypeIPC: stype = @"ipc"; break;
case KxSMBItemTypeDir: stype = @"dir"; break;
case KxSMBItemTypeFile: stype = @"file"; break;
case KxSMBItemTypeLink: stype = @"link"; break;
}
return [NSString stringWithFormat:@"<smb %@ '%@' %lld>",
stype, _path, _stat.size];
}
@end
///////////////////////////////////////////////////////////////////////////////
static void my_smbc_get_auth_data_fn(const char *srv,
const char *shr,
char *workgroup, int wglen,
char *username, int unlen,
char *password, int pwlen);
static void my_smbc_get_auth_data_with_context_fn(SMBCCTX *c,
const char *srv,
const char *shr,
char *wg, int wglen,
char *un, int unlen,
char *pw, int pwlen);
///////////////////////////////////////////////////////////////////////////////
@interface KxSMBItemFile()
- (id) createFile:(BOOL)overwrite;
@end
///////////////////////////////////////////////////////////////////////////////
@implementation KxSMBConfig
- (id) init
{
if ((self = [super init])) {
_timeout = 10000; // ms
#ifdef DEBUG
_debugLevel = 1;
#else
_debugLevel = 0;
#endif
_debugToStderr = YES;
_fullTimeNames = YES;
_shareMode = KxSMBConfigShareModeDenyNone;
_encryptionLevel = KxSMBConfigEncryptLevelNone;
_caseSensitive = NO;
_browseMaxLmbCount = 3;
_urlEncodeReaddirEntries = NO;
_oneSharePerServer = NO;
_useKerberos = NO;
_fallbackAfterKerberos = YES;
_noAutoAnonymousLogin = NO;
_useCCache = NO;
_useNTHash = NO;
}
return self;
}
- (void) configureSmbContext:(SMBCCTX *)smbContext
{
smbc_setTimeout(smbContext, (int)_timeout);
smbc_setDebug(smbContext, (int)_debugLevel);
smbc_setOptionDebugToStderr(smbContext, (smbc_bool)_debugToStderr);
smbc_setOptionFullTimeNames(smbContext, (smbc_bool)_fullTimeNames);
smbc_setOptionOpenShareMode(smbContext, (smbc_share_mode)_shareMode);
smbc_setOptionSmbEncryptionLevel(smbContext, (smbc_smb_encrypt_level)_encryptionLevel);
smbc_setOptionCaseSensitive(smbContext, (smbc_bool)_caseSensitive);
smbc_setOptionBrowseMaxLmbCount(smbContext, (int)_browseMaxLmbCount);
smbc_setOptionUrlEncodeReaddirEntries(smbContext, (smbc_bool)_urlEncodeReaddirEntries);
smbc_setOptionOneSharePerServer(smbContext, (smbc_bool)_oneSharePerServer);
smbc_setOptionUseKerberos(smbContext, (smbc_bool)_useKerberos);
smbc_setOptionFallbackAfterKerberos(smbContext, (smbc_bool)_fallbackAfterKerberos);
smbc_setOptionNoAutoAnonymousLogin(smbContext, (smbc_bool)_noAutoAnonymousLogin);
smbc_setOptionUseCCache(smbContext, (smbc_bool)_useCCache);
smbc_setOptionUseNTHash(smbContext, (smbc_bool)_useNTHash);
if (_netbiosName.length) {
smbc_setNetbiosName(smbContext, (char *)_netbiosName.UTF8String);
}
if (_workgroup.length) {
smbc_setWorkgroup(smbContext, (char *)_workgroup.UTF8String);
}
if (_username.length) {
smbc_setUser(smbContext, (char *)_username.UTF8String);
}
}
@end
///////////////////////////////////////////////////////////////////////////////
static KxSMBProvider *gSmbProvider;
@interface KxSMBProvider ()
@end
@implementation KxSMBProvider {
dispatch_queue_t _dispatchQueue;
}
+ (instancetype) sharedSmbProvider
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
gSmbProvider = [[KxSMBProvider alloc] init];
});
return gSmbProvider;
}
- (id) init
{
NSAssert(!gSmbProvider, @"singleton object");
self = [super init];
if (self) {
_config = [KxSMBConfig new];
_dispatchQueue = dispatch_queue_create("KxSMBProvider", DISPATCH_QUEUE_SERIAL);
_completionQueue = dispatch_get_main_queue();
}
return self;
}
- (void) dealloc
{
if (_dispatchQueue) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000
dispatch_release(_dispatchQueue);
#endif
_dispatchQueue = NULL;
}
}
#pragma mark - class methods
+ (SMBCCTX *) openSmbContext:(KxSMBAuth *)auth
{
//NSParameterAssert(auth);
SMBCCTX *smbContext = smbc_new_context();
if (!smbContext) {
return NULL;
}
if (auth) {
smbc_setFunctionAuthDataWithContext(smbContext, my_smbc_get_auth_data_with_context_fn);
smbc_setOptionUserData(smbContext, (void *)CFBridgingRetain(auth));
} else {
smbc_setFunctionAuthData(smbContext, my_smbc_get_auth_data_fn);
}
KxSMBConfig *cfg = [KxSMBProvider sharedSmbProvider].config;
[cfg configureSmbContext:smbContext];
if (!smbc_init_context(smbContext)) {
void *userdata = smbc_getOptionUserData(smbContext);
if (userdata) {
CFBridgingRelease(userdata);
}
smbc_free_context(smbContext, NO);
return NULL;
}
smbc_set_context(smbContext);
return smbContext;
}
+ (void) closeSmbContext:(SMBCCTX *)smbContext
{
if (smbContext) {
void *userdata = smbc_getOptionUserData(smbContext);
if (userdata) {
CFBridgingRelease(userdata);
}
// fixes warning: no talloc stackframe at libsmb/cliconnect.c:2637, leaking memory
TALLOC_CTX *frame = talloc_stackframe();
smbc_getFunctionPurgeCachedServers(smbContext)(smbContext);
TALLOC_FREE(frame);
smbc_free_context(smbContext, NO);
}
}
+ (id) fetchTreeAtPath:(NSString *)path
auth:(KxSMBAuth *)auth
{
NSParameterAssert(path);
SMBCCTX *smbContext = [self openSmbContext:auth];
if (!smbContext) {
const int err = errno;
return mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable init SMB context (errno:%d)", nil), err);
}
id result = nil;
SMBCFILE *smbFile = smbc_getFunctionOpendir(smbContext)(smbContext, path.UTF8String);
if (smbFile) {
NSMutableArray *ma = [NSMutableArray array];
struct smbc_dirent *dirent;
smbc_readdir_fn readdirFn = smbc_getFunctionReaddir(smbContext);
while((dirent = readdirFn(smbContext, smbFile)) != NULL) {
if (!dirent->name) continue;
if (!strlen(dirent->name)) continue;
if (!strcmp(dirent->name, ".") || !strcmp(dirent->name, "..") || !strcmp(dirent->name, "IPC$")) continue;
NSString *name = [NSString stringWithUTF8String:dirent->name];
NSString *itemPath;
if ([path characterAtIndex:path.length-1] == '/')
itemPath = [path stringByAppendingString:name] ;
else
itemPath = [NSString stringWithFormat:@"%@/%@", path, name];
KxSMBItemStat *stat = nil;
if (dirent->smbc_type != SMBC_WORKGROUP &&
dirent->smbc_type != SMBC_SERVER) {
id r = [self fetchStat:smbContext atPath:itemPath];
if ([r isKindOfClass:[KxSMBItemStat class]]) {
stat = r;
}
}
switch(dirent->smbc_type)
{
case SMBC_WORKGROUP:
case SMBC_SERVER: {
KxSMBItem *item = [[KxSMBItemTree alloc] initWithType:dirent->smbc_type
path:[NSString stringWithFormat:@"smb://%@", name]
stat:nil
auth:auth];
[ma addObject:item];
break;
}
case SMBC_FILE_SHARE:
case SMBC_IPC_SHARE:
case SMBC_DIR: {
KxSMBItem *item = [[KxSMBItemTree alloc] initWithType:dirent->smbc_type
path:itemPath
stat:stat
auth:auth];
[ma addObject:item];
break;
}
case SMBC_FILE: {
KxSMBItem *item = [[KxSMBItemFile alloc] initWithType:KxSMBItemTypeFile
path:itemPath
stat:stat
auth:auth];
[ma addObject:item];
break;
}
case SMBC_PRINTER_SHARE:
case SMBC_COMMS_SHARE:
case SMBC_LINK: {
KxSMBItem *item = [[KxSMBItem alloc] initWithType:dirent->smbc_type
path:itemPath
stat:stat
auth:auth];
[ma addObject:item];
break;
}
}
}
smbc_getFunctionClose(smbContext)(smbContext, smbFile);
result = [ma copy];
} else {
const int err = errno;
result = mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable open dir:%@ (errno:%d)", nil), path, err);
}
[self closeSmbContext:smbContext];
return result;
}
+ (id) fetchStat:(SMBCCTX *)smbContext
atPath:(NSString *)path
{
NSParameterAssert(smbContext);
NSParameterAssert(path);
struct stat st;
int r = smbc_getFunctionStat(smbContext)(smbContext, path.UTF8String, &st);
if (r < 0) {
const int err = errno;
return mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable get stat:%@ (errno:%d)", nil), path, err);
}
KxSMBItemStat *stat = [[KxSMBItemStat alloc] init];
stat.lastModified = [NSDate dateWithTimeIntervalSince1970: st.st_mtime];
stat.lastAccess = [NSDate dateWithTimeIntervalSince1970: st.st_atime];
stat.creationTime = [NSDate dateWithTimeIntervalSince1970: st.st_ctime];
stat.size = st.st_size;
stat.mode = st.st_mode;
return stat;
}
+ (id) fetchAtPath:(NSString *)path
expandDir:(BOOL)expandDir
auth:(KxSMBAuth *)auth
{
NSParameterAssert(path);
if (![path hasPrefix:@"smb://"]) {
return mkKxSMBError(KxSMBErrorInvalidProtocol,
NSLocalizedString(@"Path:%@", nil), path);
}
NSString *sPath = [path substringFromIndex:@"smb://".length];
if (!sPath.length) {
return [self fetchTreeAtPath:path auth:auth];
}
if ([sPath hasSuffix:@"/"]) {
sPath = [sPath substringToIndex:sPath.length - 1];
}
if (sPath.pathComponents.count == 1) {
// smb:// or smb://server/ or smb://workgroup/
return [self fetchTreeAtPath:path auth:auth];
}
id result = nil;
SMBCCTX *smbContext = [self openSmbContext:auth];
if (!smbContext) {
const int err = errno;
return mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable init SMB context (errno:%d)", nil), err);
}
result = [self fetchStat:smbContext atPath:path];
if ([result isKindOfClass:[KxSMBItemStat class]]) {
KxSMBItemStat *stat = result;
if (S_ISDIR(stat.mode)) {
if (expandDir) {
result = [self fetchTreeAtPath:path auth:auth];
} else {
result = [[KxSMBItemTree alloc] initWithType:KxSMBItemTypeDir
path:path
stat:stat
auth:auth];
}
} else if (S_ISREG(stat.mode)) {
result = [[KxSMBItemFile alloc] initWithType:KxSMBItemTypeFile
path:path
stat:stat
auth:auth];
} else {
result = [[KxSMBItem alloc] initWithType:S_ISLNK(stat.mode) ? KxSMBItemTypeLink : KxSMBItemTypeUnknown
path:path
stat:stat
auth:auth];
}
}
[self closeSmbContext:smbContext];
return result;
}
+ (id) removeAtPath:(NSString *)path
auth:(KxSMBAuth *)auth
{
NSParameterAssert(path);
if (![path hasPrefix:@"smb://"]) {
return mkKxSMBError(KxSMBErrorInvalidProtocol,
NSLocalizedString(@"Path:%@", nil), path);
}
SMBCCTX *smbContext = [self openSmbContext:auth];
if (!smbContext) {
const int err = errno;
return mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable init SMB context (errno:%d)", nil), err);
}
id result;
int r = smbc_getFunctionUnlink(smbContext)(smbContext, path.UTF8String);
if (r < 0) {
int err = errno;
if (err == EISDIR || err == EINVAL) {
r = smbc_getFunctionRmdir(smbContext)(smbContext, path.UTF8String);
if (r < 0) {
err = errno;
result = mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable rmdir file:%@ (errno:%d)", nil), path, err);
}
} else {
result = mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable unlink file:%@ (errno:%d)", nil), path, err);
}
}
[self closeSmbContext:smbContext];
return result;
}
+ (id) createFolderAtPath:(NSString *)path
auth:(KxSMBAuth *)auth
{
NSParameterAssert(path);
if (![path hasPrefix:@"smb://"]) {
return mkKxSMBError(KxSMBErrorInvalidProtocol,
NSLocalizedString(@"Path:%@", nil), path);
}
SMBCCTX *smbContext = [self openSmbContext:auth];
if (!smbContext) {
const int err = errno;
return mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable init SMB context (errno:%d)", nil), err);
}
id result;
int r = smbc_getFunctionMkdir(smbContext)(smbContext, path.UTF8String, 0);
if (r < 0) {
const int err = errno;
result = mkKxSMBError(errnoToSMBErr(err),
NSLocalizedString(@"Unable mkdir:%@ (errno:%d)", nil), path, err);
} else {
id stat = [self fetchStat:smbContext atPath: path];
if ([stat isKindOfClass:[KxSMBItemStat class]]) {
result = [[KxSMBItemTree alloc] initWithType:KxSMBItemTypeDir
path:path
stat:stat
auth:auth];
} else {
result = stat;
}
}
[self closeSmbContext:smbContext];
return result;
}
+ (id) createFileAtPath:(NSString *)path
overwrite:(BOOL)overwrite
auth:(KxSMBAuth *)auth
{
NSParameterAssert(path);
if (![path hasPrefix:@"smb://"]) {
return mkKxSMBError(KxSMBErrorInvalidProtocol,
NSLocalizedString(@"Path:%@", nil), path);
}
KxSMBItemFile *itemFile = [[KxSMBItemFile alloc] initWithType:KxSMBItemTypeFile
path:path
stat:nil
auth:auth];
id result = [itemFile createFile:overwrite];
if ([result isKindOfClass:[NSError class]]) {
return result;
}
return itemFile;
}
+ (NSError *) ensureLocalFolderExists:(NSString *)folderPath
{
NSFileManager *fm = [[NSFileManager alloc] init];
BOOL isDir;
if ([fm fileExistsAtPath:folderPath isDirectory:&isDir]) {
if (!isDir) {
return mkKxSMBError(KxSMBErrorFileIO,
NSLocalizedString(@"Cannot overwrite file %@", nil),
folderPath);
}
} else {
NSError *error;
if (![fm createDirectoryAtPath:folderPath
withIntermediateDirectories:NO
attributes:nil
error:&error]) {
return error;
}
}
return nil;
}
+ (NSFileHandle *) createLocalFile:(NSString *)path
overwrite:(BOOL) overwrite
error:(NSError **)outError
{
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:path]) {
if (overwrite) {
if (![fm removeItemAtPath:path error:outError]) {
return nil;
}
} else {
return nil;
}
}
NSString *folder = path.stringByDeletingLastPathComponent;
if (![fm fileExistsAtPath:folder] &&
![fm createDirectoryAtPath:folder
withIntermediateDirectories:YES
attributes:nil
error:outError]) {
return nil;
}
if (![fm createFileAtPath:path
contents:nil
attributes:nil]) {
if (outError) {
*outError = mkKxSMBError(KxSMBErrorFileIO,
NSLocalizedString(@"Unable create file", nil),
path.lastPathComponent);
}
return nil;
}
return [NSFileHandle fileHandleForWritingToURL:[NSURL fileURLWithPath:path]
error:outError];
}
+ (void) readSMBFile:(KxSMBItemFile *)smbFile
fileHandle:(NSFileHandle *)fileHandle
progress:(KxSMBBlockProgress)progress
block:(KxSMBBlock)block
{
[smbFile readDataOfLength:1024*1024
block:^(id result)
{
if ([result isKindOfClass:[NSData class]]) {
NSData *data = result;
if (data.length) {
[fileHandle writeData:data];
if (progress) {
BOOL stop = NO;
progress(smbFile, fileHandle.offsetInFile, &stop);
if (stop) {
// remove the local file from a disk
NSString *filePath;
char buffer[PATH_MAX] = {0};
if (fcntl(fileHandle.fileDescriptor, F_GETPATH, buffer) != -1) {
filePath = [[NSString alloc] initWithUTF8String:buffer];
}
//[fileHandle truncateFileAtOffset:0];
[fileHandle closeFile];
if (filePath.length) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
block(nil);
return;
}
}
[self readSMBFile:smbFile
fileHandle:fileHandle
progress:progress
block:block];
} else {
[fileHandle closeFile];
block(@(YES)); // complete
}
return;
}
[fileHandle closeFile];
block([result isKindOfClass:[NSError class]] ? result : nil);
}];
}
+ (void) copySMBFile:(KxSMBItemFile *)smbFile
localPath:(NSString *)localPath
overwrite:(BOOL)overwrite
progress:(KxSMBBlockProgress)progress
block:(KxSMBBlock)block
{
NSError *error = nil;
NSFileHandle *fileHandle = [self createLocalFile:localPath overwrite:overwrite error:&error];
if (fileHandle) {
[self readSMBFile:smbFile
fileHandle:fileHandle
progress:progress
block:block];
} else {
if (!error) {
error = mkKxSMBError(KxSMBErrorFileIO,
NSLocalizedString(@"Cannot overwrite file %@", nil),
localPath.lastPathComponent);
}
block(error);
}
}
+ (void) enumerateSMBFolders:(NSArray *)folders
items:(NSMutableArray *)items
block:(KxSMBBlock)block
{
KxSMBItemTree *folder = folders[0];
NSMutableArray *mfolders = [folders mutableCopy];
[mfolders removeObjectAtIndex:0];
[folder fetchItems:^(id result)
{
if ([result isKindOfClass:[NSArray class]]) {
for (KxSMBItem *item in result ) {
if ([item isKindOfClass:[KxSMBItemFile class]]) {
[items addObject:item];
} else if ([item isKindOfClass:[KxSMBItemTree class]] &&
(item.type == KxSMBItemTypeDir ||
item.type == KxSMBItemTypeFileShare ||
item.type == KxSMBItemTypeServer))
{
[mfolders addObject:item];
[items addObject:item];
}
}
if (mfolders.count) {
[self enumerateSMBFolders:mfolders items:items block:block];
} else {
block(items);
}
} else {
block([result isKindOfClass:[NSError class]] ? result : nil);
}
}];
}
+ (void) copySMBItems:(NSArray *)smbItems
smbFolder:(NSString *)smbFolder
localFolder:(NSString *)localFolder
overwrite:(BOOL)overwrite
progress:(KxSMBBlockProgress)progress
block:(KxSMBBlock)block
{
KxSMBItem *item = smbItems[0];
if (smbItems.count > 1) {
smbItems = [smbItems subarrayWithRange:NSMakeRange(1, smbItems.count - 1)];
} else {
smbItems = nil;
}
if ([item isKindOfClass:[KxSMBItemFile class]]) {
NSString *destPath = localFolder;
NSString *itemFolder = item.path.stringByDeletingLastPathComponent;
if (itemFolder.length > smbFolder.length) {
NSString *relPath = [itemFolder substringFromIndex:smbFolder.length];
destPath = [destPath stringByAppendingPathComponent:relPath];
}
destPath = [destPath stringByAppendingSMBPathComponent:item.path.lastPathComponent];
[self copySMBFile:(KxSMBItemFile *)item
localPath:destPath
overwrite:overwrite
progress:progress
block:^(id result)
{
if ([result isKindOfClass:[NSError class]]) {
block(result);
} else {
if (smbItems.count) {
[self copySMBItems:smbItems
smbFolder:smbFolder
localFolder:localFolder
overwrite:overwrite
progress:progress
block:block];
} else {
block(@(YES)); // complete
}
}
}];
} else if ([item isKindOfClass:[KxSMBItemTree class]]) {
NSString *destPath = localFolder;
NSString *itemFolder = item.path;
if (itemFolder.length > smbFolder.length) {
NSString *relPath = [itemFolder substringFromIndex:smbFolder.length];
destPath = [destPath stringByAppendingPathComponent:relPath];
}
NSError *error = [self ensureLocalFolderExists:destPath];
if (error) {
block(error);
return;
}
if (smbItems.count) {
[self copySMBItems:smbItems
smbFolder:smbFolder
localFolder:localFolder
overwrite:overwrite
progress:progress
block:block];
} else {
block(@(YES)); // complete
}
}
}
///
+ (void) writeSMBFile:(KxSMBItemFile *)smbFile
fileHandle:(NSFileHandle *)fileHandle
progress:(KxSMBBlockProgress)progress
block:(KxSMBBlock)block
{
NSData *data;
@try {
data = [fileHandle readDataOfLength:1024*1024];
}
@catch (NSException *exception) {
[fileHandle closeFile];
block(mkKxSMBError(KxSMBErrorFileIO, [exception description]));
return;
}
if (data.length) {