File: ftpclient.m

package info (click to toggle)
ftp.app 0.2-3
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 420 kB
  • ctags: 30
  • sloc: objc: 2,105; makefile: 55; sh: 17
file content (1185 lines) | stat: -rw-r--r-- 32,769 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
/*
 Project: FTP

 Copyright (C) 2005-2007 Riccardo Mottola

 Author: Riccardo Mottola

 Created: 2005-03-30

 FTP client class

 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.

 */

/*
 * this class handles acts as a remote client with the FTP server.
 * the connection modes, default, active (port) and passive
 * can be set using the three setPort* methods
 */


#import "ftpclient.h"
#import "AppController.h"
#import "fileElement.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#ifdef _WIN32
#include <fcntl.h>
#else
#include <arpa/inet.h>  /* for inet_ntoa and similar */
#include <netdb.h>
#define INVALID_SOCKET -1
#define closesocket close
#endif /* WIN32 */


#define MAX_CONTROL_BUFF 2048
#define MAX_DATA_BUFF 2048

#if defined(__linux__)
#define socklentype socklen_t
#else
#define socklentype int
#endif

void initStream(streamStruct *ss, int socket)
{
    ss->socket = socket;
    ss->position = 0;
    ss->len = 0;
    ss->buffer[0] = '\0';
}

int getChar(streamStruct* ss)
{
    int result;
    BOOL gotEof;

    gotEof = NO;
    if (ss->position == ss->len)
    {
        int read;

        read = recv(ss->socket, ss->buffer, MAX_SOCK_BUFF, 0);
        if (read > 0)
        {
            ss->len = read;
            ss->position = 0;
        } else if (read == 0)
        {
            ss->len = 0;
            ss->position = 0;
            ss->buffer[0] = '\0';
            gotEof = YES;
        } else
        {
            ss->len = 0;
            ss->position = 0;
            NSLog(@"error sock read");
            perror("getChar:read");
            ss->buffer[0] = '\0';
            gotEof = YES;
        }
    }
    if (gotEof)
        result = EOF;
    else {    
        result = ss->buffer[ss->position];
        ss->position++;
    }
    return result;
}

@implementation FtpClient

+ (void)connectWithPorts:(NSArray *)portArray
{
    NSAutoreleasePool *pool;
    NSConnection *serverConnection;
    FtpClient    *serverObject;
	
    pool = [[NSAutoreleasePool alloc] init];
	
    serverConnection = [NSConnection
            connectionWithReceivePort:[portArray objectAtIndex:0]
							 sendPort:[portArray objectAtIndex:1]];
	
    serverObject = [self alloc];
    [(id)[serverConnection rootProxy] setServer:serverObject];
    [serverObject release];
	
    [[NSRunLoop currentRunLoop] run];
    [pool release];
	
    return;
}

- (id)initWithController:(id)cont :(connectionModes)cMode
{
    if (!(self =[super initWithController:cont]))
        return nil;

    switch (cMode)
    {
        case defaultMode:
            [self setPortDefault];
            break;
        case portMode:
            [self setPortPort];
            break;
        case passiveMode:
            [self setPortPassive];
            break;
        default:
            [self setPortDefault];
    }
#ifdef _WIN32
    WORD wVersionRequested;
    WSADATA wsaData;
    wVersionRequested = MAKEWORD( 1, 1 );

    WSAStartup(wVersionRequested, &wsaData);
    NSLog(@"inited WinSock");
#endif
    connected = NO;
    return self;
}

/* three methods to set the connection handling */
- (void)setPortDefault
{
    usesPassive = NO;
    usesPorts = NO;
}

- (void)setPortPort
{
    usesPassive = NO;
    usesPorts = YES;
}

- (void)setPortPassive
{
    usesPassive = YES;
    usesPorts = NO;
}

/*
 changes the current working directory
 this directory is implicit in many other actions
 */
- (void)changeWorkingDir:(NSString *)dir
{
    char            tempStr[MAX_CONTROL_BUFF];
    char            tempStr2[MAX_CONTROL_BUFF];
    NSMutableArray *reply;

    if (!connected)
        return;
	
    [dir getCString:tempStr2];
    sprintf(tempStr, "CWD %s\r\n", tempStr2);
    [self writeLine:tempStr];
    if ([self readReply:&reply] == 250)
        [super changeWorkingDir:dir];
    else
        NSLog(@"cwd failed");
}

/* if we have a valid controller, we suppose it respons to appendTextToLog */
/* RM: is there a better way to append a newline? */
- (void)logIt:(NSString *)str
{
    NSMutableString *tempStr;
    
    if (controller == NULL)
        return;
    tempStr = [NSMutableString stringWithCapacity:([str length] + 1)];
    [tempStr appendString:str];
    [tempStr appendString:@"\n"];
    [controller appendTextToLog:tempStr];
}


/*
 read the reply of a command, be it single or multi-line
 returned is the first numerical code
 NOTE: the parser is NOT robust in handling errors
 */
#define NUMCODELEN 4

- (int)readReply :(NSMutableArray **)result
{
    char  buff[MAX_CONTROL_BUFF];
    int   readBytes;
    int   ch;
    /* the first numerical code, in case of multi-line output it is followed
       by '-' in the first line and by ' ' in the last line */
    char  numCodeStr[NUMCODELEN];
    int   numCode;
    int   startNumCode;
    char  separator;
    enum  states { N1, N2, N3, SEPARATOR, CHARS, GOTR, END };
    enum  states state;
    BOOL  multiline;

    readBytes = 0;
    state = N1;
    separator = 0;
    multiline = NO;
    *result = [NSMutableArray arrayWithCapacity:1];

    // TODO: protect against numCodeStr overflow
    while (!(state == END))
    {
        ch = getChar(&ctrlStream);
//	NSLog(@"read char: %c", ch);
        if (ch == EOF)
            state = END;

        switch (state)
        {
            case N1:
                buff[readBytes] = ch;
                if (readBytes < NUMCODELEN)
                    numCodeStr[readBytes] = ch;
                readBytes++;
                if (ch == ' ') /* skip internal lines of multi-line */
                    state = CHARS;
                else
                    state = N2;
                break;
            case N2:
                buff[readBytes] = ch;
                numCodeStr[readBytes] = ch;
                readBytes++;
                state = N3;
                break;
            case N3:
                buff[readBytes] = ch;
                numCodeStr[readBytes] = ch;
                readBytes++;
                state = SEPARATOR;
                break;
            case SEPARATOR:
                buff[readBytes] = ch;
                numCodeStr[readBytes] = '\0';
                readBytes++;
                numCode = atoi(numCodeStr);
                separator = ch;
                state = CHARS;
                break;
            case CHARS:
                if (ch == '\r')
                    state = GOTR;
                else
                {
                    buff[readBytes++] = ch;
                }
                break;
            case GOTR:
                if (ch == '\n')
                {
                    buff[readBytes] = '\0';
                    [self logIt:[NSString stringWithCString:buff]];
                    [*result addObject:[NSString stringWithCString:buff]];
                    readBytes = 0;
                    if (separator == ' ')
                    {
                        if (multiline)
                        {
                            if (numCode == startNumCode)
                                state = END;
                        } else
                        {
                            startNumCode = numCode;
                            state = END;
                        }
                    } else
                    {
                        startNumCode = numCode;
                        multiline = YES;
                        state = N1;
                    }
                }
                break;
            case END:
                NSLog(@"EOF reached prematurely");
                break;
            default:
                NSLog(@"Duh, a case default in the readReply parser");
        }
    }
    [*result retain];
    return startNumCode;
}

/*
 writes a single line to the control connection, logging it always
 */
- (int)writeLine:(char *)line
{
    return [self writeLine:line byLoggingIt:YES];
}

/*
 writes a single line to the control connection
 */
- (int)writeLine:(char *)line byLoggingIt:(BOOL)doLog
{
    int sentBytes;
    int bytesToSend;

    bytesToSend = strlen(line);
    if (doLog)
        [self logIt:[NSString stringWithCString:line length:(bytesToSend - 2)]];
    if ((sentBytes = send(controlSocket, line, strlen(line), 0)) < bytesToSend)
        NSLog(@"sent %d out of %d", sentBytes, bytesToSend);
    return sentBytes;
}


- (int)setTypeToI
{
    NSMutableArray *reply;
    int            retVal;
    
    retVal = [self writeLine:"TYPE I\r\n"];
    if ( retVal > 0)
    {
        [self readReply:&reply];
        [reply release];
    }
       
    return retVal;
}

- (int)setTypeToA
{
    NSMutableArray *reply;
    int            retVal;

    retVal = [self writeLine:"TYPE A\r\n"];
    NSLog(@"retval: %d", retVal);
    if ( retVal > 0)
    {
        [self readReply:&reply];
        [reply release];
    }
    
    return retVal;
}

- (oneway void)retrieveFile:(fileElement *)file to:(LocalClient *)localClient beingAt:(int)depth;
{
    NSString           *fileName;
    unsigned long long fileSize;
    char               fNameCStr[MAX_CONTROL_BUFF];
    char               command[MAX_CONTROL_BUFF];
    char               buff[MAX_DATA_BUFF];
    FILE               *localFileStream;
    int                bytesRead;
    NSMutableArray     *reply;
    struct sockaddr    from;
    int                fromLen;
    unsigned int       minimumPercentIncrement;
    unsigned int       progressIncBytes;
    int                replyCode;
    unsigned long long totalBytes;
    NSString           *localPath;
    BOOL               gotFile;

    fromLen = sizeof(from);    

    fileName = [file filename];
    fileSize = [file size];
    minimumPercentIncrement = fileSize / 100; // we should guard against maxint

    localPath = [[localClient workingDir] stringByAppendingPathComponent:fileName];

    if ([file isDir])
    {
        NSString     *pristineLocalPath;  /* original path */
        NSString     *pristineRemotePath; /* original path */
        NSArray      *dirList;
        NSString     *remoteDir;
        NSEnumerator *en;
        fileElement  *fEl;

        if (depth > MAX_DIR_RECURSION)
        {
            NSLog(@"Max depth reached: %d", depth);
            return;
        }

        pristineLocalPath = [[localClient workingDir] retain];
        pristineRemotePath = [[self workingDir] retain];
        
        remoteDir = [[self workingDir] stringByAppendingPathComponent:fileName];
        [self changeWorkingDir:remoteDir];

        if ([localClient createNewDir:localPath] == YES)
        {
            [localClient changeWorkingDir:localPath];
    
            dirList = [self dirContents];
            en = [dirList objectEnumerator];
            while ((fEl = [en nextObject]))
            {
                NSLog(@"recurse, download : %@", [fEl filename]);
                [self retrieveFile:fEl to:localClient beingAt:depth+1];
            }
        }
        /* we get back were we started */
        [self changeWorkingDir:pristineRemotePath];
        [localClient changeWorkingDir:pristineLocalPath];
        [pristineLocalPath release];
        [pristineRemotePath release];
        return;
    }

    /* lets settle to a plain binary standard type */
    [self setTypeToI];
    
    if ([self initDataConn] < 0)
    {
        NSLog(@"error initiating data connection, retrieveFile");
        return;
    }
    
    [fileName getCString:fNameCStr];
    sprintf(command, "RETR %s\r\n", fNameCStr);
    [self writeLine:command];
    replyCode = [self readReply:&reply];
    NSLog(@"%d reply is %@: ", replyCode, [reply objectAtIndex:0]);

    if(replyCode != 150)
    {
        [controller showAlertDialog:@"Unexpected server error."];
        NSLog(@"Unexpected condition in retrieve");
        return; /* we have an error or some unexpected condition */
    }
    [reply release];
    
    if ([self initDataStream] < 0)
    {
        [controller showAlertDialog:@"Unexpected connection error."];
        return;
    }
    
    localFileStream = fopen([localPath cString], "w");
    if (localFileStream == NULL)
    {
        [controller showAlertDialog:@"Opening of local file failed.\nCheck permissions and free space."];
        perror("local fopen failed");
        return;
    }
    
    totalBytes = 0;
    progressIncBytes = 0;
    gotFile = NO;
    [controller setThreadRunningState:YES];
    [controller setTransferBegin:fileName :fileSize];
    while (!gotFile)
    {
        bytesRead = recv(localSocket, buff, MAX_DATA_BUFF, 0);
        if (bytesRead == 0)
            gotFile = YES;
        else if (bytesRead < 0)
        {
            gotFile = YES;
            NSLog(@"error on socket read, retrieve file");
        } else
        {
            if (fwrite(buff, sizeof(char), bytesRead, localFileStream) < bytesRead)
            {
                NSLog(@"file write error, retrieve file");
            }
            totalBytes += bytesRead;
            progressIncBytes += bytesRead;
            if (progressIncBytes > minimumPercentIncrement) 
            {
                [controller setTransferProgress:[NSNumber numberWithUnsignedLongLong:totalBytes]];
                progressIncBytes = 0;
            }
        }
    }

    [controller setTransferEnd:[NSNumber numberWithUnsignedLongLong:totalBytes]];
    
    fclose(localFileStream);
    [self closeDataStream];
    [self readReply:&reply];
    [reply release];
    [controller setThreadRunningState:NO];
}

- (oneway void)storeFile:(fileElement *)file from:(LocalClient *)localClient beingAt:(int)depth
{
    NSString           *fileName;
    unsigned long long fileSize;
    char               fNameCStr[MAX_CONTROL_BUFF];
    char               command[MAX_CONTROL_BUFF];
    char               buff[MAX_DATA_BUFF];
    FILE               *localFileStream;
    NSMutableArray     *reply;
    int                bytesRead;
    struct sockaddr    from;
    int                fromLen;
    unsigned int       minimumPercentIncrement;
    unsigned int       progressIncBytes;
    int                replyCode;
    unsigned long long totalBytes;
    NSString           *localPath;
    BOOL               gotFile;

    
    fromLen = sizeof(from);

    fileName = [file filename];
    fileSize = [file size];
    minimumPercentIncrement = fileSize / 100; // we should guard against maxint

    localPath = [[localClient workingDir] stringByAppendingPathComponent:fileName];

    if ([file isDir])
    {
        NSString     *pristineLocalPath;  /* original path */
        NSString     *pristineRemotePath; /* original path */
        NSArray      *dirList;
        NSString     *remotePath;
        NSEnumerator *en;
        fileElement  *fEl;

        if (depth > MAX_DIR_RECURSION)
        {
            NSLog(@"Max depth reached: %d", depth);
            return;
        }

        pristineLocalPath = [[localClient workingDir] retain];
        pristineRemotePath = [[self workingDir] retain];

        NSLog(@"it is a dir: %@", fileName);
        remotePath = [pristineRemotePath stringByAppendingPathComponent:fileName];
        [localClient changeWorkingDir:localPath];
        NSLog(@"local dir changed: %@", [localClient workingDir]);

        if ([self createNewDir:remotePath] == YES)
        {
            NSLog(@"remote dir created succesfully");
            [self changeWorkingDir:remotePath];

            dirList = [localClient dirContents];
            en = [dirList objectEnumerator];
            while ((fEl = [en nextObject]))
            {
                NSLog(@"recurse, upload : %@", [fEl filename]);
                [self storeFile:fEl from:localClient beingAt:(depth+1)];
            }
        }
        /* we get back were we started */
        [self changeWorkingDir:pristineRemotePath];
        [localClient changeWorkingDir:pristineLocalPath];
        [pristineLocalPath release];
        [pristineRemotePath release];
        return;
    }
    
    /* lets settle to a plain binary standard type */
    [self setTypeToI];

    if ([self initDataConn] < 0)
    {
        [controller showAlertDialog:@"Error initiating the Data Connection."];
        NSLog(@"error initiating data connection, storeFile");
        return;
    }

    [fileName getCString:fNameCStr];
    sprintf(command, "STOR %s\r\n", fNameCStr);
    [self writeLine:command];
    replyCode = [self readReply:&reply];
    NSLog(@"%d reply is %@: ", replyCode, [reply objectAtIndex:0]);

    if (replyCode >= 550 && replyCode <= 559)
    {
        [controller showAlertDialog:[reply objectAtIndex:0]];
        [self logIt: [reply objectAtIndex:0]];
        [reply release];
        return;
    }
    [reply release];

    
    if ([self initDataStream] < 0)
    {
        [controller showAlertDialog:@"Unexpected connection error."];
        return;
    }


    localFileStream = fopen([localPath cString], "r");
    if (localFileStream == NULL)
    {
        [controller showAlertDialog:@"Opening of local file failed.\n Check permissions."];
        perror("local fopen failed");
        return;
    }

    totalBytes = 0;
    progressIncBytes = 0;
    gotFile = NO;
    [controller setThreadRunningState:YES];
    [controller setTransferBegin:fileName :fileSize];
    while (!gotFile)
    {
        bytesRead = fread(buff, sizeof(char), MAX_DATA_BUFF, localFileStream);
        if (bytesRead == 0)
        {
            gotFile = YES;
            if (!feof(localFileStream))
                NSLog(@"error on file read, store file");
            else
                NSLog(@"feof");
        } else
        {
            if (write(localSocket, buff, bytesRead) < bytesRead)
            {
                NSLog(@"socket write error, store file");
            }
            totalBytes += bytesRead;
            progressIncBytes += bytesRead;
            if (progressIncBytes > minimumPercentIncrement) 
            {
                [controller setTransferProgress:[NSNumber numberWithUnsignedLongLong:totalBytes]];
                progressIncBytes = 0;
            }
        }
    }
    [controller setTransferEnd:[NSNumber numberWithUnsignedLongLong:totalBytes]];
    
    fclose(localFileStream);
    [self closeDataStream];
    [self readReply:&reply];
    [reply release];
    [controller setThreadRunningState:NO];
}

- (void)deleteFile:(fileElement *)file beingAt:(int)depth
{
    NSString           *fileName;
    NSString           *localPath;
    NSFileManager      *fm;
    char               command[MAX_CONTROL_BUFF];
    NSMutableArray     *reply;
    int                replyCode;

    fm = [NSFileManager defaultManager];
    fileName = [file filename];
    localPath = [[self workingDir] stringByAppendingPathComponent:fileName];

    if ([file isDir])
    {
        NSString     *pristineRemotePath; /* original path */
        NSArray      *dirList;
        NSString     *remotePath;
        NSEnumerator *en;
        fileElement  *fEl;

        if (depth > 3)
        {
            NSLog(@"Max depth reached: %d", depth);
            return;
        }

        pristineRemotePath = [[self workingDir] retain];

        NSLog(@"it is a dir: %@", fileName);
        remotePath = [pristineRemotePath stringByAppendingPathComponent:fileName];

        NSLog(@"remote dir created succesfully");
        [self changeWorkingDir:remotePath];

        dirList = [self dirContents];
        en = [dirList objectEnumerator];
        while ((fEl = [en nextObject]))
        {
            NSLog(@"recurse, delete : %@", [fEl filename]);
            [self deleteFile:fEl beingAt:(depth+1)];
        }

        /* we get back were we started */
        [self changeWorkingDir:pristineRemotePath];
        [pristineRemotePath release];
    }

    sprintf(command, "DELE %s\r\n", [fileName cString]);
    [self writeLine:command];
    replyCode = [self readReply:&reply];
    NSLog(@"%d reply is %@: ", replyCode, [reply objectAtIndex:0]);
    [reply release];
    
}

/* initialize a connection */
/* set up and connect the control socket */
- (int)connect:(int)port :(char *)server
{
    struct hostent      *hostentPtr;
    char                *tempStr;
    socklentype         addrLen; /* socklen_t on some systems? */
    NSMutableArray      *reply;

    NSLog(@"connect to %s : %d", server, port);

    if((hostentPtr = gethostbyname(server)) == NULL)
    {
        NSLog(@"Could not resolve %s", server);
        return ERR_COULDNT_RESOLVE;
    }
    BCOPY((char *)hostentPtr->h_addr, (char *)&remoteSockName.sin_addr, hostentPtr->h_length);
    remoteSockName.sin_family = PF_INET;
    remoteSockName.sin_port = htons(port);

    tempStr = inet_ntoa(remoteSockName.sin_addr);

    if ((controlSocket = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
    {
        perror("socket failed: ");
        return ERR_SOCKET_FAIL;
    }
    if (connect(controlSocket, (struct sockaddr*) &remoteSockName, sizeof(remoteSockName)) < 0)
    {
        perror("connect failed: ");
        return ERR_CONNECT_FAIL;
    }

    /* we retrieve now the local name of the created socked */
    /* the local port is for example important as default data port */
    addrLen = sizeof(localSockName);
    if (getsockname(controlSocket, (struct sockaddr *)&localSockName, &addrLen) < 0)
    {
        perror("ftpclient: getsockname");
        return ERR_GESOCKNAME_FAIL;
    }
    
    initStream(&ctrlStream, controlSocket);
    [self readReply :&reply];
    [reply release];
    return 0;
}

- (void)disconnect
{
    NSMutableArray *reply;
    
    [self writeLine:"QUIT\r\n"];
    [self readReply:&reply];
    connected = NO;
}

- (int)authenticate:(char *)user :(char *)pass
{
    char           tempStr[MAX_CONTROL_BUFF];
    NSMutableArray *reply;
    int            replyCode;

    sprintf(tempStr, "USER %s\r\n", user);
    [self writeLine:tempStr];
    replyCode = [self readReply:&reply];
    if (replyCode == 530)
    {
        NSLog(@"Not logged in: %@", [reply objectAtIndex:0]);
        [reply release];
        [self disconnect];
        return -1;
    }
    [reply release];
    
    sprintf(tempStr, "PASS %s\r\n", pass);
    [self writeLine:tempStr byLoggingIt:NO];
    replyCode = [self readReply:&reply];
    if (replyCode == 530)
    {
        NSLog(@"Not logged in: %@", [reply objectAtIndex:0]);
        [reply release];
        [self disconnect];
        return -1;
    }
    [reply release];
    
    connected = YES;

    /* get home directory as dir we first connected to */
    [self writeLine:"PWD\r\n"];
    [self readReply:&reply];
    if ([reply count] >= 1)
    {
        NSString *line;
        unsigned int length;
        unsigned int first;
        unsigned int last;
        unsigned int i;
        
        line = [reply objectAtIndex:0];
        NSLog(@"pwd reply is: %@", line);
        length = [line length];
        i = 0;
        while (i < length && ([line characterAtIndex:i] != '\"'))
            i++;
        first = i;
        if (first < length)
        {
            first++;
            i = length-1;
            while (i > 0 &&  ([line characterAtIndex:i] != '\"'))
                i--;
            last = i;
            homeDir = [[line substringWithRange: NSMakeRange(first, last-first)] retain];
            NSLog(@"homedir: %@", homeDir);
        } else
            homeDir = nil;
    }
    return 0;
}

/* initialize the data connection */
- (int)initDataConn
{
    socklentype addrLen; /* socklen_t on some systems ? */
    int         socketReuse;
    
    socketReuse = YES;

    /* passive mode */
    if (usesPassive)
    {
        NSMutableArray *reply;
        int            replyCode;
        NSScanner      *addrScan;
        int            a1, a2, a3, a4;
        int            p1, p2;
        
        if ((dataSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
        {
            perror("socket in initDataConn");
            return -1;
        }

        [self writeLine:"PASV\r\n"];
        replyCode = [self readReply:&reply];
        if (replyCode != 227)
        {
            NSLog(@"passive mode failed");
            return -1;
        }
        NSLog(@"pasv reply is: %d %@", replyCode, [reply objectAtIndex:0]);

        addrScan = [NSScanner scannerWithString:[reply objectAtIndex:0]];
        [addrScan setCharactersToBeSkipped:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
        if ([addrScan scanInt:NULL] == NO)
        {
            NSLog(@"error while scanning pasv address");
            return -1;
        }
        NSLog(@"skipped result code");
        if ([addrScan scanInt:&a1] == NO)
        {
            NSLog(@"error while scanning pasv address");
            return -1;
        }
        NSLog(@"got first");
        if ([addrScan scanInt:&a2] == NO)
        {
            NSLog(@"error while scanning pasv address");
            return -1;
        }
        NSLog(@"got second");
        if ([addrScan scanInt:&a3] == NO)
        {
            NSLog(@"error while scanning pasv address");
            return -1;
        }
        if ([addrScan scanInt:&a4] == NO)
        {
            NSLog(@"error while scanning pasv address");
            return -1;
        }
        if ([addrScan scanInt:&p1] == NO)
        {
            NSLog(@"error while scanning pasv port");
            return -1;
        }
        if ([addrScan scanInt:&p2] == NO)
        {
            NSLog(@"error while scanning pasv port");
            return -1;
        }
        NSLog(@"read: %d %d %d %d : %d %d", a1, a2, a3, a4, p1, p2);

        dataSockName.sin_family = AF_INET;
        dataSockName.sin_addr.s_addr = htonl((a1 << 24) | (a2 << 16) | (a3 << 8) | a4);
        dataSockName.sin_port = htons((p1 << 8) | p2);

        if (connect(dataSocket, (struct sockaddr *) &dataSockName, sizeof(dataSockName)) < 0)
        {
            perror("connect in initDataConn");
            return -1;
        }
        
        return 0;
    }

    /* active mode, default or PORT arbitrated */
    dataSockName = localSockName;

    /* system picks up a port */
    if (usesPorts == YES)
        dataSockName.sin_port = 0;
    
    if ((dataSocket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
    {
        perror("socket in initDataConn");
        return -1;
    }

    /* if we use the default port, we set the option to reuse the port */
    /* linux is happier if we set both ends that way */
    if (usesPorts == NO)
    {
        if (setsockopt(dataSocket, SOL_SOCKET, SO_REUSEADDR, &socketReuse, sizeof (socketReuse)) < 0)
        {
            perror("ftpclient: setsockopt (reuse address) on data");
        }
        if (setsockopt(controlSocket, SOL_SOCKET, SO_REUSEADDR, &socketReuse, sizeof (socketReuse)) < 0)
        {
            perror("ftpclient: setsockopt (reuse address) on control");
        }
    }
    
    if (bind(dataSocket, (struct sockaddr *)&dataSockName, sizeof (dataSockName)) < 0)
    {
        perror("ftpclient: bind");
        return -1;
    }

    if (usesPorts == YES)
    {
        addrLen = sizeof (dataSockName);
        if (getsockname(dataSocket, (struct sockaddr *)&dataSockName, &addrLen) < 0)
        {
            perror("ftpclient: getsockname");
            return -1;
        }
    }
    
    if (listen(dataSocket, 1) < 0)
    {
        perror("ftpclient: listen");
        return -1;
    }

    if (usesPorts == YES)
    {
        union addrAccess { /* we use this union to extract the 8 bytes of an address */
            struct in_addr   sinAddr;
            unsigned char    ipv4[4];
        } addr;
        NSMutableArray *reply;
        char           tempStr[256];
        unsigned char  p1, p2;
        int            returnCode;
        unsigned int   port;


        addr.sinAddr = dataSockName.sin_addr;
        port = ntohs(dataSockName.sin_port);
        p1 = (port & 0xFF00) >> 8;
        p2 = port & 0x00FF;
        sprintf(tempStr, "PORT %u,%u,%u,%u,%u,%u\r\n", addr.ipv4[0], addr.ipv4[1], addr.ipv4[2], addr.ipv4[3], p1, p2);
        [self writeLine:tempStr];
        NSLog(@"port str: %s", tempStr);
        if ((returnCode = [self readReply:&reply]) != 200)
        {
            NSLog(@"error occoured in port command: %@", [reply objectAtIndex:0]);
            return -1;
        }
    }
    return 0;
}

- (int)initDataStream
{
    struct sockaddr from;
    socklentype     fromLen;
    
    fromLen = sizeof(from);
    if (usesPassive)
    {
        initStream(&dataStream, dataSocket);
        localSocket = dataSocket;
    } else
    {
        if ((localSocket = accept(dataSocket, &from, &fromLen)) < 0)
        {
            perror("accepting socket, initDataStream: ");
        }
        initStream(&dataStream, localSocket);
    }
/*
    if (dataStream == NULL)
    {
        perror("data stream opening failed");
        return -1;
    } */
    NSLog(@"data stream open");
    return 0;
}

- (int)closeDataConn
{
    closesocket(dataSocket);
    return 0;
}

- (void)closeDataStream
{
    // a passive localSocket is just a copy of the dataSocket
    if (usesPassive == NO)
        closesocket(localSocket);
    // apparently it is not true that fclose closes the underlying
    // descriptor, without closing dataSocket we got a bind error
    // at the next connection attempt
    [self closeDataConn];
}

/*
 creates a new directory
 tries to guess if the given dir is relative (no starting /) or absolute
 Is this portable to non-unix OS's?
 */
- (BOOL)createNewDir:(NSString *)dir
{
    NSString       *remotePath;
    char           command[MAX_CONTROL_BUFF];
    char           pathCStr[MAX_CONTROL_BUFF];
    NSMutableArray *reply;
    int            replyCode;

    if ([dir hasPrefix:@"/"])
    {
        NSLog(@"%@ is an absolute path", dir);
        remotePath = dir;
    } else
    {
        NSLog(@"%@ is a relative path", dir);
        remotePath = [[self workingDir] stringByAppendingPathComponent:dir];
    }

    [remotePath getCString:pathCStr];
    sprintf(command, "MKD %s\r\n", pathCStr);
    [self writeLine:command];
    replyCode = [self readReply:&reply];
    if (replyCode == 257)
        return YES;
    else
    {
        NSLog(@"remote mkdir code: %d %@", replyCode, [reply objectAtIndex:0]);
        return NO;
    }
}


/* RM again: a better path limit is needed */
- (NSArray *)dirContents
{
    int                ch;
    char               buff[MAX_DATA_BUFF];
    int                readBytes;
    enum               states_m1 { READ, GOTR };
    enum               states_m1 state;
    NSMutableArray     *listArr;
    fileElement        *aFile;
    char               path[4096];
    NSMutableArray     *reply;
    int                replyCode;
    
    if (!connected)
        return nil;
    
    [workingDir getCString:path];

    /* lets settle to a plain ascii standard type */
    if ([self setTypeToA] < 0)
    {
        connected = NO;
        NSLog(@"Timed out.");
        return nil;
    }
    
    /* create an array with a reasonable starting size */
    listArr = [NSMutableArray arrayWithCapacity:5];
    
    [self initDataConn];
    [self writeLine:"LIST\r\n"];
    [self readReply:&reply];

    if ([self initDataStream] < 0)
        return nil;

    /* read the directory listing, each line being CR-LF terminated */
    state = READ;
    readBytes = 0;
    while ((ch = getChar(&dataStream)) != EOF)
    {
        if (ch == '\r')
            state = GOTR;
        else if (ch == '\n' && state == GOTR)
        {
            
            buff[readBytes] = '\0';
            fprintf(stderr, "%s\n", buff);
            [self logIt:[NSString stringWithCString:buff]];
            state = READ; /* reset the state for a new line */
            readBytes = 0;
            aFile = [[fileElement alloc] initWithLsLine:buff];
            if (aFile)
                [listArr addObject:aFile];
        } else
            buff[readBytes++] = ch;
    }
/* FIXME ***********    if (ferror(dataStream))
    {
        perror("error in reading data stream: ");
    } else if (feof(dataStream))
    {
         fprintf(stderr, "feof\n");
    } */
    [self closeDataStream];

    replyCode = [self readReply:&reply];
    
    return [NSArray arrayWithArray:listArr];
}

@end