-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathDNSResolver.m
323 lines (265 loc) · 11 KB
/
DNSResolver.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
//
// DNSResolver.m
// NoMAD
//
// Created by Boushy, Phillip on 9/28/16.
// Copyright © 2016 Orchard & Grove Inc. All rights reserved.
//
#import "DNSResolver.h"
#include <dns_util.h>
#include <net/if.h>
@interface DNSResolver ()
@property (nonatomic, assign, readwrite) BOOL finished;
@property (nonatomic, copy, readwrite) NSError *error;
// Private Properties
@property (nonatomic, strong, readonly) NSMutableArray *mutableQueryResponse;
@end
@implementation DNSResolver {
DNSServiceRef _dnsService;
CFSocketRef _dnsSocket;
}
@synthesize queryType = _queryType;
@synthesize queryValue = _queryValue;
@synthesize delegate = _delegate;
- init {
self = [super init];
if (self != nil) {
self->_mutableQueryResponse = [[NSMutableArray alloc] init];
}
return self;
}
- initWithQueryType:(NSString*)queryType andValue:(NSString*)queryValue {
assert(queryType != nil);
assert(queryValue != nil);
self = [super init];
if (self != nil) {
self->_queryType = [queryType copy];
self->_queryValue = [queryValue copy];
self->_mutableQueryResponse = [[NSMutableArray alloc] init];
assert(self->_mutableQueryResponse != nil);
}
return self;
}
/*
-(void)dealloc {
[self stop];
}
*/
-(void)startQuery {
if (self->_dnsService == NULL) {
self.error = nil;
self.finished = NO;
[_mutableQueryResponse removeAllObjects];
[self startInternal];
}
}
-(uint16_t)getTypeAsInt {
uint16_t recordType;
if ([self.queryType isEqualToString:@"SRV"]) {
recordType = kDNSServiceType_SRV;
} else if ([self.queryType isEqualToString:@"PTR"]) {
recordType = kDNSServiceType_PTR;
} else {
recordType = kDNSServiceType_ANY;
}
return recordType;
}
-(void)startInternal {
DNSServiceErrorType err;
const char * dnsNameCStr;
int socketProtocol;
int flags;
// version (always 0), info (self because it's easy to reference?), retain, release, copyDescription
CFSocketContext context = { 0, (__bridge void *) self, NULL, NULL, NULL };
CFRunLoopSourceRef runLoopSource;
// Start off with no errors.
err = kDNSServiceErr_NoError;
//Create a C string of the queryValue and verifies it is not empty.
dnsNameCStr = [self.queryValue UTF8String];
if (dnsNameCStr == nil) {
err = kDNSServiceErr_BadParam;
}
// Create a query for the type and value
if (err == kDNSServiceErr_NoError) {
// perform different types of query based on queryType...
uint16_t recordType = [self getTypeAsInt];
//uint32_t interfaceIndex = if_nametoindex("utun1");
// check for .local
if ( [self.queryValue hasSuffix:@".local"]) {
flags = (kDNSServiceFlagsReturnIntermediates + kDNSServiceFlagsTimeout);
} else {
flags = kDNSServiceFlagsReturnIntermediates;
}
// Create the DNS Query and reference it in self->_dnsService
err = DNSServiceQueryRecord(
&self->_dnsService,
flags,
0, // query on all interfaces.
dnsNameCStr,
recordType,
kDNSServiceClass_IN,
DNSServiceRecordCallback,
(__bridge void*) self
);
}
// Create a socket that listens for incoming messages related to the DNS Query.
if (err == kDNSServiceErr_NoError) {
socketProtocol = DNSServiceRefSockFD(self->_dnsService);
self->_dnsSocket = CFSocketCreateWithNative(
NULL,
socketProtocol,
kCFSocketReadCallBack,
DNSSocketCallback,
&context
);
// Tell the socket to close on invalidation on top of any other flags it already has set.
// This is good and the default.
CFSocketSetSocketFlags(
self->_dnsSocket,
CFSocketGetSocketFlags(self->_dnsSocket) & ~ (CFOptionFlags) kCFSocketCloseOnInvalidate
);
runLoopSource = CFSocketCreateRunLoopSource(NULL, self->_dnsSocket, 0);
assert(runLoopSource != NULL);
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode);
CFRelease(runLoopSource);
}
if (err != kDNSServiceErr_NoError) {
[self stopQueryWithDNSServiceError:err];
}
}
static void DNSServiceRecordCallback(
DNSServiceRef dnsService,
DNSServiceFlags flags,
uint32_t interfaceIndex,
DNSServiceErrorType errorCode,
const char * fullname,
uint16_t recordType,
uint16_t recordClass,
uint16_t recordLength,
const void * recordData,
uint32_t ttl,
void * context
) {
DNSResolver * obj;
obj = (__bridge DNSResolver *)context;
if (errorCode == kDNSServiceErr_NoError) {
// Get Interface Name
//char *interfaceNamePtr = alloca(IF_NAMESIZE);
//char *interfaceName = if_indextoname(interfaceIndex, interfaceNamePtr);
//NSLog(@"Interface Index is: %u. Interface Name is: %s", interfaceIndex, interfaceName);
//Process Record
[obj processRecord:recordData length:recordLength];
if ( ! (flags & kDNSServiceFlagsMoreComing) ) {
[obj stopQueryWithError:nil];
}
} else {
[obj stopQueryWithDNSServiceError:errorCode];
}
}
static void DNSSocketCallback(
CFSocketRef dnsSocket,
CFSocketCallBackType type,
CFDataRef address,
const void * data,
void * info
) {
DNSServiceErrorType err;
DNSResolver * obj;
obj = (__bridge DNSResolver *)info;
err = DNSServiceProcessResult(obj->_dnsService);
if ( err != kDNSServiceErr_NoError) {
[obj stopQueryWithDNSServiceError:err];
}
}
-(void)processRecord:(const void *)recordData length:(NSUInteger)recordLength {
NSMutableData * resourceRecordData;
dns_resource_record_t * resourceRecord;
uint8_t u8;
uint16_t u16;
uint32_t u32;
//Creating the data to send to dns_parse_resource_record.
resourceRecordData = [NSMutableData data];
u8 = 0;
[resourceRecordData appendBytes:&u8 length:sizeof(u8)];
// DNS Type
uint16_t recordType = [self getTypeAsInt];
u16 = htons(recordType);
[resourceRecordData appendBytes:&u16 length:sizeof(u16)];
// DNS Class
u16 = htons(kDNSServiceClass_IN);
[resourceRecordData appendBytes:&u16 length:sizeof(u16)];
// TTL
u32 = htonl(666);
[resourceRecordData appendBytes:&u32 length:sizeof(u32)];
// Record Length
u16 = htons(recordLength);
[resourceRecordData appendBytes:&u16 length:sizeof(u16)];
[resourceRecordData appendBytes:recordData length:recordLength];
//Parse the record
resourceRecord = dns_parse_resource_record([resourceRecordData bytes], (uint32_t) [resourceRecordData length]);
if (resourceRecord != NULL) {
if ([self.queryType isEqualToString:@"SRV"]) {
NSString * target = [NSString stringWithCString:resourceRecord->data.SRV->target encoding:NSASCIIStringEncoding];
if (target != nil) {
NSDictionary * result;
NSIndexSet * resultIndexSet;
result = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInt:resourceRecord->data.SRV->priority], kSRVResolverPriority,
[NSNumber numberWithUnsignedInt:resourceRecord->data.SRV->weight], kSRVResolverWeight,
[NSNumber numberWithUnsignedInt:resourceRecord->data.SRV->port], kSRVResolverPort,
target, kSRVResolverTarget,
nil
];
assert(result != nil);
resultIndexSet = [NSIndexSet indexSetWithIndex:self.queryResults.count];
assert(resultIndexSet != nil);
[self willChange:NSKeyValueChangeInsertion valuesAtIndexes:resultIndexSet forKey:@"results"];
[self.mutableQueryResponse addObject:result];
[self didChange:NSKeyValueChangeInsertion valuesAtIndexes:resultIndexSet forKey:@"results"];
if ( (self.delegate != nil) && [self.delegate respondsToSelector:@selector(dnsResolver:didReceiveQueryResult:)] ) {
[self.delegate dnsResolver:self didReceiveQueryResult:result];
}
}
}
dns_free_resource_record(resourceRecord);
}
}
# pragma mark - Stop Query Methods
-(void)stopQuery {
if (self->_dnsSocket != NULL) {
CFSocketInvalidate(self->_dnsSocket);
CFRelease(self->_dnsSocket);
self->_dnsSocket = NULL;
}
if (self->_dnsService != NULL) {
DNSServiceRefDeallocate(self->_dnsService);
self->_dnsService = NULL;
}
self.finished = YES;
}
-(void)stopQueryWithError:(NSError *)error {
self.error = error;
[self stopQuery];
if ( (self.delegate != nil) && [self.delegate respondsToSelector:@selector(dnsResolver:didStopQueryWithError:)] ) {
[self.delegate dnsResolver:self didStopQueryWithError:error];
}
}
- (void)stopQueryWithDNSServiceError:(DNSServiceErrorType)errorCode
{
NSError * error;
error = nil;
if (errorCode != kDNSServiceErr_NoError) {
error = [NSError errorWithDomain:kDNSResolverErrorDomain code:errorCode userInfo:nil];
}
[self stopQueryWithError:error];
}
# pragma mark - Results
- (NSArray *)queryResults {
return [self.mutableQueryResponse copy];
}
@end
NSString * kSRVResolverPriority = @"priority";
NSString * kSRVResolverWeight = @"weight";
NSString * kSRVResolverPort = @"port";
NSString * kSRVResolverTarget = @"target";
NSString * kDNSResolverErrorDomain = @"kDNSResolverErrorDomain";