/
DTBonjourDataConnection.m
465 lines (369 loc) · 11.7 KB
/
DTBonjourDataConnection.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
//
// DTBonjourDataConnection.m
// DTBonjour
//
// Created by Oliver Drobnik on 01.11.12.
// Copyright (c) 2012 Oliver Drobnik. All rights reserved.
//
#import "DTBonjourDataConnection.h"
#import "DTBonjourDataChunk.h"
#import "NSScanner+DTBonjour.h"
#import <Foundation/NSJSONSerialization.h>
#define kDTBonjourQNetworkAdditionsCheckSEL NSSelectorFromString(@"netService:didAcceptConnectionWithInputStream:outputStream:")
CGFloat DTBonjourDataConnectionDefaultTimeout = 60.0;
NSString * DTBonjourDataConnectionErrorDomain = @"DTBonjourDataConnection";
@interface NSNetService (QNetworkAdditions)
- (BOOL)qNetworkAdditions_getInputStream:(out NSInputStream **)inputStreamPtr
outputStream:(out NSOutputStream **)outputStreamPtr;
@end
@implementation NSNetService (QNetworkAdditions)
- (BOOL)qNetworkAdditions_getInputStream:(out NSInputStream **)inputStreamPtr
outputStream:(out NSOutputStream **)outputStreamPtr
// The following works around three problems with
// -[NSNetService getInputStream:outputStream:]:
//
// o <rdar://problem/6868813> -- Currently the returns the streams with
// +1 retain count, which is counter to Cocoa conventions and results in
// leaks when you use it in ARC code.
//
// o <rdar://problem/9821932> -- If you create two pairs of streams from
// one NSNetService and then attempt to open all the streams simultaneously,
// some of the streams might fail to open.
//
// o <rdar://problem/9856751> -- If you create streams using
// -[NSNetService getInputStream:outputStream:], start to open them, and
// then release the last reference to the original NSNetService, the
// streams never finish opening. This problem is exacerbated under ARC
// because ARC is better about keeping things out of the autorelease pool.
{
BOOL result;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
result = NO;
readStream = NULL;
writeStream = NULL;
if ( (inputStreamPtr != NULL) || (outputStreamPtr != NULL) ) {
CFNetServiceRef netService;
netService = CFNetServiceCreate(
NULL,
(__bridge CFStringRef) [self domain],
(__bridge CFStringRef) [self type],
(__bridge CFStringRef) [self name],
0
);
if (netService != NULL) {
CFStreamCreatePairWithSocketToNetService(
NULL,
netService,
((inputStreamPtr != nil) ? &readStream : NULL),
((outputStreamPtr != nil) ? &writeStream : NULL)
);
CFRelease(netService);
}
// We have failed if the client requested an input stream and didn't
// get one, or requested an output stream and didn't get one. We also
// fail if the client requested neither the input nor the output
// stream, but we don't get here in that case.
result = ! ((( inputStreamPtr != NULL) && ( readStream == NULL)) ||
((outputStreamPtr != NULL) && (writeStream == NULL)));
}
if (inputStreamPtr != NULL) {
*inputStreamPtr = CFBridgingRelease(readStream);
}
if (outputStreamPtr != NULL) {
*outputStreamPtr = CFBridgingRelease(writeStream);
}
return result;
}
@end
@interface DTBonjourDataConnection () <NSStreamDelegate>
@end
@interface DTBonjourDataChunk (private)
// make read-only property assignable
@property (nonatomic, assign) NSUInteger sequenceNumber;
@end
typedef enum
{
DTBonjourDataConnectionExpectedDataTypeNothing,
DTBonjourDataConnectionExpectedDataTypeHeader,
DTBonjourDataConnectionExpectedDataTypeData
} DTBonjourDataConnectionExpectedDataType;
@implementation DTBonjourDataConnection
{
NSInputStream *_inputStream;
NSOutputStream *_outputStream;
NSMutableArray *_outputQueue;
DTBonjourDataChunk *_receivingChunk;
NSUInteger _chunkSequenceNumber;
__weak id <DTBonjourDataConnectionDelegate> _delegate;
}
- (id)initWithNativeSocketHandle:(CFSocketNativeHandle)nativeSocketHandle
{
self = [super init];
if (self)
{
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream);
if (readStream && writeStream)
{
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
_inputStream = (__bridge_transfer NSInputStream *)readStream;
_outputStream = (__bridge_transfer NSOutputStream *)writeStream;
_outputQueue = [[NSMutableArray alloc] init];
}
else
{
close(nativeSocketHandle);
return nil;
}
}
return self;
}
- (id)initWithService:(NSNetService *)service
{
self = [super init];
if (self)
{
NSInputStream *in;
NSOutputStream *out;
if (![[service delegate] respondsToSelector:kDTBonjourQNetworkAdditionsCheckSEL])
{
// Older iOS/OSX versions need a patch for getting input and output
// streams see the `QNetworkAdditions` above. (If the delegate does not
// implement the `kDTBonjourQNetworkAdditionsCheck` selector, we can
// simply use the patched version.
if ([service qNetworkAdditions_getInputStream:&in outputStream:&out])
return nil;
}
else
{
// iOS7/OSX10.9
if (![service getInputStream:&in outputStream:&out])
return nil;
}
_inputStream = in;
_outputStream = out;
_outputQueue = [[NSMutableArray alloc] init];
}
return self;
}
- (id)initWithInputStream:(NSInputStream *)inStream outputStream:(NSOutputStream *)outStream
{
self = [super init];
if (self)
{
_inputStream = inStream;
_outputStream = outStream;
_outputQueue = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc
{
_delegate = nil;
[self close];
}
- (BOOL)openWithTimeout:(CGFloat)timeout
{
[_inputStream setDelegate:self];
[_outputStream setDelegate:self];
[_inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_inputStream open];
[_outputStream open];
__weak id weakSelf = self;
double delayInSeconds = timeout;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// No connection after timeout, closing.
if (![weakSelf isOpen]) {
[weakSelf close];
}
});
return YES;
}
- (BOOL)open
{
return [self openWithTimeout:DTBonjourDataConnectionDefaultTimeout];
}
- (void)close
{
if (!_inputStream&&!_outputStream)
{
return;
}
[_inputStream setDelegate:nil];
[_outputStream setDelegate:nil];
[_inputStream close];
[_outputStream close];
[_inputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[_outputStream removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
_inputStream = nil;
_outputStream = nil;
if ([_delegate respondsToSelector:@selector(connectionDidClose:)])
[_delegate connectionDidClose:self];
}
- (BOOL)isOpen
{
if (!_inputStream)
return NO;
NSStreamStatus inputStatus = [_inputStream streamStatus];
NSStreamStatus outputStatus = [_outputStream streamStatus];
if (NSStreamStatusOpen != inputStatus)
return NO;
if (NSStreamStatusOpen != outputStatus)
return NO;
return YES;
}
- (void)_startOutput
{
if (![_outputQueue count])
{
return;
}
DTBonjourDataChunk *chunk = _outputQueue[0];
if (0 == chunk.numberOfTransferredBytes)
{
// nothing sent yet
if ([_delegate respondsToSelector:@selector(connection:willStartSendingChunk:)])
{
[_delegate connection:self willStartSendingChunk:chunk];
}
}
NSInteger writtenBytes = [chunk writeToOutputStream:_outputStream];
if (writtenBytes > 0)
{
if ([_delegate respondsToSelector:@selector(connection:didSendBytes:ofChunk:)])
{
[_delegate connection:self didSendBytes:writtenBytes ofChunk:chunk];
}
// If we didn't write all the bytes we'll continue writing them in response to the next
// has-space-available event.
if ([chunk isTransmissionComplete])
{
[_outputQueue removeObject:chunk];
if ([_delegate respondsToSelector:@selector(connection:didFinishSendingChunk:)])
{
[_delegate connection:self didFinishSendingChunk:chunk];
}
}
}
else
{
// A non-positive result from -write:maxLength: indicates a failure of some form; in this
// simple app we respond by simply closing down our connection.
[self close];
}
}
#pragma mark - Public Interface
- (BOOL)sendObject:(id)object error:(NSError **)error
{
if (![self isOpen])
{
if (error)
{
NSDictionary *userInfo = @{NSLocalizedDescriptionKey:@"Connection is not open"};
*error = [NSError errorWithDomain:@"DTBonjourDataConnection" code:1 userInfo:userInfo];
}
return NO;
}
DTBonjourDataChunk *newChunk = [[DTBonjourDataChunk alloc]
initWithObject:object
encoding:self.sendingContentType
error:error];
if (!newChunk)
return NO;
newChunk.sequenceNumber = _chunkSequenceNumber;
BOOL queueWasEmpty = (![_outputQueue count]);
[_outputQueue addObject:newChunk];
if (queueWasEmpty && _outputStream.streamStatus == NSStreamStatusOpen)
{
dispatch_async(dispatch_get_main_queue(), ^{
[self _startOutput];
});
}
return YES;
}
#pragma mark - NSStream Delegate
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent
{
switch(streamEvent)
{
case NSStreamEventOpenCompleted:
{
if ([_delegate respondsToSelector:@selector(connectionDidOpen:)]) {
if ([self isOpen] && aStream == _outputStream) {
[_delegate connectionDidOpen:self];
}
}
break;
}
case NSStreamEventHasBytesAvailable:
{
if (!_receivingChunk)
{
// start reading a new chunk
_receivingChunk = [[DTBonjourDataChunk alloc] initForReading];
// nothing received yet
if ([_delegate respondsToSelector:@selector(connection:willStartReceivingChunk:)])
{
[_delegate connection:self willStartReceivingChunk:_receivingChunk];
}
}
// continue reading
NSInteger actuallyRead = [_receivingChunk readFromInputStream:_inputStream];
if (actuallyRead<0)
{
[self close];
break;
}
if ([_delegate respondsToSelector:@selector(connection:didReceiveBytes:ofChunk:)])
{
[_delegate connection:self didReceiveBytes:actuallyRead ofChunk:_receivingChunk];
}
if ([_receivingChunk isTransmissionComplete])
{
if ([_delegate respondsToSelector:@selector(connection:didFinishReceivingChunk:)])
{
[_delegate connection:self didFinishReceivingChunk:_receivingChunk];
}
if ([_delegate respondsToSelector:@selector(connection:didReceiveObject:)])
{
id decodedObject = [_receivingChunk decodedObject];
[_delegate connection:self didReceiveObject:decodedObject];
}
// we're done with this chunk
_receivingChunk = nil;
}
break;
}
case NSStreamEventErrorOccurred:
{
NSLog(@"Error occurred: %@", [aStream.streamError localizedDescription]);
// Intentional fall-through.
}
case NSStreamEventEndEncountered:
{
[self close];
break;
}
case NSStreamEventHasSpaceAvailable:
{
if ([_outputQueue count])
{
[self _startOutput];
}
break;
}
default:
{
// do nothing
break;
}
}
}
#pragma mark - Properties
@synthesize delegate = _delegate;
@end