-
Notifications
You must be signed in to change notification settings - Fork 82
/
MTDNS.m
372 lines (326 loc) · 13 KB
/
MTDNS.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
#import "MTDNS.h"
#import <arpa/inet.h>
#include <netinet/tcp.h>
#import <fcntl.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <netinet/in.h>
#import <net/if.h>
#if defined(MtProtoKitDynamicFramework)
# import <MTProtoKitDynamic/MTQueue.h>
# import <MTProtoKitDynamic/MTSignal.h>
# import <MTProtoKitDynamic/MTBag.h>
# import <MTProtoKitDynamic/MTAtomic.h>
# import <MTProtoKitDynamic/MTHttpRequestOperation.h>
# import <MTProtoKitDynamic/MTEncryption.h>
# import <MTProtoKitDynamic/MTRequestMessageService.h>
# import <MTProtoKitDynamic/MTRequest.h>
# import <MTProtoKitDynamic/MTContext.h>
# import <MTProtoKitDynamic/MTApiEnvironment.h>
# import <MTProtoKitDynamic/MTDatacenterAddress.h>
# import <MTProtoKitDynamic/MTDatacenterAddressSet.h>
# import <MTProtoKitDynamic/MTProto.h>
# import <MTProtoKitDynamic/MTSerialization.h>
# import <MTProtoKitDynamic/MTLogging.h>
#elif defined(MtProtoKitMacFramework)
# import <MTProtoKitMac/MTQueue.h>
# import <MTProtoKitMac/MTSignal.h>
# import <MTProtoKitMac/MTBag.h>
# import <MTProtoKitMac/MTAtomic.h>
# import <MTProtoKitMac/MTHttpRequestOperation.h>
# import <MTProtoKitMac/MTEncryption.h>
# import <MTProtoKitMac/MTRequestMessageService.h>
# import <MTProtoKitMac/MTRequest.h>
# import <MTProtoKitMac/MTContext.h>
# import <MTProtoKitMac/MTApiEnvironment.h>
# import <MTProtoKitMac/MTDatacenterAddress.h>
# import <MTProtoKitMac/MTDatacenterAddressSet.h>
# import <MTProtoKitMac/MTProto.h>
# import <MTProtoKitMac/MTSerialization.h>
# import <MTProtoKitMac/MTLogging.h>
#else
# import <MTProtoKit/MTQueue.h>
# import <MTProtoKit/MTSignal.h>
# import <MTProtoKit/MTBag.h>
# import <MTProtoKit/MTAtomic.h>
# import <MTProtoKit/MTHttpRequestOperation.h>
# import <MTProtoKit/MTEncryption.h>
# import <MTProtoKit/MTRequestMessageService.h>
# import <MTProtoKit/MTRequest.h>
# import <MTProtoKit/MTContext.h>
# import <MTProtoKit/MTApiEnvironment.h>
# import <MTProtoKit/MTDatacenterAddress.h>
# import <MTProtoKit/MTDatacenterAddressSet.h>
# import <MTProtoKit/MTProto.h>
# import <MTProtoKit/MTSerialization.h>
# import <MTProtoKit/MTLogging.h>
#endif
#import <netinet/in.h>
#import <arpa/inet.h>
@interface MTDNSHostContext : NSObject {
MTBag *_subscribers;
id<MTDisposable> _disposable;
}
@end
@implementation MTDNSHostContext
- (instancetype)initWithHost:(NSString *)host disposable:(id<MTDisposable>)disposable {
self = [super init];
if (self != nil) {
_subscribers = [[MTBag alloc] init];
_disposable = disposable;
}
return self;
}
- (void)dealloc {
[_disposable dispose];
}
- (NSInteger)addSubscriber:(void (^)(NSString *))completion {
return [_subscribers addItem:[completion copy]];
}
- (void)removeSubscriber:(NSInteger)index {
[_subscribers removeItem:index];
}
- (bool)isEmpty {
return [_subscribers isEmpty];
}
- (void)complete:(NSString *)result {
for (void (^completion)(NSString *) in [_subscribers copyItems]) {
completion(result);
}
}
@end
@interface MTDNSContext : NSObject {
NSMutableDictionary<NSString *, MTDNSHostContext *> *_contexts;
}
@end
@implementation MTDNSContext
+ (MTQueue *)sharedQueue {
static MTQueue *queue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
queue = [[MTQueue alloc] init];
});
return queue;
}
+ (MTSignal *)shared {
return [[[MTSignal alloc] initWithGenerator:^id<MTDisposable>(MTSubscriber *subscriber) {
static MTDNSContext *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[MTDNSContext alloc] init];
});
[subscriber putNext:instance];
[subscriber putCompletion];
return nil;
}] startOn:[self sharedQueue]];
}
- (instancetype)init {
self = [super init];
if (self != nil) {
_contexts = [[NSMutableDictionary alloc] init];
}
return self;
}
- (id<MTDisposable>)subscribe:(NSString *)host port:(int32_t)port completion:(void (^)(NSString *))completion {
NSString *key = [NSString stringWithFormat:@"%@:%d", host, port];
MTMetaDisposable *disposable = nil;
if (_contexts[key] == nil) {
disposable = [[MTMetaDisposable alloc] init];
_contexts[key] = [[MTDNSHostContext alloc] initWithHost:host disposable:disposable];
}
MTDNSHostContext *context = _contexts[key];
NSInteger index = [context addSubscriber:^(NSString *result) {
if (completion) {
completion(result);
}
}];
if (disposable != nil) {
__weak MTDNSContext *weakSelf = self;
[disposable setDisposable:[[[self performLookup:host port:port] deliverOn:[MTDNSContext sharedQueue]] startWithNext:^(NSString *result) {
__strong MTDNSContext *strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
if (strongSelf->_contexts[key] != nil) {
[strongSelf->_contexts[key] complete:result];
[strongSelf->_contexts removeObjectForKey:key];
}
}]];
}
__weak MTDNSContext *weakSelf = self;
__weak MTDNSHostContext *weakContext = context;
return [[MTBlockDisposable alloc] initWithBlock:^{
[[MTDNSContext sharedQueue] dispatchOnQueue:^{
__strong MTDNSContext *strongSelf = weakSelf;
__strong MTDNSHostContext *strongContext = weakContext;
if (strongSelf == nil || strongContext == nil) {
return;
}
if (strongSelf->_contexts[key] != nil && strongSelf->_contexts[key] == strongContext) {
[strongSelf->_contexts[key] removeSubscriber:index];
if ([strongSelf->_contexts[key] isEmpty]) {
[strongSelf->_contexts removeObjectForKey:key];
}
}
}];
}];
}
- (MTSignal *)performLookup:(NSString *)host port:(int32_t)port {
MTSignal *lookupOnce = [[MTSignal alloc] initWithGenerator:^id<MTDisposable>(MTSubscriber *subscriber) {
MTMetaDisposable *disposable = [[MTMetaDisposable alloc] init];
[[MTQueue concurrentDefaultQueue] dispatchOnQueue:^{
struct addrinfo hints, *res, *res0;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
NSString *portStr = [NSString stringWithFormat:@"%d", port];
if (MTLogEnabled()) {
MTLog(@"[MTDNS lookup %@:%@]", host, portStr);
}
int gai_error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
NSString *address4 = nil;
NSString *address6 = nil;
if (gai_error == 0) {
for(res = res0; res; res = res->ai_next) {
if ((address4 == nil) && (res->ai_family == AF_INET)) {
struct sockaddr_in *addr_in = (struct sockaddr_in *)res->ai_addr;
char *s = malloc(INET_ADDRSTRLEN);
inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
address4 = [NSString stringWithUTF8String:s];
free(s);
} else if ((address6 == nil) && (res->ai_family == AF_INET6)) {
struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)res->ai_addr;
char *s = malloc(INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
address6 = [NSString stringWithUTF8String:s];
free(s);
}
}
freeaddrinfo(res0);
}
if (address4 != nil) {
if (MTLogEnabled()) {
MTLog(@"[MTDNS lookup %@:%@ success ipv4]", host, portStr);
}
[subscriber putNext:address4];
[subscriber putCompletion];
} else if (address6 != nil) {
if (MTLogEnabled()) {
MTLog(@"[MTDNS lookup %@:%@ success ipv6]", host, portStr);
}
[subscriber putNext:address6];
[subscriber putCompletion];
} else {
if (MTLogEnabled()) {
MTLog(@"[MTDNS lookup %@:%@ error %d]", host, portStr, gai_error);
}
[subscriber putError:nil];
}
}];
return disposable;
}];
return [[[lookupOnce catch:^MTSignal *(__unused id error) {
return [[MTSignal complete] delay:2.0 onQueue:[MTDNSContext sharedQueue]];
}] restart] take:1];
}
@end
@interface MTDNSCachedHostname : NSObject
@property (nonatomic, strong) NSString *ip;
@property (nonatomic) NSTimeInterval timestamp;
@end
@implementation MTDNSCachedHostname
- (instancetype)initWithIp:(NSString *)ip timestamp:(NSTimeInterval)timestamp {
self = [super init];
if (self != nil) {
_ip = ip;
_timestamp = timestamp;
}
return self;
}
@end
@implementation MTDNS
+ (MTAtomic *)hostnameCache {
static MTAtomic *result = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
result = [[MTAtomic alloc] initWithValue:[[NSMutableDictionary alloc] init]];
});
return result;
}
+ (NSString *)cachedIp:(NSString *)hostname {
return [[self hostnameCache] with:^id (NSMutableDictionary *dict) {
MTDNSCachedHostname *result = dict[hostname];
if (result != nil && result.timestamp > CFAbsoluteTimeGetCurrent() - 10.0 * 60.0) {
return result.ip;
}
return nil;
}];
}
+ (void)cacheIp:(NSString *)hostname ip:(NSString *)ip {
[[self hostnameCache] with:^id (NSMutableDictionary *dict) {
dict[hostname] = [[MTDNSCachedHostname alloc] initWithIp:ip timestamp:CFAbsoluteTimeGetCurrent()];
return nil;
}];
}
+ (MTSignal *)resolveHostname:(NSString *)hostname {
return [[MTSignal alloc] initWithGenerator:^id<MTDisposable>(MTSubscriber *subscriber) {
NSString *cached = [self cachedIp:hostname];
if (cached != nil) {
[subscriber putNext:cached];
[subscriber putCompletion];
return nil;
}
NSDictionary *headers = @{@"Host": @"dns.google.com"};
return [[[MTHttpRequestOperation dataForHttpUrl:[NSURL URLWithString:[NSString stringWithFormat:@"https://google.com/resolve?name=%@", hostname]] headers:headers] mapToSignal:^MTSignal *(NSData *data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if ([dict respondsToSelector:@selector(objectForKey:)]) {
NSArray *answer = dict[@"Answer"];
if ([answer respondsToSelector:@selector(objectAtIndex:)]) {
for (NSDictionary *item in answer) {
if ([item respondsToSelector:@selector(objectForKey:)]) {
NSString *itemData = item[@"data"];
if ([itemData respondsToSelector:@selector(characterAtIndex:)]) {
bool isIp = true;
struct in_addr ip4;
struct in6_addr ip6;
if (inet_aton(itemData.UTF8String, &ip4) == 0) {
if (inet_pton(AF_INET6, itemData.UTF8String, &ip6) == 0) {
isIp = false;
}
}
if (isIp) {
[self cacheIp:hostname ip:itemData];
return [MTSignal single:itemData];
}
}
}
}
}
}
[subscriber putNext:hostname];
[subscriber putCompletion];
return nil;
}] startWithNext:^(id next) {
[subscriber putNext:next];
[subscriber putCompletion];
} error:^(id error) {
[subscriber putNext:hostname];
[subscriber putCompletion];
} completed:nil];
}];
}
+ (MTSignal *)resolveHostnameNative:(NSString *)hostname port:(int32_t)port {
return [[MTDNSContext shared] mapToSignal:^MTSignal *(MTDNSContext *context) {
return [[MTSignal alloc] initWithGenerator:^id<MTDisposable>(MTSubscriber *subscriber) {
return [context subscribe:hostname port:port completion:^(NSString *result) {
[subscriber putNext:result];
[subscriber putCompletion];
}];
}];
}];
}
+ (MTSignal *)resolveHostnameUniversal:(NSString *)hostname port:(int32_t)port {
return [[self resolveHostname:hostname] timeout:10.0 onQueue:[MTQueue concurrentDefaultQueue] orSignal:[self resolveHostnameNative:hostname port:port]];
}
@end