forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDnssdHostNameRegistrar.cpp
439 lines (376 loc) · 14 KB
/
DnssdHostNameRegistrar.cpp
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/*
*
* Copyright (c) 2022 Project CHIP Authors
*
* 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.
*/
#include "DnssdHostNameRegistrar.h"
#include "DnssdImpl.h"
#include "MdnsError.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/ethernet.h>
#include <net/if_dl.h>
#include <netdb.h>
#include <set>
#include <platform/CHIPDeviceLayer.h>
constexpr DNSServiceFlags kRegisterRecordFlags = kDNSServiceFlagsShared;
namespace chip {
namespace Dnssd {
namespace {
#if CHIP_PROGRESS_LOGGING
constexpr char kPathStatusInvalid[] = "Invalid";
constexpr char kPathStatusUnsatisfied[] = "Unsatisfied";
constexpr char kPathStatusSatisfied[] = "Satisfied";
constexpr char kPathStatusSatisfiable[] = "Satisfiable";
constexpr char kPathStatusUnknown[] = "Unknown";
constexpr char kInterfaceTypeCellular[] = "Cellular";
constexpr char kInterfaceTypeWiFi[] = "WiFi";
constexpr char kInterfaceTypeWired[] = "Wired";
constexpr char kInterfaceTypeLoopback[] = "Loopback";
constexpr char kInterfaceTypeOther[] = "Other";
constexpr char kInterfaceTypeUnknown[] = "Unknown";
const char * GetPathStatusString(nw_path_status_t status)
{
const char * str = nullptr;
if (status == nw_path_status_invalid)
{
str = kPathStatusInvalid;
}
else if (status == nw_path_status_unsatisfied)
{
str = kPathStatusUnsatisfied;
}
else if (status == nw_path_status_satisfied)
{
str = kPathStatusSatisfied;
}
else if (status == nw_path_status_satisfiable)
{
str = kPathStatusSatisfiable;
}
else
{
str = kPathStatusUnknown;
}
return str;
}
const char * GetInterfaceTypeString(nw_interface_type_t type)
{
const char * str = nullptr;
if (type == nw_interface_type_cellular)
{
str = kInterfaceTypeCellular;
}
else if (type == nw_interface_type_wifi)
{
str = kInterfaceTypeWiFi;
}
else if (type == nw_interface_type_wired)
{
str = kInterfaceTypeWired;
}
else if (type == nw_interface_type_loopback)
{
str = kInterfaceTypeLoopback;
}
else if (type == nw_interface_type_other)
{
str = kInterfaceTypeOther;
}
else
{
str = kInterfaceTypeUnknown;
}
return str;
}
void LogDetails(uint32_t interfaceId, InetInterfacesVector inetInterfaces, Inet6InterfacesVector inet6Interfaces)
{
for (auto & inetInterface : inetInterfaces)
{
if (interfaceId == inetInterface.first)
{
char addr[INET_ADDRSTRLEN] = {};
inet_ntop(AF_INET, &inetInterface.second, addr, sizeof(addr));
ChipLogProgress(Discovery, "\t\t* ipv4: %s", addr);
}
}
for (auto & inet6Interface : inet6Interfaces)
{
if (interfaceId == inet6Interface.first)
{
char addr[INET6_ADDRSTRLEN] = {};
inet_ntop(AF_INET6, &inet6Interface.second, addr, sizeof(addr));
ChipLogProgress(Discovery, "\t\t* ipv6: %s", addr);
}
}
}
void LogDetails(nw_path_t path)
{
auto status = nw_path_get_status(path);
ChipLogProgress(Discovery, "Status: %s", GetPathStatusString(status));
}
void LogDetails(InetInterfacesVector inetInterfaces, Inet6InterfacesVector inet6Interfaces)
{
std::set<uint32_t> interfaceIds;
for (auto & inetInterface : inetInterfaces)
{
interfaceIds.insert(inetInterface.first);
}
for (auto & inet6Interface : inet6Interfaces)
{
interfaceIds.insert(inet6Interface.first);
}
for (auto interfaceId : interfaceIds)
{
char interfaceName[chip::Inet::InterfaceId::kMaxIfNameLength] = {};
if_indextoname(interfaceId, interfaceName);
ChipLogProgress(Discovery, "\t%s (%u)", interfaceName, interfaceId);
LogDetails(interfaceId, inetInterfaces, inet6Interfaces);
}
}
void LogDetails(nw_interface_t interface, InetInterfacesVector inetInterfaces, Inet6InterfacesVector inet6Interfaces)
{
auto interfaceId = nw_interface_get_index(interface);
auto interfaceName = nw_interface_get_name(interface);
auto interfaceType = nw_interface_get_type(interface);
ChipLogProgress(Discovery, "\t%s (%u / %s)", interfaceName, interfaceId, GetInterfaceTypeString(interfaceType));
LogDetails(interfaceId, inetInterfaces, inet6Interfaces);
}
#endif // CHIP_PROGRESS_LOGGING
bool HasValidFlags(unsigned int flags, bool allowLoopbackOnly)
{
VerifyOrReturnValue(!allowLoopbackOnly || (flags & IFF_LOOPBACK), false);
VerifyOrReturnValue((flags & IFF_RUNNING), false);
VerifyOrReturnValue((flags & IFF_MULTICAST), false);
return true;
}
bool HasValidNetworkType(nw_interface_t interface)
{
auto interfaceType = nw_interface_get_type(interface);
return interfaceType == nw_interface_type_wifi || interfaceType == nw_interface_type_wired ||
interfaceType == nw_interface_type_other;
}
bool IsValidInterfaceId(uint32_t targetInterfaceId, nw_interface_t interface)
{
auto currentInterfaceId = nw_interface_get_index(interface);
return targetInterfaceId == kDNSServiceInterfaceIndexAny || targetInterfaceId == currentInterfaceId;
}
void ShouldUseVersion(chip::Inet::IPAddressType addressType, bool & shouldUseIPv4, bool & shouldUseIPv6)
{
#if INET_CONFIG_ENABLE_IPV4
shouldUseIPv4 = addressType == Inet::IPAddressType::kIPv4 || addressType == Inet::IPAddressType::kAny;
#else
shouldUseIPv4 = false;
#endif // INET_CONFIG_ENABLE_IPV4
shouldUseIPv6 = addressType == Inet::IPAddressType::kIPv6 || addressType == Inet::IPAddressType::kAny;
}
static void OnRegisterRecord(DNSServiceRef sdRef, DNSRecordRef recordRef, DNSServiceFlags flags, DNSServiceErrorType err,
void * context)
{
ChipLogProgress(Discovery, "Mdns: %s flags: %d", __func__, flags);
if (kDNSServiceErr_NoError != err)
{
ChipLogError(Discovery, "%s (%s)", __func__, Error::ToString(err));
}
}
void GetInterfaceAddresses(uint32_t interfaceId, chip::Inet::IPAddressType addressType, InetInterfacesVector & inetInterfaces,
Inet6InterfacesVector & inet6Interfaces, bool searchLoopbackOnly = false)
{
bool shouldUseIPv4, shouldUseIPv6;
ShouldUseVersion(addressType, shouldUseIPv4, shouldUseIPv6);
ifaddrs * ifap;
VerifyOrReturn(getifaddrs(&ifap) >= 0);
for (struct ifaddrs * ifa = ifap; ifa != nullptr; ifa = ifa->ifa_next)
{
auto interfaceAddress = ifa->ifa_addr;
if (interfaceAddress == nullptr)
{
continue;
}
if (!HasValidFlags(ifa->ifa_flags, searchLoopbackOnly))
{
continue;
}
auto currentInterfaceId = if_nametoindex(ifa->ifa_name);
if (interfaceId != kDNSServiceInterfaceIndexAny && interfaceId != currentInterfaceId)
{
continue;
}
if (shouldUseIPv4 && (AF_INET == interfaceAddress->sa_family))
{
auto inetAddress = reinterpret_cast<struct sockaddr_in *>(interfaceAddress)->sin_addr;
inetInterfaces.push_back(InetInterface(currentInterfaceId, inetAddress));
}
else if (shouldUseIPv6 && (AF_INET6 == interfaceAddress->sa_family))
{
auto inet6Address = reinterpret_cast<struct sockaddr_in6 *>(interfaceAddress)->sin6_addr;
inet6Interfaces.push_back(Inet6Interface(currentInterfaceId, inet6Address));
}
}
freeifaddrs(ifap);
}
} // namespace
HostNameRegistrar::~HostNameRegistrar()
{
Unregister();
if (mLivenessTracker != nullptr)
{
*mLivenessTracker = false;
}
}
DNSServiceErrorType HostNameRegistrar::Init(const char * hostname, Inet::IPAddressType addressType, uint32_t interfaceId)
{
mHostname = hostname;
mInterfaceId = interfaceId;
mAddressType = addressType;
mServiceRef = nullptr;
mInterfaceMonitor = nullptr;
mLivenessTracker = std::make_shared<bool>(true);
if (mLivenessTracker == nullptr)
{
return kDNSServiceErr_NoMemory;
}
return kDNSServiceErr_NoError;
}
CHIP_ERROR HostNameRegistrar::Register()
{
// If the target interface is kDNSServiceInterfaceIndexLocalOnly, just
// register the loopback addresses.
if (IsLocalOnly())
{
ReturnErrorOnFailure(ResetSharedConnection());
InetInterfacesVector inetInterfaces;
Inet6InterfacesVector inet6Interfaces;
// Instead of mInterfaceId (which will not match any actual interface),
// use kDNSServiceInterfaceIndexAny and restrict to loopback interfaces.
GetInterfaceAddresses(kDNSServiceInterfaceIndexAny, mAddressType, inetInterfaces, inet6Interfaces,
true /* searchLoopbackOnly */);
// But we register the IPs with mInterfaceId, not the actual interface
// IDs, so that resolution code that is grouping addresses by interface
// ends up doing the right thing, since we registered our SRV record on
// mInterfaceId.
//
// And only register the IPv6 ones, for simplicity.
for (auto & interface : inet6Interfaces)
{
ReturnErrorOnFailure(RegisterInterface(mInterfaceId, interface.second, kDNSServiceType_AAAA));
}
return CHIP_NO_ERROR;
}
return StartMonitorInterfaces(^(InetInterfacesVector inetInterfaces, Inet6InterfacesVector inet6Interfaces) {
ReturnOnFailure(ResetSharedConnection());
RegisterInterfaces(inetInterfaces, kDNSServiceType_A);
RegisterInterfaces(inet6Interfaces, kDNSServiceType_AAAA);
});
}
CHIP_ERROR HostNameRegistrar::RegisterInterface(uint32_t interfaceId, uint16_t rtype, const void * rdata, uint16_t rdlen)
{
DNSRecordRef dnsRecordRef;
auto err = DNSServiceRegisterRecord(mServiceRef, &dnsRecordRef, kRegisterRecordFlags, interfaceId, mHostname.c_str(), rtype,
kDNSServiceClass_IN, rdlen, rdata, 0, OnRegisterRecord, nullptr);
return Error::ToChipError(err);
}
void HostNameRegistrar::Unregister()
{
if (!IsLocalOnly())
{
StopMonitorInterfaces();
}
StopSharedConnection();
}
CHIP_ERROR HostNameRegistrar::StartMonitorInterfaces(OnInterfaceChanges interfaceChangesBlock)
{
mInterfaceMonitor = nw_path_monitor_create();
VerifyOrReturnError(mInterfaceMonitor != nullptr, CHIP_ERROR_NO_MEMORY);
nw_path_monitor_set_queue(mInterfaceMonitor, chip::DeviceLayer::PlatformMgrImpl().GetWorkQueue());
// Our update handler closes over "this", but can't keep us alive (because we
// are not refcounted). Make sure it closes over a shared ref to our
// liveness tracker, which it _can_ keep alive, so it can bail out if we
// have been destroyed between when the task was queued and when it ran.
std::shared_ptr<bool> livenessTracker = mLivenessTracker;
nw_path_monitor_set_update_handler(mInterfaceMonitor, ^(nw_path_t path) {
if (!*livenessTracker)
{
// The HostNameRegistrar has been destroyed; just bail out.
return;
}
#if CHIP_PROGRESS_LOGGING
LogDetails(path);
#endif // CHIP_PROGRESS_LOGGING
__block InetInterfacesVector inet;
__block Inet6InterfacesVector inet6;
// The loopback interfaces needs to be manually added. While lo0 is usually 1, this is not guaranteed. So search for a
// loopback interface with the specified interface id. If the specified interface id is kDNSServiceInterfaceIndexAny, it
// will look for all available loopback interfaces.
GetInterfaceAddresses(mInterfaceId, mAddressType, inet, inet6, true /* searchLoopbackOnly */);
#if CHIP_PROGRESS_LOGGING
LogDetails(inet, inet6);
#endif // CHIP_PROGRESS_LOGGING
auto status = nw_path_get_status(path);
if (status == nw_path_status_satisfied)
{
nw_path_enumerate_interfaces(path, ^(nw_interface_t interface) {
VerifyOrReturnValue(HasValidNetworkType(interface), true);
VerifyOrReturnValue(IsValidInterfaceId(mInterfaceId, interface), true);
auto targetInterfaceId = nw_interface_get_index(interface);
GetInterfaceAddresses(targetInterfaceId, mAddressType, inet, inet6);
#if CHIP_PROGRESS_LOGGING
LogDetails(interface, inet, inet6);
#endif // CHIP_PROGRESS_LOGGING
return true;
});
}
interfaceChangesBlock(inet, inet6);
});
nw_path_monitor_start(mInterfaceMonitor);
return CHIP_NO_ERROR;
}
void HostNameRegistrar::StopMonitorInterfaces()
{
if (mInterfaceMonitor != nullptr)
{
nw_path_monitor_cancel(mInterfaceMonitor);
nw_release(mInterfaceMonitor);
mInterfaceMonitor = nullptr;
}
}
CHIP_ERROR HostNameRegistrar::StartSharedConnection()
{
VerifyOrReturnError(mServiceRef == nullptr, CHIP_ERROR_INCORRECT_STATE);
auto err = DNSServiceCreateConnection(&mServiceRef);
VerifyOrReturnValue(kDNSServiceErr_NoError == err, Error::ToChipError(err));
err = DNSServiceSetDispatchQueue(mServiceRef, chip::DeviceLayer::PlatformMgrImpl().GetWorkQueue());
if (kDNSServiceErr_NoError != err)
{
StopSharedConnection();
}
return Error::ToChipError(err);
}
void HostNameRegistrar::StopSharedConnection()
{
if (mServiceRef != nullptr)
{
// All the DNSRecordRefs registered to the shared DNSServiceRef will be deallocated.
DNSServiceRefDeallocate(mServiceRef);
mServiceRef = nullptr;
}
}
CHIP_ERROR HostNameRegistrar::ResetSharedConnection()
{
StopSharedConnection();
ReturnLogErrorOnFailure(StartSharedConnection());
return CHIP_NO_ERROR;
}
} // namespace Dnssd
} // namespace chip