/
CKFTPConnection.m
3758 lines (3318 loc) · 129 KB
/
CKFTPConnection.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
/*
Copyright (c) 2004-2006, Greg Hulands <ghulands@mac.com>
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.
Neither the name of Greg Hulands 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.
*/
#import "CKFTPConnection.h"
#import "CKConnectionThreadManager.h"
#import "RunLoopForwarder.h"
#import "CKInternalTransferRecord.h"
#import "CKTransferRecord.h"
#import "NSFileManager+Connection.h"
#import "NSObject+Connection.h"
#import "CKCacheableHost.h"
#import "CKConnectionProtocol.h"
#import "CKURLProtectionSpace.h"
#import <sys/types.h>
#import <sys/socket.h>
#import <netinet/in.h>
NSString *CKFTPErrorDomain = @"FTPErrorDomain";
// 500 ms.
const double kDelegateNotificationTheshold = 0.5;
@interface CKTransferRecord (Internal)
- (void)setSize:(unsigned long long)size;
@end
@interface CKFTPConnection (Private)
- (NSArray *)parseLines:(NSString *)line;
- (void)closeDataConnection;
- (void)handleDataReceivedEvent:(NSStreamEvent)eventCode;
- (void)handleDataSendStreamEvent:(NSStreamEvent)eventCode;
- (void)closeDataStreams;
- (void)openDataStreamsToHost:(NSHost *)aHost port:(int)aPort;
- (CKConnectionCommand *)pushDataConnectionOnCommandQueue;
- (CKConnectionCommand *)nextAvailableDataConnectionType;
- (CKTransferRecord *)uploadFile:(NSString *)localPath
orData:(NSData *)data
offset:(unsigned long long)offset
remotePath:(NSString *)remotePath
checkRemoteExistence:(BOOL)flag
delegate:(id)delegate;
- (NSFileHandle *)writeHandle;
- (void)setWriteHandle:(NSFileHandle *)aWriteHandle;
- (NSFileHandle *)readHandle;
- (void)setReadHandle:(NSFileHandle *)aReadHandle;
- (NSData *)readData;
- (void)setReadData:(NSData *)aReadData;
- (NSString *)currentPath;
- (void)setCurrentPath:(NSString *)aCurrentPath;
- (BOOL)isAboveNotificationTimeThreshold:(NSDate *)date;
- (NSString *)setupEPRTConnection; //returns the command after creating a socket
- (NSString *)setupActiveConnection; //return the cmmand after creating a socket
- (void)setDataInputStreamAndOpen:(NSInputStream *)iStream outputStream:(NSOutputStream *)oStream socket:(CFSocketNativeHandle)socket;
- (void)prepareAndOpenDataStreams;
//Command Handling
- (void)_receivedCodeInConnectionNotConnectedState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentUsernameState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentAccountState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentPasswordState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionAwaitingCurrentDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionAwaitingDirectoryContentsState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionChangingDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionCreateDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionDeleteDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionRenameFromState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionAwaitingRenameState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionDeleteFileState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionDownloadingFileState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionUploadingFileState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentOffsetState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentFeatureRequestState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentQuitState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSettingPermissionsState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentSizeState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInConnectionSentDisconnectState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInFTPSettingPassiveState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInFTPSettingEPSVState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInFTPSettingActiveState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInFTPSettingEPRTState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInFTPAwaitingRemoteSystemTypeState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
- (void)_receivedCodeInFTPChangeDirectoryListingStyleState:(int)code command:(NSString *)command buffer:(NSString *)buffer;
@end
@interface CKFTPConnection (Authentication) <NSURLAuthenticationChallengeSender>
@property(nonatomic, copy) NSURLCredential *currentAuthenticationCredential;
- (void)authenticateConnection;
- (void)sendPassword;
@end
#pragma mark -
void dealWithConnectionSocket(CFSocketRef s, CFSocketCallBackType type,
CFDataRef address, const void *data, void *info);
#pragma mark -
@implementation CKFTPConnection
+ (void)load // registration of this class
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[CKConnectionRegistry sharedConnectionRegistry] registerClass:self forName:[self name] URLScheme:@"ftp"];
[pool release];
}
+ (NSInteger)defaultPort { return 21; }
+ (NSString *)name
{
return @"FTP";
}
+ (NSArray *)URLSchemes
{
return [NSArray arrayWithObject:@"ftp"];
}
- (id)initWithRequest:(CKConnectionRequest *)request
{
if (self = [super initWithRequest:request])
{
[self setState:CKConnectionNotConnectedState];
// These are never replaced during the lifetime of this object so we don't bother with accessor methods
_dataBuffer = [[NSMutableData data] retain];
_commandBuffer = [[NSMutableString alloc] initWithString:@""];
_ftpFlags.canUseActive = YES;
_ftpFlags.canUseEPRT = YES;
_ftpFlags.canUsePASV = YES;
_ftpFlags.canUseEPSV = YES;
_ftpFlags.hasSize = YES;
_isConnected = NO;
}
return self;
}
- (void)dealloc
{
[self closeDataStreams];
[_buffer release];
[_commandBuffer release];
[_dataBuffer release];
[_writeHandle release];
[self setReadHandle:nil];
[self setWriteHandle:nil];
[self setReadData:nil];
[self setCurrentPath:nil];
[_rootPath release];
[_lastNotified release];
[_noopTimer invalidate];
[_noopTimer release];
[_lastAuthenticationChallenge release];
[_currentAuthenticationCredential release];
[super dealloc];
}
#pragma mark -
#pragma mark Commands
/*! Called from the background thread.
*/
- (void)sendCommand:(id)command
{
/* clang flagged these as not being used
NSString *stringOnlyCommand = command;
if ([command isKindOfClass:[NSInvocation class]])
{
stringOnlyCommand = NSStringFromSelector([command selector]);
}
*/
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([command isKindOfClass:[NSInvocation class]])
{
[command invoke];
return;
}
if ([command isEqualToString:@"DATA_CON"])
{
CKConnectionCommand *cmd = [self nextAvailableDataConnectionType];
[self pushCommandOnHistoryQueue:cmd];
command = [cmd command];
_state = [cmd sentState];
[self closeDataConnection];
}
if ([command isEqualToString:@"EPRT"])
{
_ftpFlags.isActiveDataConn = YES;
command = [self setupEPRTConnection];
}
else if ([command isEqualToString:@"PORT"])
{
_ftpFlags.isActiveDataConn = YES;
command = [self setupActiveConnection];
}
else if ([command isEqualToString:@"EPSV"])
{
_ftpFlags.isActiveDataConn = NO;
}
else if ([command isEqualToString:@"PASV"])
{
_ftpFlags.isActiveDataConn = NO;
}
else if ([command isEqualToString:@"LIST -a"] && _ftpFlags.isMicrosoft)
{
command = @"LIST";
}
NSString *formattedCommand = [NSString stringWithFormat:@"%@\r\n", command];
NSString *commandToEcho = command;
if ([command rangeOfString:@"PASS"].location != NSNotFound)
{
if (![defaults boolForKey:@"AllowPasswordToBeLogged"])
{
commandToEcho = @"PASS ####";
}
}
[[self client] appendString:commandToEcho toTranscript:CKTranscriptSent];
KTLog(CKProtocolDomain, KTLogDebug, @">> %@", commandToEcho);
if ([formattedCommand rangeOfString:@"RETR"].location != NSNotFound)
{
CKInternalTransferRecord *download = [self currentDownload];
[[self client] downloadDidBegin:[download remotePath]];
if ([download delegateRespondsToTransferDidBegin])
{
[[download delegate] transferDidBegin:[download userInfo]];
}
}
if ([formattedCommand rangeOfString:@"STOR"].location != NSNotFound)
{
CKInternalTransferRecord *upload = [self currentUpload];
[[self client] uploadDidBegin:[upload remotePath]];
if ([upload delegateRespondsToTransferDidBegin])
{
[[upload delegate] transferDidBegin:[upload userInfo]];
}
}
[self sendData:[formattedCommand dataUsingEncoding:NSUTF8StringEncoding]];
}
/*! The main communication between the foreground thread and the background thread. Called by EITHER thread.
*/
/*! Parse the response received from the server. Called from the background thread.
*/
- (void)parseCommand:(NSString *)command
{
NSScanner *scanner = [NSScanner scannerWithString:command];
int code;
[scanner scanInt:&code];
// we need to consume everything until 'xxx '
NSMutableString *buffer = [NSMutableString stringWithFormat:@"%@\n", command];
BOOL atEnd = NO;
NSRange r;
NSString *strCode = [NSString stringWithFormat:@"%d ", code];
if (![command hasPrefix:strCode])
{
if ((r = [_commandBuffer rangeOfString:strCode]).location != NSNotFound) {
[buffer appendString:_commandBuffer];
//need to drop out of the commandBuffer up to the new line.
NSRange newLineRange;
NSRange toEnd = NSMakeRange(r.location, [_commandBuffer length] - r.location);
if ((newLineRange = [_commandBuffer rangeOfString:@"\r\n"
options:NSCaseInsensitiveSearch
range:toEnd]).location != NSNotFound
|| (newLineRange = [_commandBuffer rangeOfString:@"\n"
options:NSCaseInsensitiveSearch
range:toEnd]).location != NSNotFound)
[_commandBuffer deleteCharactersInRange:NSMakeRange(0,newLineRange.location+newLineRange.length)];
atEnd = YES;
}
else
{
[buffer appendString:_commandBuffer];
[_commandBuffer deleteCharactersInRange:NSMakeRange(0, [_commandBuffer length])];
}
while (atEnd == NO)
{
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
NSData *data = [self availableData];
if ([data length] > 0)
{
NSString *line = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (line)
[buffer appendString:line];
if ([line rangeOfString:strCode].location != NSNotFound)
atEnd = YES;
[line release];
}
}
}
[[self client] appendString:buffer toTranscript:CKTranscriptReceived];
KTLog(CKProtocolDomain, KTLogDebug, @"<<# %@", command); /// use <<# to help find commands
int stateToHandle = GET_STATE;
//State independent handling
switch (code)
{
case 200: //Command okay
case 202:
case 215: //NAME system type
case 250:
case 257: //Path Created
case 450: //Requested file action not taken. File unavailable.
case 451: //Requested acion aborted, local error in processing
case 504: //Command not implemented for that parameter (Karelia Case 28078, FileZilla servers do not allow CHMOD, returning 504)
case 551:
{
[self setState:CKConnectionIdleState];
break;
}
case 150: //File status okay, about to open data connection.
{
if ([command rangeOfString:@"directory listing"].location != NSNotFound) //Sometimes we get "150 Here comes the directory listing"
{
//we'll clean the buffer
[_buffer setLength:0];
}
break;
}
case 226:
{
_ftpFlags.received226 = YES;
if ([command rangeOfString:@"abort" options:NSCaseInsensitiveSearch].location != NSNotFound)
{
NSString *remotePath = [NSString string];
if ([self currentUpload] != nil)
{
remotePath = [NSString stringWithString:[[self currentUpload] remotePath]];
//Dequeue and close any handles just as if we finished the upload
[self dequeueUpload];
[self setReadData:nil];
[self setReadHandle:nil];
_transferSize = 0;
}
else if ([self currentDownload] != nil)
{
remotePath = [NSString stringWithString:[[self currentDownload] remotePath]];
//Dequeue and close any handles just as if we finished the download
[self dequeueDownload];
[_writeHandle closeFile];
[self setWriteHandle:nil];
}
[[self client] connectionDidCancelTransfer:remotePath];
}
if (_dataSendStream == nil || _dataReceiveStream == nil)
{
[self setState:CKConnectionIdleState];
}
break;
}
case 332: //need account
{
NSString *account = [[self client] accountForUsername:nil];
if (account)
{
[self sendCommand:[NSString stringWithFormat:@"ACCT %@", account]];
[self setState:CKConnectionSentAccountState];
}
break;
}
case 421: //service timed out.
{
[self closeDataStreams];
[super threadedDisconnect]; //This empties the queues, etc.
_isConnected = NO;
[[self client] connectionDidDisconnectFromHost:[[[self request] URL] host]];
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"FTP service not available; Remote server has closed connection", @"FTP service timed out");
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[self request] URL], ConnectionHostKey, nil];
NSError *error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
[[self client] connectionDidReceiveError:error];
[self setState:CKConnectionNotConnectedState];
break;
}
case 503: //Bad sequence of commands
{
//This is an internal error in the syntax of the commands and arguments sent.
//We should never get to this state as we should construct commands correctly.
if (GET_STATE != CKConnectionSentFeatureRequestState)
{
KTLog(CKProtocolDomain, KTLogError, @"FTP Internal Error: %@", command);
// We should just see if we can process the next command
[self setState:CKConnectionIdleState];
break;
}
else
{
[self authenticateConnection];
break;
}
}
case 522:
{
_ftpFlags.canUseEPRT = NO;
[self sendCommand:@"DATA_CON"];
break;
}
case 530: //User not logged in
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"Not Logged In", @"FTP Error"), NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[[self request] URL] host], ConnectionHostKey, nil];
NSError *error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
[[self client] connectionDidReceiveError:error];
break;
}
default:
break;
}
switch (stateToHandle)
{
case CKConnectionNotConnectedState:
[self _receivedCodeInConnectionNotConnectedState:code command:command buffer:buffer];
break;
case CKConnectionSentUsernameState:
[self _receivedCodeInConnectionSentUsernameState:code command:command buffer:buffer];
break;
case CKConnectionSentAccountState:
[self _receivedCodeInConnectionSentAccountState:code command:command buffer:buffer];
break;
case CKConnectionSentPasswordState:
[self _receivedCodeInConnectionSentPasswordState:code command:command buffer:buffer];
break;
case CKConnectionAwaitingCurrentDirectoryState:
[self _receivedCodeInConnectionAwaitingCurrentDirectoryState:code command:command buffer:buffer];
break;
case CKConnectionAwaitingDirectoryContentsState:
[self _receivedCodeInConnectionAwaitingDirectoryContentsState:code command:command buffer:buffer];
break;
case CKConnectionChangingDirectoryState:
[self _receivedCodeInConnectionChangingDirectoryState:code command:command buffer:buffer];
break;
case CKConnectionCreateDirectoryState:
[self _receivedCodeInConnectionCreateDirectoryState:code command:command buffer:buffer];
break;
case CKConnectionDeleteDirectoryState:
[self _receivedCodeInConnectionDeleteDirectoryState:code command:command buffer:buffer];
break;
case CKConnectionRenameFromState:
[self _receivedCodeInConnectionRenameFromState:code command:command buffer:buffer];
break;
case CKConnectionAwaitingRenameState:
[self _receivedCodeInConnectionAwaitingRenameState:code command:command buffer:buffer];
break;
case CKConnectionDeleteFileState:
[self _receivedCodeInConnectionDeleteFileState:code command:command buffer:buffer];
break;
case CKConnectionDownloadingFileState:
[self _receivedCodeInConnectionDownloadingFileState:code command:command buffer:buffer];
break;
case CKConnectionUploadingFileState:
[self _receivedCodeInConnectionUploadingFileState:code command:command buffer:buffer];
break;
case CKConnectionSentOffsetState:
[self _receivedCodeInConnectionSentOffsetState:code command:command buffer:buffer];
break;
case CKConnectionSentFeatureRequestState:
[self _receivedCodeInConnectionSentFeatureRequestState:code command:command buffer:buffer];
break;
case CKConnectionSentQuitState:
[self _receivedCodeInConnectionSentQuitState:code command:command buffer:buffer];
break;
case CKConnectionSettingPermissionsState:
[self _receivedCodeInConnectionSettingPermissionsState:code command:command buffer:buffer];
break;
case CKConnectionSentSizeState:
[self _receivedCodeInConnectionSentSizeState:code command:command buffer:buffer];
break;
case CKConnectionSentDisconnectState:
[self _receivedCodeInConnectionSentDisconnectState:code command:command buffer:buffer];
break;
case FTPSettingPassiveState:
[self _receivedCodeInFTPSettingPassiveState:code command:command buffer:buffer];
break;
case FTPSettingEPSVState:
[self _receivedCodeInFTPSettingEPSVState:code command:command buffer:buffer];
break;
case FTPSettingActiveState:
[self _receivedCodeInFTPSettingActiveState:code command:command buffer:buffer];
break;
case FTPSettingEPRTState:
[self _receivedCodeInFTPSettingEPRTState:code command:command buffer:buffer];
break;
case FTPAwaitingRemoteSystemTypeState:
[self _receivedCodeInFTPAwaitingRemoteSystemTypeState:code command:command buffer:buffer];
break;
case FTPChangeDirectoryListingStyle:
[self _receivedCodeInFTPChangeDirectoryListingStyleState:code command:command buffer:buffer];
break;
default:
break;
}
}
- (void)_receivedCodeInConnectionNotConnectedState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
switch (code)
{
case 120: //Service Ready
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"FTP Service Unavailable", @"FTP no service"), NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[[self request] URL] host], ConnectionHostKey, nil];
NSError *error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
[[self client] connectionDidConnectToHost:[[[self request] URL] host] error:error];
[self setState:CKConnectionNotConnectedState]; //don't really need.
break;
}
case 220: //Service Ready For New User
{
if (_ftpFlags.loggedIn != NO)
break;
if ([command rangeOfString:@"Microsoft FTP Service"].location != NSNotFound ||
[buffer rangeOfString:@"Microsoft FTP Service"].location != NSNotFound)
{
_ftpFlags.isMicrosoft = YES;
}
else
{
_ftpFlags.isMicrosoft = NO;
}
[self authenticateConnection];
break;
}
default:
break;
}
}
- (void)_receivedCodeInConnectionSentUsernameState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
switch (code)
{
case 230: //User logged in, proceed
{
if (![[_currentAuthenticationCredential user] isEqualToString:@"anonymous"]) break;
_ftpFlags.loggedIn = YES;
// Queue up the commands we want to insert in the queue before notifying client we're connected
// We get the current directory -- and we're notified of a change directory ... so we'll know what directory
// we are starting in.
CKConnectionCommand *getCurrentDirectoryCommand = [CKConnectionCommand command:@"PWD"
awaitState:CKConnectionIdleState
sentState:CKConnectionAwaitingCurrentDirectoryState
dependant:nil
userInfo:nil];
[self pushCommandOnCommandQueue:getCurrentDirectoryCommand];
CKConnectionCommand *getRemoteSystemTypeCommand = [CKConnectionCommand command:@"SYST"
awaitState:CKConnectionIdleState
sentState:FTPAwaitingRemoteSystemTypeState
dependant:nil
userInfo:nil];
[self pushCommandOnCommandQueue:getRemoteSystemTypeCommand];
// What features does the server support?
CKConnectionCommand *featuresCommand = [CKConnectionCommand command:@"FEAT"
awaitState:CKConnectionIdleState
sentState:CKConnectionSentFeatureRequestState
dependant:nil
userInfo:nil];
[self pushCommandOnCommandQueue:featuresCommand];
[self setState:CKConnectionIdleState];
break;
}
case 331: //User name okay, need password.
{
[self sendPassword];
break;
}
default:
break;
}
}
- (void)_receivedCodeInConnectionSentAccountState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
switch (code)
{
case 230: //User logged in, proceed
{
[self sendPassword];
break;
}
case 530: //User not logged in
{
// TODO: Attempt authentication again
/*NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"Invalid Account name", @"FTP Error"), NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[self host], ConnectionHostKey, nil];
*/
break;
}
default:
break;
}
}
- (void)_receivedCodeInConnectionSentPasswordState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
switch(code)
{
case 230: //User logged in, proceed
{
_ftpFlags.loggedIn = YES;
// Appropriately store the credentials once the password has been sent
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:[self currentAuthenticationCredential]
forProtectionSpace:[_lastAuthenticationChallenge protectionSpace]];
[self setCurrentAuthenticationCredential:nil];
// We get the current directory -- and we're notified of a change directory ... so we'll know what directory
// we are starting in.
CKConnectionCommand *getCurrentDirectoryCommand = [CKConnectionCommand command:@"PWD"
awaitState:CKConnectionIdleState
sentState:CKConnectionAwaitingCurrentDirectoryState
dependant:nil
userInfo:nil];
[self pushCommandOnCommandQueue:getCurrentDirectoryCommand];
CKConnectionCommand *getRemoteSystemTypeCommand = [CKConnectionCommand command:@"SYST"
awaitState:CKConnectionIdleState
sentState:FTPAwaitingRemoteSystemTypeState
dependant:nil
userInfo:nil];
[self pushCommandOnCommandQueue:getRemoteSystemTypeCommand];
// What features does the server support?
CKConnectionCommand *featuresCommand = [CKConnectionCommand command:@"FEAT"
awaitState:CKConnectionIdleState
sentState:CKConnectionSentFeatureRequestState
dependant:nil
userInfo:nil];
[self pushCommandOnCommandQueue:featuresCommand];
[self setState:CKConnectionIdleState];
break;
}
case 530: // Authentication failed. We shall request fresh authentication
{
[self authenticateConnection];
break;
}
default:
break;
}
}
- (void)_receivedCodeInConnectionAwaitingCurrentDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
NSError *error = nil;
NSString *path = [self scanBetweenQuotes:command];
if (!path || [path length] == 0)
path = [[[[self lastCommand] command] substringFromIndex:4] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
switch (code)
{
case 257: //Path Created
{
[self setCurrentPath:path];
if (_rootPath == nil)
_rootPath = [path copy];
break;
}
case 421:
{
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"FTP service not available; Remote server has closed connection", @"FTP service timed out");
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[[self request] URL] host], ConnectionHostKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
case 550: //Requested action not taken, file not found. //Permission Denied
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:LocalizedStringInConnectionKitBundle(@"Permission Denied", @"Permission Denied"), NSLocalizedDescriptionKey, path, NSFilePathErrorKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
}
default:
break;
}
[[self client] connectionDidChangeToDirectory:path error:error];
}
- (void)_receivedCodeInConnectionAwaitingDirectoryContentsState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
switch (code)
{
case 425: //Couldn't open data connection
{
CKConnectionCommand *last = [self lastCommand];
CKConnectionState lastState = [[[self commandHistory] objectAtIndex:1] sentState];
if (lastState == FTPSettingEPSVState)
{
_ftpFlags.canUseEPSV = NO;
[self closeDataStreams];
[self sendCommand:@"DATA_CON"];
[self pushCommandOnCommandQueue:last];
}
else if (lastState == FTPSettingEPRTState)
{
_ftpFlags.canUseEPRT = NO;
[self closeDataStreams];
[self sendCommand:@"DATA_CON"];
[self pushCommandOnCommandQueue:last];
}
else if (lastState == FTPSettingActiveState)
{
_ftpFlags.canUseActive = NO;
[self closeDataStreams];
[self sendCommand:@"DATA_CON"];
[self pushCommandOnCommandQueue:last];
}
else if (lastState == FTPSettingPassiveState)
{
_ftpFlags.canUsePASV = NO;
[self closeDataStreams];
[self sendCommand:@"DATA_CON"];
[self pushCommandOnCommandQueue:last];
}
break;
}
default:
break;
}
}
- (void)_receivedCodeInConnectionChangingDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
NSError *error = nil;
NSString *path = [self scanBetweenQuotes:command];
if (!path || [path length] == 0)
path = [[[[self lastCommand] command] substringFromIndex:4] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
switch (code)
{
case 421:
{
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"FTP service not available; Remote server has closed connection", @"FTP service timed out");
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[[self request] URL] host], ConnectionHostKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
case 500: //Syntax error, command unrecognized.
case 501: //Syntax error in parameters or arguments.
case 502: //Command not implemented
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"Failed to change to directory", @"Bad ftp command"), NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey, path, NSFilePathErrorKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:ConnectionErrorChangingDirectory userInfo:userInfo];
break;
}
case 550: //Requested action not taken, file not found. //Permission Denied
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:LocalizedStringInConnectionKitBundle(@"Permission Denied", @"Permission Denied"), NSLocalizedDescriptionKey, path, NSFilePathErrorKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
default:
break;
}
[[self client] connectionDidChangeToDirectory:path error:error];
[self setState:CKConnectionIdleState];
}
- (void)_receivedCodeInConnectionCreateDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
NSError *error = nil;
switch (code)
{
case 421:
{
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"FTP service not available; Remote server has closed connection", @"FTP service timed out");
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[[self request] URL] host], ConnectionHostKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
case 521: //Supported Address Families
{
if (!_isRecursiveUploading)
{
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"Create directory operation failed", @"FTP Create directory error");
NSString *path = nil;
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if ([command rangeOfString:@"exists"].location != NSNotFound)
{
[userInfo setObject:[NSNumber numberWithBool:YES] forKey:ConnectionDirectoryExistsKey];
if ([command rangeOfString:@":"].location != NSNotFound)
{
path = [command substringWithRange:NSMakeRange(4, [command rangeOfString:@":"].location - 4)];
[userInfo setObject:path forKey:ConnectionDirectoryExistsFilenameKey];
[userInfo setObject:path forKey:NSFilePathErrorKey];
}
}
[userInfo setObject:localizedDescription forKey:NSLocalizedDescriptionKey];
[userInfo setObject:command forKey:NSLocalizedFailureReasonErrorKey];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
}
break;
}
case 550: //Requested action not taken, file not found.
{
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"Create directory operation failed", @"FTP Create directory error");
//Some servers won't say that the directory exists. Once I get peer connections going, I will be able to ask the
//peer if the dir exists for confirmation until then we will make the assumption that it exists.
//if ([command rangeOfString:@"exists"].location != NSNotFound) {
[userInfo setObject:[NSNumber numberWithBool:YES] forKey:ConnectionDirectoryExistsKey];
NSString *path = [[[[self lastCommand] command] substringFromIndex:4] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[userInfo setObject:path forKey:ConnectionDirectoryExistsFilenameKey];
[userInfo setObject:path forKey:NSFilePathErrorKey];
[userInfo setObject:localizedDescription forKey:NSLocalizedDescriptionKey];
[userInfo setObject:command forKey:NSLocalizedFailureReasonErrorKey];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
default:
break;
}
NSString *path = [self scanBetweenQuotes:command];
if (!path || [path length] == 0)
{
path = [[[[self lastCommand] command] substringFromIndex:4] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
[[self client] connectionDidCreateDirectory:path error:error];
[self setState:CKConnectionIdleState];
}
- (void)_receivedCodeInConnectionDeleteDirectoryState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
NSError *error = nil;
switch (code)
{
case 421:
{
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"FTP service not available; Remote server has closed connection", @"FTP service timed out");
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[[self request] URL] host], ConnectionHostKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
case 550: //Requested action not taken, file not found.
{
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
NSString *localizedDescription = [NSString stringWithFormat:@"%@: %@", LocalizedStringInConnectionKitBundle(@"Failed to delete directory", @"couldn't delete the file"), [[self currentDirectory] stringByAppendingPathComponent:[self currentDeletion]]];
[userInfo setObject:[self currentDeletion] forKey:NSFilePathErrorKey];
[userInfo setObject:localizedDescription forKey:NSLocalizedDescriptionKey];
[userInfo setObject:command forKey:NSLocalizedFailureReasonErrorKey];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
default:
break;
}
// Uses same _fileDeletes queue, hope that's safe to do. (Any chance one could get ahead of another?)
[[self client] connectionDidDeleteDirectory:[_fileDeletes objectAtIndex:0] error:error];
[self dequeueDeletion];
[self setState:CKConnectionIdleState];
}
- (void)_receivedCodeInConnectionRenameFromState:(int)code command:(NSString *)command buffer:(NSString *)buffer
{
NSError *error = nil;
switch (code)
{
case 350: //Requested action pending further information
{
[self setState:CKConnectionRenameToState];
break;
}
case 421:
{
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"FTP service not available; Remote server has closed connection", @"FTP service timed out");
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
command, NSLocalizedFailureReasonErrorKey,
[[[self request] URL] host], ConnectionHostKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
default:
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:LocalizedStringInConnectionKitBundle(@"No such file", @"No such file"), NSLocalizedDescriptionKey, nil];
error = [NSError errorWithDomain:CKFTPErrorDomain code:code userInfo:userInfo];
break;
}
}
//Unlike other methods, we check that error isn't nil here, because we're sending the finished delegate message on error, whereas the "successful" codes send downloadProgressed messages.
if (error)
{