summaryrefslogtreecommitdiffstats
path: root/src/VBox/Main/src-server/darwin/HostDnsServiceDarwin.cpp
blob: 0d0b0d5cdedfeb3a1afd809c718a8a0dbaddc1af (plain)
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
/* $Id: HostDnsServiceDarwin.cpp $ */
/** @file
 * Darwin specific DNS information fetching.
 */

/*
 * Copyright (C) 2004-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include <VBox/com/string.h>
#include <VBox/com/ptr.h>


#include <iprt/asm.h>
#include <iprt/errcore.h>
#include <iprt/thread.h>
#include <iprt/semaphore.h>

#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SCDynamicStore.h>

#include <iprt/sanitized/string>
#include <vector>
#include "../HostDnsService.h"


struct HostDnsServiceDarwin::Data
{
    Data()
        : m_fStop(false) { }

    SCDynamicStoreRef m_store;
    CFRunLoopSourceRef m_DnsWatcher;
    CFRunLoopRef m_RunLoopRef;
    CFRunLoopSourceRef m_SourceStop;
    volatile bool m_fStop;
    RTSEMEVENT m_evtStop;
    static void performShutdownCallback(void *);
};


static const CFStringRef kStateNetworkGlobalDNSKey = CFSTR("State:/Network/Global/DNS");


HostDnsServiceDarwin::HostDnsServiceDarwin()
    : HostDnsServiceBase(true /* fThreaded */)
    , m(NULL)
{
    m = new HostDnsServiceDarwin::Data();
}

HostDnsServiceDarwin::~HostDnsServiceDarwin()
{
    if (m != NULL)
        delete m;
}

HRESULT HostDnsServiceDarwin::init(HostDnsMonitorProxy *pProxy)
{
    SCDynamicStoreContext ctx;
    RT_ZERO(ctx);

    ctx.info = this;

    m->m_store = SCDynamicStoreCreate(NULL, CFSTR("org.virtualbox.VBoxSVC.HostDNS"),
                                      (SCDynamicStoreCallBack)HostDnsServiceDarwin::hostDnsServiceStoreCallback,
                                      &ctx);
    AssertReturn(m->m_store, E_FAIL);

    m->m_DnsWatcher = SCDynamicStoreCreateRunLoopSource(NULL, m->m_store, 0);
    if (!m->m_DnsWatcher)
        return E_OUTOFMEMORY;

    int vrc = RTSemEventCreate(&m->m_evtStop);
    AssertRCReturn(vrc, E_FAIL);

    CFRunLoopSourceContext sctx;
    RT_ZERO(sctx);
    sctx.info    = this;
    sctx.perform = HostDnsServiceDarwin::Data::performShutdownCallback;

    m->m_SourceStop = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &sctx);
    AssertReturn(m->m_SourceStop, E_FAIL);

    HRESULT hrc = HostDnsServiceBase::init(pProxy);
    return hrc;
}

void HostDnsServiceDarwin::uninit(void)
{
    HostDnsServiceBase::uninit();

    CFRelease(m->m_SourceStop);
    CFRelease(m->m_RunLoopRef);
    CFRelease(m->m_DnsWatcher);
    CFRelease(m->m_store);

    RTSemEventDestroy(m->m_evtStop);
}

int HostDnsServiceDarwin::monitorThreadShutdown(RTMSINTERVAL uTimeoutMs)
{
    RTCLock grab(m_LockMtx);
    if (!m->m_fStop)
    {
        ASMAtomicXchgBool(&m->m_fStop, true);
        CFRunLoopSourceSignal(m->m_SourceStop);
        CFRunLoopStop(m->m_RunLoopRef);

        RTSemEventWait(m->m_evtStop, uTimeoutMs);
    }

    return VINF_SUCCESS;
}

int HostDnsServiceDarwin::monitorThreadProc(void)
{
    m->m_RunLoopRef = CFRunLoopGetCurrent();
    AssertReturn(m->m_RunLoopRef, VERR_INTERNAL_ERROR);

    CFRetain(m->m_RunLoopRef);

    CFRunLoopAddSource(m->m_RunLoopRef, m->m_SourceStop, kCFRunLoopCommonModes);

    CFArrayRef watchingArrayRef = CFArrayCreate(NULL,
                                                (const void **)&kStateNetworkGlobalDNSKey,
                                                1, &kCFTypeArrayCallBacks);
    if (!watchingArrayRef)
    {
        CFRelease(m->m_DnsWatcher);
        return VERR_NO_MEMORY;
    }

    if (SCDynamicStoreSetNotificationKeys(m->m_store, watchingArrayRef, NULL))
        CFRunLoopAddSource(CFRunLoopGetCurrent(), m->m_DnsWatcher, kCFRunLoopCommonModes);

    CFRelease(watchingArrayRef);

    onMonitorThreadInitDone();

    /* Trigger initial update. */
    int vrc = updateInfo();
    AssertRC(vrc); /* Not fatal in release builds. */  /** @todo r=bird: The function always returns VINF_SUCCESS. */

    while (!ASMAtomicReadBool(&m->m_fStop))
    {
        CFRunLoopRun();
    }

    CFRunLoopRemoveSource(m->m_RunLoopRef, m->m_SourceStop, kCFRunLoopCommonModes);

    /* We're notifying stopper thread. */
    RTSemEventSignal(m->m_evtStop);

    return VINF_SUCCESS;
}

int HostDnsServiceDarwin::updateInfo(void)
{
    CFPropertyListRef propertyRef = SCDynamicStoreCopyValue(m->m_store, kStateNetworkGlobalDNSKey);
    /**
     * # scutil
     * \> get State:/Network/Global/DNS
     * \> d.show
     * \<dictionary\> {
     * DomainName : vvl-domain
     * SearchDomains : \<array\> {
     * 0 : vvl-domain
     * 1 : de.vvl-domain.com
     * }
     * ServerAddresses : \<array\> {
     * 0 : 192.168.1.4
     * 1 : 192.168.1.1
     * 2 : 8.8.4.4
     *   }
     * }
     */

    if (!propertyRef)
        return VINF_SUCCESS;

    HostDnsInformation info;
    CFStringRef domainNameRef = (CFStringRef)CFDictionaryGetValue(static_cast<CFDictionaryRef>(propertyRef), CFSTR("DomainName"));
    if (domainNameRef)
    {
        const char *pszDomainName = CFStringGetCStringPtr(domainNameRef, CFStringGetSystemEncoding());
        if (pszDomainName)
            info.domain = pszDomainName;
    }

    CFArrayRef serverArrayRef = (CFArrayRef)CFDictionaryGetValue(static_cast<CFDictionaryRef>(propertyRef),
                                                                 CFSTR("ServerAddresses"));
    if (serverArrayRef)
    {
        CFIndex const cItems = CFArrayGetCount(serverArrayRef);
        for (CFIndex i = 0; i < cItems; ++i)
        {
            CFStringRef serverAddressRef = (CFStringRef)CFArrayGetValueAtIndex(serverArrayRef, i);
            if (!serverArrayRef)
                continue;

            /** @todo r=bird: This code is messed up as CFStringGetCStringPtr is documented
             *  to return NULL even if the string is valid.   Furthermore, we must have
             *  UTF-8 - some joker might decide latin-1 is better here for all we know
             *  and we'll end up with evil invalid UTF-8 sequences. */
            const char *pszServerAddress = CFStringGetCStringPtr(serverAddressRef, CFStringGetSystemEncoding());
            if (!pszServerAddress)
                continue;

            /** @todo r=bird: Why on earth are we using std::string and not Utf8Str?   */
            info.servers.push_back(std::string(pszServerAddress));
        }
    }

    CFArrayRef searchArrayRef = (CFArrayRef)CFDictionaryGetValue(static_cast<CFDictionaryRef>(propertyRef),
                                                                 CFSTR("SearchDomains"));
    if (searchArrayRef)
    {
        CFIndex const cItems = CFArrayGetCount(searchArrayRef);
        for (CFIndex i = 0; i < cItems; ++i)
        {
            CFStringRef searchStringRef = (CFStringRef)CFArrayGetValueAtIndex(searchArrayRef, i);
            if (!searchArrayRef)
                continue;

            /** @todo r=bird: This code is messed up as CFStringGetCStringPtr is documented
             *  to return NULL even if the string is valid.   Furthermore, we must have
             *  UTF-8 - some joker might decide latin-1 is better here for all we know
             *  and we'll end up with evil invalid UTF-8 sequences. */
            const char *pszSearchString = CFStringGetCStringPtr(searchStringRef, CFStringGetSystemEncoding());
            if (!pszSearchString)
                continue;

            /** @todo r=bird: Why on earth are we using std::string and not Utf8Str?   */
            info.searchList.push_back(std::string(pszSearchString));
        }
    }

    CFRelease(propertyRef);

    setInfo(info);

    return VINF_SUCCESS;
}

void HostDnsServiceDarwin::hostDnsServiceStoreCallback(void *, void *, void *pInfo)
{
    HostDnsServiceDarwin *pThis = (HostDnsServiceDarwin *)pInfo;
    AssertPtrReturnVoid(pThis);

    RTCLock grab(pThis->m_LockMtx);
    pThis->updateInfo();
}

void HostDnsServiceDarwin::Data::performShutdownCallback(void *pInfo)
{
    HostDnsServiceDarwin *pThis = (HostDnsServiceDarwin *)pInfo;
    AssertPtrReturnVoid(pThis);

    AssertPtrReturnVoid(pThis->m);
    ASMAtomicXchgBool(&pThis->m->m_fStop, true);
}