forked from ifrotz/iosfrotz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFtpConnection.m
1230 lines (961 loc) · 45.5 KB
/
FtpConnection.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
/*
iosFtpServer
Copyright (C) 2008 Richard Dearlove ( monsta )
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#import "FtpConnection.h"
#import "FtpServer.h"
#import "iosfrotz.h"
@implementation FtpConnection
@synthesize transferMode;
@synthesize currentFile;
@synthesize currentDir;
@synthesize rnfrFilename;
// ----------------------------------------------------------------------------------------------------------
-(instancetype)initWithAsyncSocket:(AsyncSocket*)newSocket forServer:(id)myServer
// ----------------------------------------------------------------------------------------------------------
{
self = [super init ];
if (self)
{
connectionSocket = newSocket;
server = myServer;
[ connectionSocket setDelegate:self ];
[ connectionSocket writeData:DATASTR(@"220 Frotz File Transfer Server " IPHONE_FROTZ_VERS ". Login with any user name.\r\n") withTimeout:-1 tag:0 ]; // send out the welcome message to the client
[ connectionSocket readDataToData:[AsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:FTP_CLIENT_REQUEST ]; // start listening for commands on this connection to client
dataListeningSocket = nil;
dataPort=2001;
transferMode = pasvftp;
queuedData = [[ NSMutableArray alloc ] init ]; // A buffer for sending data when the connection isn't quite up yet
currentDir = [ server.baseDir copy]; // the working directory for this connection, Starts in the directory the server is set to. set chroot=true in server code to sandbox in
currentFile = nil;
currentFileHandle = nil; // not saving to a file yet
rnfrFilename = nil;
currentUser = nil;
//NSLog(@"FC: Current Directory starting at %@",currentDir );
}
return self;
}
// ----------------------------------------------------------------------------------------------------------
-(void)dealloc
// ----------------------------------------------------------------------------------------------------------
{
if(connectionSocket)
{
[connectionSocket setDelegate:nil];
[connectionSocket disconnect];
}
if(dataListeningSocket){ // 12/2/10 - think this code is now redundant, dataListeningSocket, does it do anything anymore...?
[dataListeningSocket setDelegate:nil];
[dataListeningSocket disconnect];
}
if(dataSocket)
{
[dataSocket setDelegate:nil];
[dataSocket disconnect];
}
}
#pragma mark STATE
// ----------------------------------------------------------------------------------------------------------
//-(void)setTransferMode:(int)mode
// ----------------------------------------------------------------------------------------------------------
//{
// transferMode = mode;
//}
// ----------------------------------------------------------------------------------------------------------
-(NSString*)connectionAddress
// ----------------------------------------------------------------------------------------------------------
{
return [connectionSocket connectedHost];
}
// ==========================================================================================================
#pragma mark CHOOSE DATA SOCKET
// ==========================================================================================================
// ----------------------------------------------------------------------------------------------------------
-(BOOL)openDataSocket:(int)portNumber
// ----------------------------------------------------------------------------------------------------------
{
NSString *responseString;
NSError *error = nil;
if (dataSocket) // Code changed 2010-02-12 - As per Jon's fix. stops memory leak on socket and connection
{
dataSocket = nil;
}
dataSocket = [ [ AsyncSocket alloc ] initWithDelegate:self ]; // create our socket for Listening or Direct Connection
if (dataConnection)
{
dataConnection = nil;
}
switch (transferMode) {
case portftp:
dataPort = portNumber;
responseString = [ NSString stringWithFormat:@"200 PORT command successful."];
[ dataSocket connectToHost:[self connectionAddress] onPort:portNumber error:&error ];
// sleep(1);
dataConnection = [[ FtpDataConnection alloc ] initWithAsyncSocket:dataSocket forConnection:self withQueuedData:queuedData ];
break;
case lprtftp: // FIXME wrong return message
dataPort = portNumber;
responseString = [ NSString stringWithFormat:@"228 Entering Long Passive Mode (af, hal, h1, h2, h3,..., pal, p1, p2...)"]; //, dataPort >>8, dataPort & 0xff;
[ dataSocket connectToHost:[self connectionAddress] onPort:portNumber error:&error ];
dataConnection = [[ FtpDataConnection alloc ] initWithAsyncSocket:dataSocket forConnection:self withQueuedData:queuedData ];
break;
case eprtftp:
dataPort = portNumber;
responseString = @"200 EPRT command successful.";
[ dataSocket connectToHost:[self connectionAddress] onPort:portNumber error:&error ];
dataConnection = [[ FtpDataConnection alloc ] initWithAsyncSocket:dataSocket forConnection:self withQueuedData:queuedData ];
break;
case pasvftp: {
dataPort = [ self choosePasvDataPort ];
NSString *address = [ [connectionSocket localHost ] stringByReplacingOccurrencesOfString:@"." withString:@"," ]; // autoreleased
responseString = [ NSString stringWithFormat:@"227 Entering Passive Mode (%@,%d,%d)",address, dataPort >>8, dataPort & 0xff];
[ dataSocket acceptOnPort: dataPort error:&error ];
dataConnection = nil; // will pickup from the listening socket
}
break;
case epsvftp:
dataPort = [ self choosePasvDataPort ];
responseString = [ NSString stringWithFormat:@"229 Entering Extended Passive Mode (|||%d|)", dataPort ];
[ dataSocket acceptOnPort: dataPort error:&error ];
dataConnection = nil; // will pickup from the listening socket
break;
default:
break;
}
//NSLog( @"-- %@", [ error localizedDescription ] );
[ self sendMessage:responseString ];
return YES;
}
// ----------------------------------------------------------------------------------------------------------
-(int)choosePasvDataPort
// ----------------------------------------------------------------------------------------------------------
{
struct timeval tv;
unsigned short int seed[3];
gettimeofday(&tv, NULL);
seed[0] = (tv.tv_sec >> 16) & 0xFFFF;
seed[1] = tv.tv_sec & 0xFFFF;
seed[2] = tv.tv_usec & 0xFFFF;
seed48(seed);
int portNumber;
portNumber = (lrand48() % 64512) + 1024;
// NSLog(@"New Port number is %i", portNumber );
return portNumber; // FIXME - presetting to 2001 for the moment
//return 2001;
}
// ==========================================================================================================
#pragma mark ASYNCSOCKET DATACONNECTION
// ==========================================================================================================
// ----------------------------------------------------------------------------------------------------------
-(BOOL)onSocketWillConnect:(AsyncSocket *)sock
// ----------------------------------------------------------------------------------------------------------
{
// NSLog(@"FC:onSocketWillConnect");
[ sock readDataWithTimeout:READ_TIMEOUT tag:0 ];
return YES;
}
// ----------------------------------------------------------------------------------------------------------
-(void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket // should be for a data connection on 2001
// ----------------------------------------------------------------------------------------------------------
{
// opened socket for passive data - new socket connected to this which is the passive connection
// NSLog(@"FC:New Connection -- should be for the data port");
dataConnection = [[ FtpDataConnection alloc ] initWithAsyncSocket:newSocket forConnection:self withQueuedData:queuedData];
}
// ==========================================================================================================
#pragma mark ASYNCSOCKET FTPCLIENT CONNECTION
// ==========================================================================================================
// ----------------------------------------------------------------------------------------------------------
-(void)onSocket:(AsyncSocket*)sock didReadData:(NSData*)data withTag:(long)tag // DATA READ
// ----------------------------------------------------------------------------------------------------------
{
// NSLog(@"FC:didReadData");
[ connectionSocket readDataToData:[AsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:FTP_CLIENT_REQUEST ]; // start reading again
[ self processDataRead:data ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)onSocket:(AsyncSocket*)sock didWriteDataWithTag:(long)tag // DATA WRITTEN
// ----------------------------------------------------------------------------------------------------------
{
[ connectionSocket readDataToData:[AsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:FTP_CLIENT_REQUEST ]; // start reading again
// NSLog(@"FC:didWriteData");
}
// ----------------------------------------------------------------------------------------------------------
-(void)sendMessage:(NSString*)ftpMessage // REDUNDANT really - FIXME
// ----------------------------------------------------------------------------------------------------------
{
//NSLog(@">%@",ftpMessage );
NSMutableData *dataString = [[ ftpMessage dataUsingEncoding:NSUTF8StringEncoding ] mutableCopy]; // Autoreleased
[ dataString appendData:[AsyncSocket CRLFData] ];
[ connectionSocket writeData:dataString withTimeout:READ_TIMEOUT tag:FTP_CLIENT_REQUEST ];
dataString = nil;
[ connectionSocket readDataToData:[AsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:FTP_CLIENT_REQUEST ]; // start reading again
// [ connectionSocket readDataWithTimeout:READ_TIMEOUT tag:FTP_CLIENT_REQUEST ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)sendDataString:(NSString*)dataString
// ----------------------------------------------------------------------------------------------------------
{
NSMutableString *message = [[NSMutableString alloc] initWithString:dataString];
CFStringNormalize((CFMutableStringRef)message, kCFStringNormalizationFormC);
NSMutableData *data = [[ message dataUsingEncoding:server.clientEncoding ] mutableCopy]; // Autoreleased
message = nil;
if (dataConnection )
{// NSLog(@"FC:sendData");
[ dataConnection writeData:data ];
}
else
{
[ queuedData addObject:data ];
}
data = nil;
}
// ----------------------------------------------------------------------------------------------------------
-(void)sendData:(NSMutableData*)data
// ----------------------------------------------------------------------------------------------------------
{
if (dataConnection )
{// NSLog(@"FC:sendData");
[ dataConnection writeData:data ];
}
else
{
[ queuedData addObject:data ];
}
}
// ----------------------------------------------------------------------------------------------------------
-(void)didReceiveDataWritten // notification from FtpDataConnection that the dataWasWritten
// ----------------------------------------------------------------------------------------------------------
{
// NSLog(@"SENDING COMPLETED");
[ self sendMessage:@"226 Transfer complete." ]; // send completed message to client
[ dataConnection closeConnection ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)didReceiveDataRead // notification from FtpDataConnection that the dataWasWritten
// ----------------------------------------------------------------------------------------------------------
{
// NSLog(@"FC:didReceiveDataRead");
// must have sent a file
// Should start writing file out if not written yet : FIXNOW
if ( currentFileHandle != nil )
{
// Append data on
// NSLog(@"FC:Writing File to %@", currentFile );
[ currentFileHandle writeData:dataConnection.receivedData ];
}
else
{
NSLog(@"Couldnt write data");
}
}
// ----------------------------------------------------------------------------------------------------------
-(void)didFinishReading // Called at the end of a data connection from the client we presume
// ----------------------------------------------------------------------------------------------------------
{
if (currentFile)
{
// NSLog(@"Closing File Handle");
currentFile = nil;
}
else
{
NSLog(@"FC:Data Sent but not sure where its for ");
}
[ self sendMessage:@"226 Transfer complete." ]; // send completed message to client
// [ dataConnection closeConnection ]; // It must be closed, it dropped us
if ( currentFileHandle != nil )
{
// NSLog(@"Closing File Handle");
[ currentFileHandle closeFile ]; // Close the file handle
currentFileHandle = nil;
[ server didReceiveFileListChanged];
}
dataConnection.connectionState = clientQuiet;
}
// ==========================================================================================================
#pragma mark PROCESS
// =========================================================================================================
// ----------------------------------------------------------------------------------------------------------
-(void)processDataRead:(NSData*)data // convert to commands as Client Connection
// ----------------------------------------------------------------------------------------------------------
{
NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)]; // remove last 2 chars
NSString *crlfmessage = [[NSString alloc] initWithData:strData encoding:server.clientEncoding];
NSString *message;
// message = [ crlfmessage stringByReplacingOccurrencesOfString:@"\r\n" withString:@""]; // gets autoreleased
message = [ crlfmessage stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet ]];
//NSLog(@"<%@",message );
msgComponents = [message componentsSeparatedByString:@" "]; // change this to use spaces - for the FTP protocol
[ self processCommand ];
[connectionSocket readDataToData:[AsyncSocket CRLFData] withTimeout:-1 tag:0 ]; // force to readdata CHECK
}
// ----------------------------------------------------------------------------------------------------------
-(void)processCommand // assumes data has been place in Array msgComponents
// ----------------------------------------------------------------------------------------------------------
{
@autoreleasepool {
NSString *commandString = msgComponents[0];
if ([ commandString length ] > 0) // If there is a command here
{
// Search through dictionary for correct matching command and method that it calls
NSString *commandSelector = [ [server commands][[commandString lowercaseString]] stringByAppendingString:@"arguments:"];
if ( commandSelector ) // If we have a matching command
{
SEL action = NSSelectorFromString(commandSelector); // Turn into a method
if ( [ self respondsToSelector:action ]) // If we respond to this method
{
// DO COMMAND
// [self performSelector:action withObject:self withObject:msgComponents ]; // Preform method with arguments
// Do performSelector 'manually' to avoid ARC warning. Safe since called selectors do not return retained values.
IMP imp = [self methodForSelector:action];
void (*func)(id, SEL, NSArray *) = (void *)imp;
func(self, action, msgComponents);
}
else
{ // UNKNOWN COMMAND
NSString *outputString =[ NSString stringWithFormat:@"500 '%@': command not understood.", commandString ];
[ self sendMessage:outputString ];
NSLog(@"DONT UNDERSTAND");
}
}
else // UNKNOWN COMMAND
{
NSString *outputString =[ NSString stringWithFormat:@"500 '%@': command not understood.", commandString ];
[ self sendMessage:outputString ];
}
}
else
{
// Write out an error msg
}
} // autorelease pool
}
// ==========================================================================================================
#pragma mark COMMANDS
// ==========================================================================================================
// ----------------------------------------------------------------------------------------------------------
-(void)doQuit:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// NSLog(@"Quit : %@",arguments);
[self sendMessage:@"221 Bye" ];
if(connectionSocket)
{
[connectionSocket disconnectAfterWriting ]; // Will this close the socket ?
// [connectionSocket disconnect];
}
[ server closeConnection:self ]; // Tell the server to close us down, remove us from the list of connections
// FIXME - delete the dataconnection if its open
}
// ----------------------------------------------------------------------------------------------------------
-(void)doUser:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// send out confirmation message -- 331 password required for
currentUser = arguments[1];
NSString *outputString = [ NSString stringWithFormat:@"230 Login successful." ];
[ sender sendMessage:outputString];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doPass:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// NSString *pass = [ arguments objectAtIndex:1 ];
NSString *outputString = [ NSString stringWithFormat:@"230 User %@ logged in.", currentUser ];
[ sender sendMessage:outputString];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doStat:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// Send out stat message
[ sender sendMessage:@"211-localhost FTP server status:"];
// FIXME - add in the stats
[ sender sendMessage:@"211 End of Status"];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doFeat:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
[ sender sendMessage:@"211-Features supported"];
// If encoding is UTF8, notify the client
if (server.clientEncoding == NSUTF8StringEncoding)
[ sender sendMessage:@" UTF8" ];
[ sender sendMessage:@"211 End"];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doList:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// Get the name of any additional directory that we are asked to list, if its empty we use the current directory
NSString *lsDir = [ self fileNameFromArgs:arguments] ; // autoreleased, get the directory that we're being asked for
NSString *listText;
if ([lsDir length]<1) {
lsDir = currentDir;
}
else {
lsDir = [self rootedPath:lsDir ];
}
// NSLog( @"doList currentDir(%@) changeRoot%d", lsDir, server.changeRoot );
// NSLog(@"Will list %@ ",lsDir);
listText = [ server createList:lsDir shortForm:NO];
// if ([self canChangeDirectoryTo:lsDir]) {
// listText = [ [ server createList:lsDir] retain ]; // Can list directory so do it
// }
// else {
// listText = @""; // return nothing as not in chroot
// }
// NSLog( @"doList sending this. %@", listText );
[ sender sendMessage:@"150 Here comes the directory listing."];
[ sender sendDataString:listText ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doPwd:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// NSLog(@"Will PWD %@ ",[self visibleCurrentDir]);
// CHECKME - changed to show basedir - currentdir
NSString *cmdString = [ NSString stringWithFormat:@"257 \"%@\" is the current directory.", [self visibleCurrentDir] ]; // autoreleased
[ sender sendMessage:cmdString ]; // FIXME - seems to be buggy on ftp command line client
}
// ----------------------------------------------------------------------------------------------------------
-(void)doNoop:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
[sender sendMessage:@"200 NOOP command successful." ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doSyst:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
[ sender sendMessage:@"215 UNIX Type: L8 Version: iosFtp 20080912" ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doLprt:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// LPRT,"6,16,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,231,92"
NSString *socketDesc = arguments[1] ;
NSArray *socketAddr = [ socketDesc componentsSeparatedByString:@"," ];
int hb = [socketAddr[19] intValue ];
int lb = [socketAddr[20] intValue ];
NSLog(@"%d %d %d",hb <<8, hb,lb );
int clientPort = (hb <<8 ) + lb;
[sender setTransferMode:lprtftp];
[ sender openDataSocket:clientPort ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doEprt:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// EPRT |2|1080::8:800:200C:417A|5282|
NSString *socketDesc = arguments[1] ;
NSArray *socketAddr = [ socketDesc componentsSeparatedByString:@"|" ];
NSString *item;
for (item in socketAddr) {
NSLog(@"%@",item);
}
int clientPort = [socketAddr[3] intValue ];
NSLog(@"Got Send Port %d", clientPort );
[sender setTransferMode:eprtftp];
// [ sender initDataSocket:clientPort ];
[ sender openDataSocket:clientPort ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doPasv:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
[sender setTransferMode:pasvftp];
// [ sender initDataSocket:0 ];
[ sender openDataSocket:0 ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doEpsv:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// FIXME - open a port random high address
[sender setTransferMode:epsvftp];
// [ sender initDataSocket:0 ];
[ sender openDataSocket:0 ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doPort:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
int hb, lb;
// PORT 127,0,0,1,197,251 looks like this
// get 2nd argument and split up by , and then take the last 2 bits
NSString *socketDesc = arguments[1] ;
NSArray *socketAddr = [ socketDesc componentsSeparatedByString:@"," ];
hb = [socketAddr[4] intValue ];
lb = [socketAddr[5] intValue ];
int clientPort = (hb <<8 ) + lb;
[sender setTransferMode:portftp];
[ sender openDataSocket:clientPort ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doOpts:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
NSString *cmd = arguments[1];
NSString *cmdstr = [ NSString stringWithFormat:@"502 Unknown command '%@'",cmd ];
[ sender sendMessage:cmdstr ];
// 502 Unknown command 'sj'
}
// ----------------------------------------------------------------------------------------------------------
-(void)doType:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// 200 Type set to A.
// FIXME - change the data output to the matching type -- we dont do anything with this yet,, there are many types apart from this one.
NSString *cmd = arguments[1];
//if ( [ [cmd lowercaseString] isEqualToString:@"i" ])
// {
NSString *cmdstr = [ NSString stringWithFormat:@"200 Type set to %@.",cmd ];
[ sender sendMessage:cmdstr ];
// }
// else
// {
// NSString *cmdstr = [ NSString stringWithFormat:@"500 'type %@': command not understood.",cmd ];
// [ sender sendMessage:cmdstr ];
// }
}
// ----------------------------------------------------------------------------------------------------------
-(void)doCwd:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// 250
// 500, 501, 502, 421, 530, 550
// 250 CWD command successful.
// NSLog(@"DoCwd arguments is %@",arguments);
NSString *cmdstr;
NSString *cwdDir = [ self fileNameFromArgs:arguments] ; // autoreleased, get the directory that we're being asked for
if ( [ self changedCurrentDirectoryTo:cwdDir ] ) // tries to change to that directory, checks in bounds and viable
{
cmdstr = [ NSString stringWithFormat:@"250 OK. Current directory is %@", [self visibleCurrentDir]]; // currentDir is now in the new place
cmdstr = @"250 CWD command successful.";
}
else
{
cmdstr = @"550 CWD failed.";
}
[ sender sendMessage:cmdstr];
//NSLog(@"currentDir is now %@",currentDir );
}
// ----------------------------------------------------------------------------------------------------------
-(void)doNlst:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// Get the name of any additional directory that we are asked to list, if its empty we use the current directory
NSString *lsDir = [ self fileNameFromArgs:arguments] ; // autoreleased, get the directory that we're being asked for
NSString *listText;
if ([lsDir length]<1) {
lsDir = currentDir;
}
else {
lsDir = [self rootedPath:lsDir ];
}
// NSLog( @"doList currentDir(%@) changeRoot%d", lsDir, server.changeRoot );
// NSLog(@"Will list %@ ",lsDir);
listText = [ server createList:lsDir shortForm:YES];
// NSLog( @"doNLst sending this. %@", listText );
[ sender sendMessage:@"150 Here comes the directory listing."];
[ sender sendDataString:listText ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doStor:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// eg STOR my filename here.mp3 STOR=0 my=1 filename=2 etc
NSFileManager *fs = [NSFileManager defaultManager];
NSString *filename = [ self fileNameFromArgs:arguments]; // autoreleased
NSString *cmdstr;
self.currentFile = [self makeFilePathFrom:filename]; // makes a filepath, using absolute or relative filename
// Check this falls within the area of filesystem we are allowed to write to
if ( [self validNewFilePath:self.currentFile] ) // FIXME - finish function for test
{
// CREATE and then OPEN NEW FILE FOR WRITING
if ([fs createFileAtPath:self.currentFile contents:nil attributes:nil]==YES)
{
currentFileHandle = [ NSFileHandle fileHandleForWritingAtPath:currentFile]; // Open the file handle to write to
cmdstr = [ NSString stringWithFormat:@"150 Opening BINARY mode data connection for '%@'.",filename ]; // autoreleased
}
else
{
// couldn't make file, send out the error
cmdstr = [ NSString stringWithFormat:@"553 %@: Permission denied.", filename ];
}
}
else
{
// couldn't make file as out of root area
cmdstr = [ NSString stringWithFormat:@"553 %@: Permission denied.", filename ];
}
// NSLog(@"FC:doStor %@", currentFile );
[sender sendMessage:cmdstr];
// CHECKME - data connection should have been brought up by client?
if (dataConnection ) // if not we're in trouble. mind u currentFile is doing similar job.
{
// NSLog(@"FC:setting connection state to clientSending");
dataConnection.connectionState = clientSending;
}
else
{
NSLog(@"FC:Erorr Cant set connection state to Client Sending : no Connection yet ");
}
}
// ----------------------------------------------------------------------------------------------------------
-(void)doRetr:(id)sender arguments:(NSArray*)arguments // DOWNLOAD to CLIENT
// ----------------------------------------------------------------------------------------------------------
{
BOOL isDir;
NSString *cmdstr;
NSString *filename = [self fileNameFromArgs:arguments]; // autoreleased
NSString *filePath = [self makeFilePathFrom:filename]; // turns relative or absolute path into format we need
//NSLog(@"FC:doRetr: %@", filePath );
if ( [self accessibleFilePath:filePath ] ) // if this filepath is in rooted area, and is a real file
{
if ( [ [ NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory: &isDir ]) // FIXME - fold into previous line
{
if ( isDir ){ // reject if its a directory request
[ sender sendMessage: [NSString stringWithFormat:@"550 %@: Not a plain file.",filename]];
}
else // SEND FILE
{ // FIXME URGENT - need to stop loading whole file into memory to send
NSMutableData *fileData = [ NSMutableData dataWithContentsOfFile:filePath ]; // FIXME - open in bits ? seems risky opening file in one piece
cmdstr = [ NSString stringWithFormat:@"150 Opening BINARY mode data connection for '%@'.",filename ];
[sender sendMessage:cmdstr];
[ sender sendData:fileData ]; // Send file
fileData = nil;
}
}
}
else // doesn't exist or not in basedir sandbox
{
cmdstr = [ NSString stringWithFormat:@"50 %@ No such file or directory.",filename ];
NSLog(@"FC:doRetr: file %@ doesnt' exist ", filePath);
[sender sendMessage:cmdstr];
}
}
// ----------------------------------------------------------------------------------------------------------
-(void)doDele:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
NSString *cmdStr;
NSError *error;
NSString *filename =[self fileNameFromArgs:arguments]; // autoreleased
NSString *filePath = [self makeFilePathFrom:filename];
//NSLog(@"filename is %@",filename);
// attempt to delete the file
if ( [self accessibleFilePath:filePath ]) // exists and can access
{
if ([[ NSFileManager defaultManager ] removeItemAtPath:filePath error:&error ])
{
cmdStr = [ NSString stringWithFormat:@"250 DELE command successful." ];
[ server didReceiveFileListChanged]; // Addition by Brendan copied in by Rich 16/12/08
}
else
{
cmdStr = [ NSString stringWithFormat:@"550 DELE command unsuccessful." ]; // FIXME put correct error code in
}
}
else
{
cmdStr = [ NSString stringWithFormat:@"550 %@ No such file or directory.", filename];
}
[ sender sendMessage:cmdStr ];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doMlst:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
NSString *filename = [self fileNameFromArgs: arguments];
NSString *cmdstr = [ NSString stringWithFormat:@"150 Opening BINARY mode data connection for '%@'.",filename ];
// tell connection to expect a file
[sender sendMessage:cmdstr]; // FIXME - this doesn't do anything beyond respond with first message
/* typiccal output to generate
250: MLST 2012.pdf
Type=file;Size=2420017;Modify=20080808074805;Perm=adfrw;Unique=AgAADpIHZwA; /Users/monsta/Documents/2012.pdf
End
*/
}
// ----------------------------------------------------------------------------------------------------------
-(void)doSize:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
NSString *cmdStr;
NSString *filename = [self fileNameFromArgs: arguments]; // Autoreleased
NSString *filePath = [self makeFilePathFrom:filename]; // Autoreleased
if ([self accessibleFilePath:filePath]) // Can we reach that file ?
{
if ([self fileSize:filePath] < 10240) // If small enough for old style size command
{
cmdStr = [ NSString stringWithFormat:@"213 %qu",[self fileSize:filePath] ]; // report size
}
else
{
cmdStr = [ NSString stringWithFormat:@"550 %@ file too large for SIZE.",filename ];
}
}
else
{
cmdStr = [ NSString stringWithFormat:@"550 %@ No such file or directory.",filename ]; // report file not found
}
// tell connection to expect a file
[sender sendMessage:cmdStr];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doMkdir:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
//NSLog(@"current dir is %@",currentDir);
NSString *cmdStr;
NSString *p = [self makeFilePathFrom:[self fileNameFromArgs:arguments]];
NSFileManager *fs = [NSFileManager defaultManager];
if ( [self validNewFilePath:p ]) // FIXME - make sure function works. see function
{
if( [fs fileExistsAtPath:p isDirectory:nil] )
{
cmdStr = [ NSString stringWithFormat:@"Error %@ exists",[self fileNameFromArgs:arguments] ];
}
else
{
// FIXME - check that its ok to make a directory in this position
[fs createDirectoryAtPath:p withIntermediateDirectories:YES attributes:nil error:nil];
cmdStr = [ NSString stringWithFormat:@"250 MKD command successful."];
}
}
[sender sendMessage:cmdStr];
}
// ----------------------------------------------------------------------------------------------------------
-(void)doCdUp:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
//NSLog(@"CurrentDir is %@",[self visibleCurrentDir]);
NSString *upDir=[[self visibleCurrentDir] stringByDeletingLastPathComponent];
if ( [self changedCurrentDirectoryTo:upDir] ) // checks to see if its ok before moving
{
[sender sendMessage:@"250 CDUP command successful."];
}
else
{
// create message saying you cant go to that directory - FIXME
[ sender sendMessage:@"550 CDUP command failed." ]; // CHECKME - look at a typical ftp mkdr command failure message
}
}
// ----------------------------------------------------------------------------------------------------------
-(void)doRnfr:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
self.rnfrFilename = [self makeFilePathFrom:[self fileNameFromArgs:arguments]];
if ( [ self accessibleFilePath:self.rnfrFilename ] ) // FIXME - finish function
{
if ( [[ NSFileManager defaultManager] fileExistsAtPath: rnfrFilename ] )
{
[ sender sendMessage:@"350 RNFR command successful." ];
}
else
[ sender sendMessage:@"550 RNFR command failed." ];
}
}
// ----------------------------------------------------------------------------------------------------------
-(void)doRnto:(id)sender arguments:(NSArray*)arguments
// ----------------------------------------------------------------------------------------------------------
{
// FIXME - check its ok to use the new filename - ie in sandbox/basedir
if ( self.rnfrFilename == nil ){
[ sender sendMessage:@"550 RNTO command failed." ];
return;
}
NSError *error;
NSString *rntoFilename = [self makeFilePathFrom:[self fileNameFromArgs:arguments]];
//NSLog(@"%@", rnfrFilename );