/
CBLSyncListener.m
257 lines (208 loc) · 7.74 KB
/
CBLSyncListener.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
//
// CBLSyncListener.m
// Couchbase Lite
//
// Created by Jens Alfke on 4/3/15.
// Copyright (c) 2015 Couchbase. All rights reserved.
//
#import "CBLSyncListener.h"
#import "CBLListener+Internal.h"
#import "CBLSyncConnection.h"
#import "BLIPRequest.h"
#import "CouchbaseLite.h"
#import "CBLInternal.h"
#import "BLIPPocketSocketListener.h"
#import "PSWebSocket.h"
#import "CollectionUtils.h"
#import "Logging.h"
@interface CBLSyncListener ()
@property (readwrite) UInt16 port;
@property (readwrite) NSUInteger connectionCount;
@property (readwrite, copy) NSString* bonjourName;
@end
@interface CBLSyncListenerImpl : BLIPPocketSocketListener <NSNetServiceDelegate>
@end
@implementation CBLSyncListenerImpl
{
CBLManager* _manager;
__weak CBLSyncListener* _facade;
NSMutableSet* _handlers;
dispatch_queue_t _queue;
NSString* _bonjourName, *_bonjourType;
NSNetService* _netService;
NSData* _txtData;
}
- (instancetype) initWithManager: (CBLManager*)manager
facade: (CBLSyncListener*)facade
{
NSArray* paths = [manager.allDatabaseNames my_map:^id(NSString* name) {
return $sprintf(@"/%@/_blipsync", name);
}];
self = [super initWithPaths: paths delegate: nil queue: nil];
if (self) {
_manager = manager;
_facade = facade;
_handlers = [NSMutableSet new];
_queue = dispatch_queue_create("CBLSyncListener", DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (void)dealloc {
LogTo(CBLListener, @"DEALLOC %@", self);
dispatch_sync(_queue, ^{
for (CBLSyncConnection* handler in _handlers)
[handler removeObserver: self forKeyPath: @"state"];
});
}
- (BOOL) checkClientCertificateAuthentication: (SecTrustRef)trust
fromAddress: (NSData*)address
{
id<CBLListenerDelegate> delegate = _facade.delegate;
if ([delegate respondsToSelector: @selector(authenticateConnectionFromAddress:withTrust:)]) {
return [delegate authenticateConnectionFromAddress: address withTrust: trust] != nil;
}
return YES;
}
- (void) blipConnectionDidOpen:(BLIPConnection *)connection {
NSString* name = ((BLIPPocketSocketConnection*)connection).webSocket.URLRequest.URL.path;
name = name.stringByDeletingLastPathComponent.lastPathComponent;
LogTo(CBLListener, @"OPENED INCOMING %@ from <%@> for %@", connection, connection.URL, name);
[_manager.backgroundServer waitForDatabaseNamed: name to: ^id(CBLDatabase* db) {
NSString* name = $sprintf(@"Sync from %@", connection.URL);
dispatch_queue_t queue = dispatch_queue_create(name.UTF8String, DISPATCH_QUEUE_SERIAL);
CBLSyncConnection* handler = [[CBLSyncConnection alloc] initWithDatabase: db
connection: connection
queue: queue];
if (_facade.readOnly) {
handler.onSyncAccessCheck = ^CBLStatus(BLIPRequest* request, NSString* docID) {
NSString* profile = request.profile;
if ([profile isEqualToString:@"setCheckpoint"] ||
[profile isEqualToString:@"changes"] ||
[profile isEqualToString:@"rev"])
return kCBLStatusForbidden;
return kCBLStatusOK;
};
}
[handler addObserver: self forKeyPath: @"state" options: 0 context: (void*)1];
dispatch_sync(_queue, ^{
[_handlers addObject: handler];
_facade.connectionCount = _handlers.count;
});
return nil;
}];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if (context == (void*)1) {
CBLSyncConnection* handler = object;
if (handler.state == kSyncStopped) {
LogTo(CBLListener, @"CLOSED INCOMING connection from <%@>", handler.peerURL);
dispatch_sync(_queue, ^{
[_handlers removeObject: handler];
[handler removeObserver: self forKeyPath: @"state"];
_facade.connectionCount = _handlers.count;
});
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark - BONJOUR:
- (void) setBonjourName: (NSString*)name type: (NSString*)type {
dispatch_async(_queue, ^{
_bonjourName = name;
_bonjourType = type;
});
}
- (NSDictionary*) TXTRecordDictionary {
return _txtData ? [NSNetService dictionaryFromTXTRecordData: _txtData] : nil;
}
- (void)setTXTRecordDictionary:(NSDictionary *)dict {
NSData* txtData = dict ? [NSNetService dataFromTXTRecordDictionary: dict] : nil;
dispatch_async(_queue, ^{
_txtData = txtData;
NSNetService* ns = _netService;
if (ns) {
dispatch_async(dispatch_get_main_queue(), ^{
ns.TXTRecordData = txtData;
});
}
});
}
- (void) listenerDidStart {
_facade.port = self.port;
if (_bonjourType) {
dispatch_async(_queue, ^{
NSNetService* ns = [[NSNetService alloc] initWithDomain: @""
type: _bonjourType
name: _bonjourName
port: self.port];
if ([ns respondsToSelector: @selector(setIncludesPeerToPeer:)]) // 10.10+
ns.includesPeerToPeer = YES;
ns.delegate = self;
ns.TXTRecordData = _txtData;
_netService = ns;
dispatch_async(dispatch_get_main_queue(), ^{
[ns publishWithOptions: 0];
});
});
}
}
- (void) listenerDidStop {
dispatch_async(_queue, ^{
CBLSyncListener* facade = _facade;
facade.port = 0;
NSNetService* ns = _netService;
if (ns) {
_netService = nil;
facade.bonjourName = nil;
dispatch_async(dispatch_get_main_queue(), ^{
ns.delegate = nil;
[ns stop];
});
}
});
}
// called on main thread
- (void)netServiceDidPublish:(NSNetService *)ns {
NSString* name = ns.name;
LogTo(CBLListener, @"CBLSyncListener: Published Bonjour service '%@'", name);
_facade.bonjourName = name;
}
// called on main thread
- (void)netService:(NSNetService *)ns didNotPublish:(NSDictionary *)errorDict {
Warn(@"CBLSyncListener: Failed to publish Bonjour service '%@': %@", ns.name, errorDict);
}
@end
@implementation CBLSyncListener
{
CBLSyncListenerImpl* _impl;
uint16_t _desiredPort;
}
@synthesize port=_port, connectionCount=_connectionCount;
@synthesize bonjourName=_bonjourName;
- (instancetype) initWithManager: (CBLManager*)manager port: (uint16_t)port {
self = [super initWithManager: manager port: port];
if (self) {
_impl = [[CBLSyncListenerImpl alloc] initWithManager: manager facade: self];
_desiredPort = port;
}
return self;
}
- (void) setBonjourName: (NSString*)name type: (NSString*)type {
[_impl setBonjourName: name type: type];
}
- (NSDictionary*) TXTRecordDictionary {return _impl.TXTRecordDictionary;}
- (void)setTXTRecordDictionary:(NSDictionary *)dict {_impl.TXTRecordDictionary = dict;}
- (void) setPasswords:(NSDictionary *)passwords {_impl.passwords = passwords;}
- (BOOL) start: (NSError**)outError {
return [_impl acceptOnInterface: nil
port: _desiredPort
SSLCertificates: self.SSLIdentityAndCertificates
error: outError];
}
- (void) stop {
[_impl disconnect];
}
@end