summaryrefslogtreecommitdiffstats
path: root/mDNSResponder/mDNSMacOSX/DomainBrowser/Shared/_CNDomainBrowser.m
blob: 379837727798a9f20b4f69f7aad7b7c4e165cf6d (plain) (blame)
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
/*
 *
 * Copyright (c) 2016 Apple Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#import "_CNDomainBrowser.h"
#import "CNDomainBrowserPathUtils.h"
#include <dns_sd.h>

const NSString *    _CNSubDomainKey_defaultFlag         = @"defaultFlag";
const NSString *    _CNSubDomainKey_subPath             = @"subPath";
const NSString *    _CNSubDomainKey_reverseDomainPath   = @"reverseDomainPath";

@interface _CNDomainBrowser ()

@property (assign) DNSServiceRef                    browseDomainR;
@property (strong) NSMutableDictionary *            browseDomainD;

@property (weak)   id<_CNDomainBrowserDelegate>    delegate;

@end

@implementation _CNDomainBrowser

void enumReply(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *replyDomain, void *context);

- (instancetype)initWithDelegate:(id<_CNDomainBrowserDelegate>)delegate
{
    if (self = [super init])
    {
        _delegate = delegate;
        [self _commonInit];
    }
    return(self);
}

- (void)_commonInit
{
    self.browseDomainD = [NSMutableDictionary dictionary];
    self.callbackQueue = dispatch_get_main_queue();
}

- (void)dealloc
{
    [self stopBrowser];
}

- (void)startBrowser
{
    if (!_browseDomainR)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            dispatch_queue_t queue = dispatch_queue_create("DNSServiceEnumerateDomains", DISPATCH_QUEUE_PRIORITY_DEFAULT);
            dispatch_set_context(queue, (void *)CFBridgingRetain(self));
            dispatch_set_finalizer_f(queue, finalizer);
            
            DNSServiceRef ref;
            if (DNSServiceEnumerateDomains(&ref, _browseRegistration ? kDNSServiceFlagsRegistrationDomains : kDNSServiceFlagsBrowseDomains, 0, enumReply, (__bridge void *)self))
                NSLog(@"DNSServiceEnumerateDomains failed");
            else
            {
                _browseDomainR = ref;
                (void)DNSServiceSetDispatchQueue(_browseDomainR, queue);
            }
        });
    }
}

- (void)stopBrowser
{    
    if (_browseDomainR)
    {
        DNSServiceRefDeallocate(_browseDomainR);
        _browseDomainR = nil;
    }
}

- (NSArray *)defaultDomainPath
{
    NSArray * revDomainArray = nil;
    
    NSArray *defaults = [[self.browseDomainD allValues] filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: @"(%K == %@)", _CNSubDomainKey_defaultFlag, @YES]];
    if (defaults.count)     revDomainArray = defaults[0][_CNSubDomainKey_reverseDomainPath];
    if (!revDomainArray)	revDomainArray = [NSArray arrayWithObject: @"local"];	//	If no defaults found
    
    return(revDomainArray);
}

- (NSArray *)flattenedDNSDomains
{
    return([self.browseDomainD allKeys]);
}

- (NSArray *)subDomainsAtDomainPath:(NSArray *)domainPath
{
    NSMutableDictionary * subs = [NSMutableDictionary dictionary];
    for (NSDictionary * next in [self.browseDomainD allValues])
    {
        NSArray * bdomain = next[_CNSubDomainKey_reverseDomainPath];
        if (bdomain.count > domainPath.count)
        {
            BOOL	match = YES;
            for (NSUInteger i = 0 ; i < domainPath.count ; i++)
            {
                if (![bdomain[i] isEqualToString: domainPath[i]])	{ match = NO;	break; }
            }
            if (match)
            {
                NSString * key = bdomain[domainPath.count];
                [subs setObject: @{ _CNSubDomainKey_subPath: key, _CNSubDomainKey_defaultFlag: next[_CNSubDomainKey_defaultFlag] } forKey: key];
            }
        }
    }
    return([subs allValues]);
}

- (void) reloadBrowser
{
    if ([_delegate respondsToSelector: @selector(bonjourBrowserDomainUpdate:)])
    {
        dispatch_async(self.callbackQueue, ^{
            [_delegate bonjourBrowserDomainUpdate: [self defaultDomainPath]];
        });
    }
}

- (BOOL)isBrowsing
{
    return(_browseDomainR != nil);
}

#pragma mark - Dispatch

static void finalizer(void * context)
{
    _CNDomainBrowser *self = (__bridge _CNDomainBrowser *)context;
    NSLog(@"finalizer: %@", self);
    (void)CFBridgingRelease((__bridge void *)self);
}

#pragma mark - Commands

#pragma mark - Static Callbacks

void enumReply(DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode,
               const char *replyDomain, void *context)
{
	(void)sdRef;
	(void)interfaceIndex;
	(void)errorCode;
	
    if (!*replyDomain) return;
    
    _CNDomainBrowser *self = (__bridge _CNDomainBrowser *)context;
    NSString *key = [NSString stringWithUTF8String: replyDomain];
    
    if (self.ignoreLocal && [key isEqualToString: @"local."])   return;
    if (self.ignoreBTMM && [key hasSuffix: @".members.btmm.icloud.com."])   return;
    
    if (!(flags & kDNSServiceFlagsAdd))
    {
        [self.browseDomainD removeObjectForKey:key];
    }
    else
    {
        NSArray * pathArray = DNSDomainToDomainPath(key);
        [self.browseDomainD setObject: @{ _CNSubDomainKey_reverseDomainPath: pathArray,
                                          _CNSubDomainKey_defaultFlag: (flags & kDNSServiceFlagsDefault) ? @YES : @NO }
                               forKey: key];
    }
    
    if (!(flags & kDNSServiceFlagsMoreComing))
    {
        [self reloadBrowser];
    }
}

@end