/
StreamBasedConnection.m
1867 lines (1633 loc) · 56.9 KB
/
StreamBasedConnection.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) 2005, 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 "StreamBasedConnection.h"
#import "ConnectionThreadManager.h"
#import "InterThreadMessaging.h"
#import "NSData+Connection.h"
#import "NSObject+Connection.h"
#import "NSFileManager+Connection.h"
#import "RunLoopForwarder.h"
#import "CKCacheableHost.h"
#import "CKTransferRecord.h"
#import "AbstractConnectionProtocol.h"
#import "CKInternalTransferRecord.h"
#import "NSString+Connection.h"
#import <sys/types.h>
#import <sys/socket.h>
#import <netinet/in.h>
#import <sys/types.h>
#import <sys/socket.h>
#import <arpa/inet.h>
#import <poll.h>
#import <netdb.h>
#import <sys/types.h>
#import <sys/sysctl.h>
#import <Security/Security.h>
const unsigned int kStreamChunkSize = 2048;
const NSTimeInterval kStreamTimeOutValue = 10.0; // 10 second timeout
NSString *StreamBasedErrorDomain = @"StreamBasedErrorDomain";
NSString *SSLErrorDomain = @"SSLErrorDomain";
OSStatus SSLReadFunction(SSLConnectionRef connection, void *data, size_t *dataLength);
OSStatus SSLWriteFunction(SSLConnectionRef connection, const void *data, size_t *dataLength);
@interface StreamBasedConnection (Private)
- (void)checkQueue;
- (void)processFileCheckingQueue;
- (void)recalcUploadSpeedWithBytesSent:(unsigned)length;
- (void)recalcDownloadSpeedWithBytesSent:(unsigned)length;
// SSL Stuff
- (void)initializeSSL;
- (void)negotiateSSLWithData:(NSData *)data;
- (int)handshakeWithInputData:(NSMutableData *)inputData
outputData:(NSMutableData *)outputData;
@end
@implementation StreamBasedConnection
- (id)initWithHost:(NSString *)host
port:(NSString *)port
username:(NSString *)username
password:(NSString *)password
error:(NSError **)error
{
if (self = [super initWithHost:host port:port username:username password:password error:error])
{
_sendBufferLock = [[NSLock alloc] init];
_sendBuffer = [[NSMutableData data] retain];
_createdThread = [NSThread currentThread];
myStreamFlags.sendOpen = NO;
myStreamFlags.readOpen = NO;
myStreamFlags.wantsSSL = NO;
myStreamFlags.isNegotiatingSSL = NO;
myStreamFlags.sslOn = NO;
myStreamFlags.allowsBadCerts = NO;
myStreamFlags.initializedSSL = NO;
myStreamFlags.isDeleting = NO;
_recursiveS3RenamesQueue = [[NSMutableArray alloc] init];
_recursivelyRenamedDirectoriesToDelete = [[NSMutableArray alloc] init];
_recursiveS3RenameLock = [[NSLock alloc] init];
_recursiveDeletionsQueue = [[NSMutableArray alloc] init];
_emptyDirectoriesToDelete = [[NSMutableArray alloc] init];
_recursiveDeletionLock = [[NSLock alloc] init];
_recursiveDownloadQueue = [[NSMutableArray alloc] init];
_recursiveDownloadLock = [[NSLock alloc] init];
mySSLEncryptedSendBuffer = [[NSMutableData data] retain];
[NSThread prepareForConnectionInterThreadMessages];
}
return self;
}
- (void)dealloc
{
if (mySSLContext) SSLDisposeContext(mySSLContext);
if (mySSLIdentity) CFRelease(mySSLIdentity);
[mySSLSendBuffer release];
[mySSLRecevieBuffer release];
[mySSLRawReadBuffer release];
[mySSLEncryptedSendBuffer release];
// NSStream has a problem in that if you release and set the delegate to nil in the same runloop pass it will still send messages
// autoreleasing will stop the crashes.
[_sendStream setDelegate:nil];
[_receiveStream setDelegate:nil];
[_sendStream autorelease];
[_receiveStream autorelease];
[_sendBufferLock release];
[_sendBuffer release];
[_fileCheckingConnection setDelegate:nil];
[_fileCheckingConnection forceDisconnect];
[_fileCheckingConnection release];
[_fileCheckInFlight release];
[_recursiveS3RenameLock release];
[_recursiveS3RenamesQueue release];
[_recursivelyRenamedDirectoriesToDelete release];
[_recursiveDeletionsQueue release];
[_recursiveDeletionConnection setDelegate:nil];
[_recursiveDeletionConnection forceDisconnect];
[_recursiveDeletionConnection release];
[_emptyDirectoriesToDelete release];
[_recursiveDeletionLock release];
[_recursiveDownloadConnection setDelegate:nil];
[_recursiveDownloadConnection forceDisconnect];
[_recursiveDownloadConnection release];
[_recursiveDownloadQueue release];
[_recursiveDownloadLock release];
[super dealloc];
}
#pragma mark -
#pragma mark Accessors
- (void)setSendStream:(NSStream *)stream
{
if (stream != _sendStream) {
[_sendStream autorelease];
_sendStream = [stream retain];
}
}
- (void)setReceiveStream:(NSStream *)stream
{
if (stream != _receiveStream) {
[_receiveStream autorelease];
_receiveStream = [stream retain];
}
}
- (NSStream *)sendStream
{
return _sendStream;
}
- (NSStream *)receiveStream
{
return _receiveStream;
}
- (BOOL)sendStreamOpen
{
return myStreamFlags.sendOpen;
}
- (BOOL)receiveStreamOpen
{
return myStreamFlags.readOpen;
}
- (void)sendStreamDidOpen {}
- (void)sendStreamDidClose {}
- (void)receiveStreamDidOpen {}
- (void)receiveStreamDidClose {}
- (NSString *)remoteIPAddress
{
struct sockaddr sock;
socklen_t len = sizeof(sock);
if (getsockname([self socket], &sock, &len) >= 0) {
char *addr = inet_ntoa(((struct sockaddr_in *)&sock)->sin_addr);
return [NSString stringWithCString:addr];
}
return nil;
}
- (unsigned)localPort
{
struct sockaddr sock;
socklen_t len = sizeof(sock);
if (getsockname([self socket], &sock, &len) >= 0) {
return ntohs(((struct sockaddr_in *)&sock)->sin_port);
}
return 0;
}
- (CFSocketNativeHandle)socket
{
CFSocketNativeHandle native;
CFDataRef nativeProp = CFReadStreamCopyProperty ((CFReadStreamRef)_receiveStream, kCFStreamPropertySocketNativeHandle);
if (nativeProp == NULL)
{
return -1;
}
CFDataGetBytes (nativeProp, CFRangeMake(0, CFDataGetLength(nativeProp)), (UInt8 *)&native);
CFRelease (nativeProp);
return native;
}
#pragma mark -
#pragma mark Threading Support
- (void)runloopForwarder:(RunLoopForwarder *)rlw returnedValue:(void *)value
{
//by default we do nothing, subclasses are implementation specific based on their current state
}
- (void)scheduleStreamsOnRunLoop
{
[_receiveStream setDelegate:self];
[_sendStream setDelegate:self];
[_receiveStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_sendStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_receiveStream open];
[_sendStream open];
}
#pragma mark -
#pragma mark Queue Support
- (void)endBulkCommands
{
[super endBulkCommands];
[[[ConnectionThreadManager defaultManager] prepareWithInvocationTarget:self] checkQueue];
}
- (void)sendCommand:(id)command
{
// Subclasses handle this
}
#pragma mark -
#pragma mark AbstractConnection Overrides
- (void)setDelegate:(id)delegate
{
[super setDelegate:delegate];
// Also tell the forwarder to use this delegate.
[_forwarder setDelegate:delegate]; // note that its delegate it not retained.
}
- (BOOL)openStreamsToPort:(unsigned)port
{
NSHost *host = [CKCacheableHost hostWithName:_connectionHost];
if(!host){
KTLog(TransportDomain, KTLogError, @"Cannot find the host: %@", _connectionHost);
if (_flags.error) {
NSError *error = [NSError errorWithDomain:ConnectionErrorDomain
code:EHOSTUNREACH
userInfo:
[NSDictionary dictionaryWithObjectsAndKeys:LocalizedStringInConnectionKitBundle(@"Host Unavailable", @"Couldn't open the port to the host"), NSLocalizedDescriptionKey,
_connectionHost, @"host", nil]];
[_forwarder connection:self didReceiveError:error];
}
return NO;
}
/* If the host has multiple names it can screw up the order in the list of name */
if ([[host names] count] > 1) {
[host setValue:[NSArray arrayWithObject:_connectionHost] forKey:@"names"]; // KVC hack
}
if ([[host addresses] count] > 1) {
NSEnumerator *e = [[host addresses] objectEnumerator];
NSString *cur;
while (cur = [e nextObject])
{
if ([cur rangeOfString:@"."].location != NSNotFound)
{
[host setValue:[NSArray arrayWithObject:cur] forKey:@"addresses"];
}
}
}
[self closeStreams]; // make sure streams are closed before opening/allocating new ones
KTLog(TransportDomain, KTLogDebug, @"Opening streams to host: %@", host);
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
KTLog(TransportDomain, KTLogDebug, @"Socket: %d", port);
// Set TCP Keep Alive
int opt = 1;
if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &opt, sizeof(opt)))
{
NSLog(@"Failed to set socket keep alive setting");
}
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt)))
{
NSLog(@"Failed to set tcp no delay setting");
}
struct sockaddr_in addr;
bzero((char *) &addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr([[host address] cString]);
KTLog(TransportDomain, KTLogDebug, @"Connecting to %@:%d", [host address], port);
if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) == 0)
{
CFStreamCreatePairWithSocket(kCFAllocatorDefault,
sock,
(CFReadStreamRef *)(&_receiveStream),
(CFWriteStreamRef *)(&_sendStream)); // "Ownership follows the Create Rule."
// CFStreamCreatePairWithSocket does not close the socket by default
CFReadStreamSetProperty((CFReadStreamRef)_receiveStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty((CFWriteStreamRef)_sendStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
}
else
{
KTLog(TransportDomain, KTLogDebug, @"connect() failed");
}
if(!_receiveStream || !_sendStream){
KTLog(TransportDomain, KTLogError, @"Cannot create a stream to the host: %@", _connectionHost);
if (_flags.error) {
NSError *error = [NSError errorWithDomain:ConnectionErrorDomain
code:EHOSTUNREACH
userInfo:[NSDictionary dictionaryWithObject:LocalizedStringInConnectionKitBundle(@"Stream Unavailable", @"Error creating stream")
forKey:NSLocalizedDescriptionKey]];
[_forwarder connection:self didReceiveError:error];
}
return NO;
}
return YES;
}
- (void)threadedConnect
{
myStreamFlags.reportedError = NO;
[self scheduleStreamsOnRunLoop];
[super threadedConnect];
}
- (void)connect
{
_isForceDisconnecting = NO;
int connectionPort = [_connectionPort intValue];
if (0 == connectionPort)
{
connectionPort = 21; // standard FTP control port
}
if ([self openStreamsToPort:connectionPort])
{
// only call super if we have successfully opened the ports and put them on the runloop
[super connect];
}
}
/*! Disconnect from host. Called by foreground thread.
*/
- (void)disconnect
{
ConnectionCommand *con = [ConnectionCommand command:[NSInvocation invocationWithSelector:@selector(threadedDisconnect) target:self arguments:[NSArray array]]
awaitState:ConnectionIdleState
sentState:ConnectionSentDisconnectState
dependant:nil
userInfo:nil];
[self queueCommand:con];
[_fileCheckingConnection disconnect];
}
- (void)threadedDisconnect
{
[self setState:ConnectionNotConnectedState];
[self closeStreams];
[_fileCheckingConnection disconnect];
[_recursiveDeletionConnection disconnect];
[_recursiveDownloadConnection disconnect];
[super threadedDisconnect];
}
- (void)threadedForceDisconnect
{
[self setState:ConnectionNotConnectedState];
_isForceDisconnecting = YES;
[self closeStreams];
[super threadedForceDisconnect];
}
- (void)forceDisconnect
{
[self setState:ConnectionNotConnectedState];
[[[ConnectionThreadManager defaultManager] prepareWithInvocationTarget:self] threadedForceDisconnect];
[_fileCheckingConnection forceDisconnect];
[_recursiveDeletionConnection forceDisconnect];
[_recursiveDownloadConnection forceDisconnect];
}
- (void) cleanupConnection
{
[_fileCheckingConnection cleanupConnection];
[_recursiveDeletionConnection cleanupConnection];
[_recursiveDownloadConnection cleanupConnection];
}
- (BOOL)isBusy
{
return ([super isBusy] || [_recursiveDownloadConnection isBusy] || [_recursiveDeletionConnection isBusy] || [_fileCheckingConnection isBusy]);
}
#pragma mark -
#pragma mark Stream Delegate Methods
- (void)recalcUploadSpeedWithBytesSent:(unsigned)length
{
NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval diff = now - _lastChunkSent;
_uploadSpeed = length / diff;
_lastChunkSent = now;
}
- (void)recalcDownloadSpeedWithBytesSent:(unsigned)length
{
NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval diff = now - _lastChunkReceived;
_downloadSpeed = length / diff;
_lastChunkReceived = now;
}
- (void)closeStreams
{
[_receiveStream close];
[_sendStream close];
[_receiveStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_sendStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[_receiveStream setDelegate:nil];
[_sendStream setDelegate:nil];
[_receiveStream release];
[_sendStream release];
_receiveStream = nil;
_sendStream = nil;
[_sendBuffer setLength:0];
myStreamFlags.sendOpen = NO;
myStreamFlags.readOpen = NO;
}
- (void)processReceivedData:(NSData *)data
{
// we do nothing. subclass has to do the work.
}
- (NSData *)availableData
{
NSData *data = nil;
[self availableData:&data ofLength:kStreamChunkSize];
return data;
}
- (int)availableData:(NSData **)dataOut ofLength:(int)length
{
if ([_receiveStream streamStatus] != NSStreamStatusOpen)
{
*dataOut = nil;
return 0;
}
struct pollfd fds;
fds.fd = [self socket];
fds.events = POLLIN;
int hasBytes = poll(&fds, 1, 10);
if (hasBytes > 0)
//if ([_receiveStream hasBytesAvailable])
{
uint8_t *buf = (uint8_t *)malloc(sizeof(uint8_t) * length);
int len = [_receiveStream read:buf maxLength:length];
NSData *data = nil;
if (len >= 0)
{
data = [NSData dataWithBytesNoCopy:buf length:len freeWhenDone:YES];
}
*dataOut = data;
return len;
}
*dataOut = nil;
return 0;
}
- (BOOL)shouldChunkData
{
return YES;
}
- (NSMutableData *)outputDataBuffer
{
NSMutableData *dataBuffer = nil;
if (myStreamFlags.wantsSSL)
{
if (!myStreamFlags.sslOn && myStreamFlags.isNegotiatingSSL)
{
dataBuffer = mySSLEncryptedSendBuffer;
}
}
else
{
dataBuffer = _sendBuffer;
}
return dataBuffer;
}
- (void) sendQueuedOutput
{
NSMutableData *dataBuffer = [self outputDataBuffer];
[_sendBufferLock lock];
unsigned chunkLength = [dataBuffer length];
if ([self shouldChunkData])
{
chunkLength = MIN(kStreamChunkSize, [dataBuffer length]);
}
if (chunkLength > 0)
{
NSData *chunk = [dataBuffer subdataWithRange:NSMakeRange(0,chunkLength)];
KTLog(OutputStreamDomain, KTLogDebug, @"<< %@", [chunk shortDescription]);
uint8_t *bytes = (uint8_t *)[chunk bytes];
[(NSOutputStream *)_sendStream write:bytes maxLength:chunkLength];
[self recalcUploadSpeedWithBytesSent:chunkLength];
[self stream:_sendStream sentBytesOfLength:chunkLength];
[dataBuffer replaceBytesInRange:NSMakeRange(0,chunkLength)
withBytes:NULL
length:0];
_lastChunkSent = [NSDate timeIntervalSinceReferenceDate];
}
else
{
// KTLog(OutputStreamDomain, KTLogDebug, @"NOTHING NEEDED TO BE SENT RIGHT NOW");
}
[_sendBufferLock unlock];
}
- (unsigned)sendData:(NSData *)data // returns how many bytes it sent. If the buffer was not empty and it was appended, then it will return 0
{
if (myStreamFlags.wantsSSL)
{
if (!myStreamFlags.sslOn && !myStreamFlags.isNegotiatingSSL)
{
//put into the normal send buffer that is not encrypted.
[_sendBufferLock lock];
[_sendBuffer appendData:data];
[_sendBufferLock unlock];
return 0;
}
}
BOOL bufferWasEmpty = NO;
NSMutableData *dataBuffer = [self outputDataBuffer];
if (!dataBuffer)
{
KTLog(SSLDomain, KTLogFatal, @"No Data Buffer in sendData:");
return 0;
}
[_sendBufferLock lock];
bufferWasEmpty = [dataBuffer length] == 0;
[dataBuffer appendData:data];
[_sendBufferLock unlock];
unsigned chunkLength = 0;
if (bufferWasEmpty) {
// prime the sending
if (([_sendStream streamStatus] == NSStreamStatusOpen) && [_sendStream hasSpaceAvailable])
{
// KTLog(OutputStreamDomain, KTLogDebug, @"Buffer was empty, and there is space available, so sending this queued output");
// It's already ready for us, go ahead and send out some data
[self sendQueuedOutput];
}
else
{
// KTLog(OutputStreamDomain, KTLogDebug, @"Buffer was empty, but no space available, so we will WAIT for the event and not send now");
}
}
else
{
// KTLog(OutputStreamDomain, KTLogDebug, @"Buffer was NOT empty, so we have just appended it and we'll let it get sent out when it's ready");
}
// wait for the stream to open
// NSDate *start = [NSDate date];
// while (([_sendStream streamStatus] != NSStreamStatusOpen) || ![_sendStream hasSpaceAvailable])
// {
// if (abs([start timeIntervalSinceNow]) > kStreamTimeOutValue)
// {
// [self closeStreams];
// if (_flags.error)
// {
// NSError *error = [NSError errorWithDomain:StreamBasedErrorDomain
// code:StreamErrorTimedOut
// userInfo:[NSDictionary dictionaryWithObject:LocalizedStringInConnectionKitBundle(@"Timed Out waiting for remote host.", @"time out") forKey:NSLocalizedDescriptionKey]];
// [_forwarder connection:self didReceiveError:error];
// }
// return 0;
// }
// [NSThread sleepUntilDate:[NSDate distantPast]];
// }
return chunkLength;
}
- (void)handleReceiveStreamEvent:(NSStreamEvent)theEvent
{
switch (theEvent)
{
case NSStreamEventHasBytesAvailable:
{
uint8_t *buf = (uint8_t *)malloc(sizeof(uint8_t) * kStreamChunkSize);
int len = [_receiveStream read:buf maxLength:kStreamChunkSize];
if (len >= 0)
{
NSData *data = [NSData dataWithBytesNoCopy:buf length:len freeWhenDone:NO];
KTLog(InputStreamDomain, KTLogDebug, @"%d >> %@", len, [data shortDescription]);
[self stream:_receiveStream readBytesOfLength:len];
[self recalcDownloadSpeedWithBytesSent:len];
if (myStreamFlags.wantsSSL && myStreamFlags.isNegotiatingSSL)
{
[self negotiateSSLWithData:data];
}
else
{
[self processReceivedData:data];
}
}
free(buf);
break;
}
case NSStreamEventOpenCompleted:
{
myStreamFlags.readOpen = YES;
if (myStreamFlags.wantsSSL)
{
if (myStreamFlags.sendOpen)
{
myStreamFlags.isNegotiatingSSL = YES;
[self initializeSSL];
}
}
else
{
[self receiveStreamDidOpen];
}
KTLog(InputStreamDomain, KTLogDebug, @"Command receive stream opened");
break;
}
case NSStreamEventErrorOccurred:
{
KTLog(InputStreamDomain, KTLogError, @"receive stream error: %@", [_receiveStream streamError]);
NSError *error = nil;
if (GET_STATE == ConnectionNotConnectedState)
{
error = [NSError errorWithDomain:ConnectionErrorDomain
code:ConnectionStreamError
userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@ %@?", LocalizedStringInConnectionKitBundle(@"Is the service running on the server", @"Stream Error before opening"), [self host]]
forKey:NSLocalizedDescriptionKey]];
}
else
{
// we want to catch the connection reset by peer error
error = [_receiveStream streamError];
if ([[error domain] isEqualToString:NSPOSIXErrorDomain] && ([error code] == ECONNRESET || [error code] == EPIPE))
{
KTLog(TransportDomain, KTLogInfo, @"Connection was reset by peer/broken pipe, attempting to reconnect.", [_receiveStream streamError]);
error = nil;
// resetup connection again
[self closeStreams];
[self setState:ConnectionNotConnectedState];
// roll back to the first command in this chain of commands
NSArray *cmds = [[self lastCommand] sequencedChain];
NSEnumerator *e = [cmds reverseObjectEnumerator];
ConnectionCommand *cur;
while (cur = [e nextObject])
{
[self pushCommandOnCommandQueue:cur];
}
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(openStreamsToPort:)
target:self
arguments:[NSArray array]];
int port = [[self port] intValue];
[inv setArgument:&port atIndex:2];
[inv performSelector:@selector(invoke) inThread:_createdThread];
while (_sendStream == nil || _receiveStream == nil)
{
[NSThread sleepUntilDate:[NSDate distantPast]];
}
[self scheduleStreamsOnRunLoop];
break;
}
}
if (_flags.error && !myStreamFlags.reportedError)
{
myStreamFlags.reportedError = YES;
[_forwarder connection:self didReceiveError:error];
}
break;
}
case NSStreamEventEndEncountered:
{
myStreamFlags.readOpen = NO;
KTLog(InputStreamDomain, KTLogDebug, @"Command receive stream ended");
[self closeStreams];
[self setState:ConnectionNotConnectedState];
if (_flags.didDisconnect) {
[_forwarder connection:self didDisconnectFromHost:_connectionHost];
}
[self receiveStreamDidClose];
break;
}
case NSStreamEventNone:
{
break;
}
case NSStreamEventHasSpaceAvailable:
{
break;
}
}
}
- (void)handleSendStreamEvent:(NSStreamEvent)theEvent
{
switch (theEvent)
{
case NSStreamEventHasBytesAvailable:
{
// This can be called in here when send and receive stream are the same.
[self handleReceiveStreamEvent:theEvent];
break;
}
case NSStreamEventOpenCompleted:
{
myStreamFlags.sendOpen = YES;
if (myStreamFlags.wantsSSL)
{
if (myStreamFlags.readOpen)
{
myStreamFlags.isNegotiatingSSL = YES;
[self initializeSSL];
}
}
else
{
[self sendStreamDidOpen];
}
KTLog(OutputStreamDomain, KTLogDebug, @"Command send stream opened");
break;
}
case NSStreamEventErrorOccurred:
{
KTLog(OutputStreamDomain, KTLogError, @"send stream error: %@", [_receiveStream streamError]);
NSError *error = nil;
if (GET_STATE == ConnectionNotConnectedState)
{
error = [NSError errorWithDomain:ConnectionErrorDomain
code:ConnectionStreamError
userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@ %@?", LocalizedStringInConnectionKitBundle(@"Is the service running on the server", @"Stream Error before opening"), [self host]]
forKey:NSLocalizedDescriptionKey]];
}
else
{
// we want to catch the connection reset by peer error
error = [_sendStream streamError];
if ([[error domain] isEqualToString:NSPOSIXErrorDomain] && ([error code] == ECONNRESET || [error code] == EPIPE))
{
KTLog(TransportDomain, KTLogInfo, @"Connection was reset by peer/broken pipe, attempting to reconnect.", [_sendStream streamError]);
error = nil;
// resetup connection again
[self closeStreams];
[self setState:ConnectionNotConnectedState];
// roll back to the first command in this chain of commands
NSArray *cmds = [[self lastCommand] sequencedChain];
NSEnumerator *e = [cmds reverseObjectEnumerator];
ConnectionCommand *cur;
while (cur = [e nextObject])
{
[self pushCommandOnCommandQueue:cur];
}
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(openStreamsToPort:)
target:self
arguments:[NSArray array]];
int port = [[self port] intValue];
[inv setArgument:&port atIndex:2];
[inv performSelector:@selector(invoke) inThread:_createdThread];
while (_sendStream == nil || _receiveStream == nil)
{
[NSThread sleepUntilDate:[NSDate distantPast]];
}
[self scheduleStreamsOnRunLoop];
break;
}
}
if (_flags.error && !myStreamFlags.reportedError)
{
myStreamFlags.reportedError = YES;
[_forwarder connection:self didReceiveError:error];
}
break;
}
case NSStreamEventEndEncountered:
{
myStreamFlags.sendOpen = NO;
KTLog(OutputStreamDomain, KTLogDebug, @"Command send stream ended");
[self closeStreams];
[self setState:ConnectionNotConnectedState];
if (_flags.didDisconnect) {
[_forwarder connection:self didDisconnectFromHost:_connectionHost];
}
[self sendStreamDidClose];
break;
}
case NSStreamEventNone:
{
break;
}
case NSStreamEventHasSpaceAvailable:
{
// KTLog(OutputStreamDomain, KTLogDebug, @"Space available, sending any queued output");
[self sendQueuedOutput];
break;
}
default:
{
KTLog(OutputStreamDomain, KTLogError, @"Composite Event Code! Need to deal with this!");
break;
}
}
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)theEvent
{
if (stream == (NSStream *)_sendStream) {
[self handleSendStreamEvent:theEvent];
} else if (stream == (NSStream *)_receiveStream) {
[self handleReceiveStreamEvent:theEvent];
} else {
KTLog(TransportDomain, KTLogError, @"StreamBasedConnection: unknown stream (%@)", stream);
}
}
- (void)stream:(id<OutputStream>)stream sentBytesOfLength:(unsigned)length
{
// we do nothing - just allow subclasses to know that something was sent
}
- (void)stream:(id<InputStream>)stream readBytesOfLength:(unsigned)length
{
// we do nothing - just allow subclasses to know that something was read
}
#pragma mark -
#pragma mark File Checking
- (void)processFileCheckingQueue
{
if (!_fileCheckingConnection)
{
_fileCheckingConnection = [[[self class] alloc] initWithHost:[self host]
port:[self port]
username:[self username]
password:[self password]
error:nil];
[_fileCheckingConnection setDelegate:self];
[_fileCheckingConnection setTranscript:[self propertyForKey:@"FileCheckingTranscript"]];
[_fileCheckingConnection connect];
}
[_fileCheckLock lock];
if (!_fileCheckInFlight && [self numberOfFileChecks] > 0)
{
_fileCheckInFlight = [[self currentFileCheck] copy];
NSString *dir = [_fileCheckInFlight stringByDeletingLastPathComponent];
if (!dir)
NSLog(@"%@: %@", NSStringFromSelector(_cmd), _fileCheckInFlight);
[_fileCheckingConnection changeToDirectory:dir];
[_fileCheckingConnection directoryContents];
}
[_fileCheckLock unlock];
}
- (void)checkExistenceOfPath:(NSString *)path
{
NSString *dir = [path stringByDeletingLastPathComponent];
//if we pass in a relative path (such as xxx.tif), then the last path is @"", with a length of 0, so we need to add the current directory
//according to docs, passing "/" to stringByDeletingLastPathComponent will return "/", conserving a 1 size
//
if (!dir || [dir length] == 0)
{
path = [[self currentDirectory] stringByAppendingPathComponent:path];
}
[_fileCheckLock lock];
[self queueFileCheck:path];
[_fileCheckLock unlock];
[[[ConnectionThreadManager defaultManager] prepareWithInvocationTarget:self] processFileCheckingQueue];
}
#pragma mark -
#pragma mark Recursive S3 Directory Rename Support Methods
- (void)processRecursiveS3RenamingQueue
{
if (!_recursiveS3RenameConnection)
{
_recursiveS3RenameConnection = [self copy];
[_recursiveS3RenameConnection setName:@"Recursive S3 Renaming"];
[_recursiveS3RenameConnection setDelegate:self];
[_recursiveS3RenameConnection setTranscript:[self propertyForKey:@"RecursiveS3RenamingTranscript"]];
[_recursiveS3RenameConnection connect];
}
[_recursiveS3RenameLock lock];
if (!myStreamFlags.isRecursivelyRenamingForS3 && [_recursiveS3RenamesQueue count] > 0)
{
myStreamFlags.isRecursivelyRenamingForS3 = YES;
NSDictionary *renameDictionary = [_recursiveS3RenamesQueue objectAtIndex:0];
NSString *fromDirectoryPath = [renameDictionary objectForKey:@"FromDirectoryPath"];