-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Resolver_ImplMinimalMdns.cpp
531 lines (462 loc) · 17.3 KB
/
Resolver_ImplMinimalMdns.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
/*
*
* Copyright (c) 2021 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 "Resolver.h"
#include <limits>
#include "MinimalMdnsServer.h"
#include "ServiceNaming.h"
#include <mdns/TxtFields.h>
#include <mdns/minimal/Parser.h>
#include <mdns/minimal/QueryBuilder.h>
#include <mdns/minimal/RecordData.h>
#include <mdns/minimal/core/FlatAllocatedQName.h>
#include <support/CHIPMemString.h>
#include <support/logging/CHIPLogging.h>
// MDNS servers will receive all broadcast packets over the network.
// Disable 'invalid packet' messages because the are expected and common
// These logs are useful for debug only
#undef MINMDNS_RESOLVER_OVERLY_VERBOSE
namespace chip {
namespace Mdns {
namespace {
const ByteSpan GetSpan(const mdns::Minimal::BytesRange & range)
{
return ByteSpan(range.Start(), range.Size());
}
template <class NodeData>
class TxtRecordDelegateImpl : public mdns::Minimal::TxtRecordDelegate
{
public:
explicit TxtRecordDelegateImpl(NodeData & nodeData) : mNodeData(nodeData) {}
void OnRecord(const mdns::Minimal::BytesRange & name, const mdns::Minimal::BytesRange & value) override
{
FillNodeDataFromTxt(GetSpan(name), GetSpan(value), mNodeData);
}
private:
NodeData & mNodeData;
};
constexpr size_t kMdnsMaxPacketSize = 1024;
constexpr uint16_t kMdnsPort = 5353;
using namespace mdns::Minimal;
class PacketDataReporter : public ParserDelegate
{
public:
PacketDataReporter(ResolverDelegate * delegate, chip::Inet::InterfaceId interfaceId, DiscoveryType discoveryType,
const BytesRange & packet) :
mDelegate(delegate),
mDiscoveryType(discoveryType), mPacketRange(packet)
{
mNodeData.mInterfaceId = interfaceId;
}
// ParserDelegate implementation
void OnHeader(ConstHeaderRef & header) override;
void OnQuery(const QueryData & data) override;
void OnResource(ResourceType type, const ResourceData & data) override;
// Called after ParsePacket is complete to send final notifications to the delegate.
// Used to ensure all the available IP addresses are attached before completion.
void OnComplete();
private:
ResolverDelegate * mDelegate = nullptr;
DiscoveryType mDiscoveryType;
ResolvedNodeData mNodeData;
DiscoveredNodeData mDiscoveredNodeData;
BytesRange mPacketRange;
bool mValid = false;
bool mHasNodePort = false;
bool mHasIP = false;
void OnCommissionableNodeSrvRecord(SerializedQNameIterator name, const SrvRecord & srv);
void OnOperationalSrvRecord(SerializedQNameIterator name, const SrvRecord & srv);
void OnDiscoveredNodeIPAddress(const chip::Inet::IPAddress & addr);
void OnOperationalIPAddress(const chip::Inet::IPAddress & addr);
};
void PacketDataReporter::OnQuery(const QueryData & data)
{
ChipLogError(Discovery, "Unexpected query packet being parsed as a response");
mValid = false;
}
void PacketDataReporter::OnHeader(ConstHeaderRef & header)
{
mValid = header.GetFlags().IsResponse();
if (header.GetFlags().IsTruncated())
{
#ifdef MINMDNS_RESOLVER_OVERLY_VERBOSE
// MinMdns does not cache data, so receiving piecewise data does not work
ChipLogError(Discovery, "Truncated responses not supported for address resolution");
#endif
}
}
void PacketDataReporter::OnOperationalSrvRecord(SerializedQNameIterator name, const SrvRecord & srv)
{
mdns::Minimal::SerializedQNameIterator it = srv.GetName();
if (it.Next())
{
Platform::CopyString(mNodeData.mHostName, it.Value());
}
if (!name.Next())
{
#ifdef MINMDNS_RESOLVER_OVERLY_VERBOSE
ChipLogError(Discovery, "mDNS packet is missing a valid server name");
#endif
mHasNodePort = false;
return;
}
if (ExtractIdFromInstanceName(name.Value(), &mNodeData.mPeerId) != CHIP_NO_ERROR)
{
ChipLogError(Discovery, "Failed to parse peer id from %s", name.Value());
mHasNodePort = false;
return;
}
mNodeData.mPort = srv.GetPort();
mHasNodePort = true;
}
void PacketDataReporter::OnCommissionableNodeSrvRecord(SerializedQNameIterator name, const SrvRecord & srv)
{
// Host name is the first part of the qname
mdns::Minimal::SerializedQNameIterator it = srv.GetName();
if (it.Next())
{
Platform::CopyString(mDiscoveredNodeData.hostName, it.Value());
}
if (name.Next())
{
strncpy(mDiscoveredNodeData.instanceName, name.Value(), sizeof(DiscoveredNodeData::instanceName));
}
}
void PacketDataReporter::OnOperationalIPAddress(const chip::Inet::IPAddress & addr)
{
// TODO: should validate that the IP address we receive belongs to the
// server associated with the SRV record.
//
// This code assumes that all entries in the mDNS packet relate to the
// same entity. This may not be correct if multiple servers are reported
// (if multi-admin decides to use unique ports for every ecosystem).
mNodeData.mAddress = addr;
mHasIP = true;
}
void PacketDataReporter::OnDiscoveredNodeIPAddress(const chip::Inet::IPAddress & addr)
{
if (mDiscoveredNodeData.numIPs >= DiscoveredNodeData::kMaxIPAddresses)
{
return;
}
mDiscoveredNodeData.ipAddress[mDiscoveredNodeData.numIPs++] = addr;
}
bool HasQNamePart(SerializedQNameIterator qname, QNamePart part)
{
while (qname.Next())
{
if (strcmp(qname.Value(), part) == 0)
{
return true;
}
}
return false;
}
void PacketDataReporter::OnResource(ResourceType type, const ResourceData & data)
{
if (!mValid)
{
return;
}
/// Data content is expected to contain:
/// - A SRV entry that includes the node ID in expected format (fabric + nodeid)
/// - Can extract: fabricid, nodeid, port
/// - References ServerName
/// - Additional records tied to ServerName contain A/AAAA records for IP address data
switch (data.GetType())
{
case QType::SRV: {
SrvRecord srv;
if (!srv.Parse(data.GetData(), mPacketRange))
{
ChipLogError(Discovery, "Packet data reporter failed to parse SRV record");
mHasNodePort = false;
}
else if (mDiscoveryType == DiscoveryType::kOperational)
{
// Ensure this is our record.
// TODO: Fix this comparison which is too loose.
if (HasQNamePart(data.GetName(), kOperationalServiceName))
{
OnOperationalSrvRecord(data.GetName(), srv);
}
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode || mDiscoveryType == DiscoveryType::kCommissionerNode)
{
// TODO: Fix this comparison which is too loose.
if (HasQNamePart(data.GetName(), kCommissionableServiceName) || HasQNamePart(data.GetName(), kCommissionerServiceName))
{
OnCommissionableNodeSrvRecord(data.GetName(), srv);
}
}
break;
}
case QType::PTR: {
if (mDiscoveryType == DiscoveryType::kCommissionableNode)
{
SerializedQNameIterator qname;
ParsePtrRecord(data.GetData(), mPacketRange, &qname);
if (qname.Next())
{
strncpy(mDiscoveredNodeData.instanceName, qname.Value(), sizeof(DiscoveredNodeData::instanceName));
}
}
break;
}
case QType::TXT:
if (mDiscoveryType == DiscoveryType::kCommissionableNode || mDiscoveryType == DiscoveryType::kCommissionerNode)
{
TxtRecordDelegateImpl<DiscoveredNodeData> textRecordDelegate(mDiscoveredNodeData);
ParseTxtRecord(data.GetData(), &textRecordDelegate);
}
else if (mDiscoveryType == DiscoveryType::kOperational)
{
TxtRecordDelegateImpl<ResolvedNodeData> textRecordDelegate(mNodeData);
ParseTxtRecord(data.GetData(), &textRecordDelegate);
}
break;
case QType::A: {
Inet::IPAddress addr;
if (!ParseARecord(data.GetData(), &addr))
{
ChipLogError(Discovery, "Packet data reporter failed to parse A record");
mHasIP = false;
}
else
{
if (mDiscoveryType == DiscoveryType::kOperational)
{
OnOperationalIPAddress(addr);
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode || mDiscoveryType == DiscoveryType::kCommissionerNode)
{
OnDiscoveredNodeIPAddress(addr);
}
}
break;
}
case QType::AAAA: {
Inet::IPAddress addr;
if (!ParseAAAARecord(data.GetData(), &addr))
{
ChipLogError(Discovery, "Packet data reporter failed to parse AAAA record");
mHasIP = false;
}
else
{
if (mDiscoveryType == DiscoveryType::kOperational)
{
OnOperationalIPAddress(addr);
}
else if (mDiscoveryType == DiscoveryType::kCommissionableNode || mDiscoveryType == DiscoveryType::kCommissionerNode)
{
OnDiscoveredNodeIPAddress(addr);
}
}
break;
}
default:
break;
}
}
void PacketDataReporter::OnComplete()
{
if ((mDiscoveryType == DiscoveryType::kCommissionableNode || mDiscoveryType == DiscoveryType::kCommissionerNode) &&
mDiscoveredNodeData.IsValid())
{
mDelegate->OnNodeDiscoveryComplete(mDiscoveredNodeData);
}
else if (mDiscoveryType == DiscoveryType::kOperational && mHasIP && mHasNodePort)
{
mNodeData.LogNodeIdResolved();
mDelegate->OnNodeIdResolved(mNodeData);
}
}
class MinMdnsResolver : public Resolver, public MdnsPacketDelegate
{
public:
MinMdnsResolver() { GlobalMinimalMdnsServer::Instance().SetResponseDelegate(this); }
//// MdnsPacketDelegate implementation
void OnMdnsPacketData(const BytesRange & data, const chip::Inet::IPPacketInfo * info) override;
///// Resolver implementation
CHIP_ERROR StartResolver(chip::Inet::InetLayer * inetLayer, uint16_t port) override;
CHIP_ERROR SetResolverDelegate(ResolverDelegate * delegate) override;
CHIP_ERROR ResolveNodeId(const PeerId & peerId, Inet::IPAddressType type) override;
CHIP_ERROR FindCommissionableNodes(DiscoveryFilter filter = DiscoveryFilter()) override;
CHIP_ERROR FindCommissioners(DiscoveryFilter filter = DiscoveryFilter()) override;
private:
ResolverDelegate * mDelegate = nullptr;
DiscoveryType mDiscoveryType = DiscoveryType::kUnknown;
CHIP_ERROR SendQuery(mdns::Minimal::FullQName qname, mdns::Minimal::QType type);
CHIP_ERROR BrowseNodes(DiscoveryType type, DiscoveryFilter subtype);
template <typename... Args>
mdns::Minimal::FullQName CheckAndAllocateQName(Args &&... parts)
{
size_t requiredSize = mdns::Minimal::FlatAllocatedQName::RequiredStorageSize(parts...);
if (requiredSize > kMaxQnameSize)
{
return mdns::Minimal::FullQName();
}
return mdns::Minimal::FlatAllocatedQName::Build(qnameStorage, parts...);
}
static constexpr int kMaxQnameSize = 100;
char qnameStorage[kMaxQnameSize];
};
void MinMdnsResolver::OnMdnsPacketData(const BytesRange & data, const chip::Inet::IPPacketInfo * info)
{
if (mDelegate == nullptr)
{
return;
}
PacketDataReporter reporter(mDelegate, info->Interface, mDiscoveryType, data);
if (!ParsePacket(data, &reporter))
{
ChipLogError(Discovery, "Failed to parse received mDNS packet");
}
else
{
reporter.OnComplete();
}
}
CHIP_ERROR MinMdnsResolver::StartResolver(chip::Inet::InetLayer * inetLayer, uint16_t port)
{
/// Note: we do not double-check the port as we assume the APP will always use
/// the same inetLayer and port for mDNS.
if (GlobalMinimalMdnsServer::Server().IsListening())
{
return CHIP_NO_ERROR;
}
return GlobalMinimalMdnsServer::Instance().StartServer(inetLayer, port);
}
CHIP_ERROR MinMdnsResolver::SetResolverDelegate(ResolverDelegate * delegate)
{
mDelegate = delegate;
return CHIP_NO_ERROR;
}
CHIP_ERROR MinMdnsResolver::SendQuery(mdns::Minimal::FullQName qname, mdns::Minimal::QType type)
{
System::PacketBufferHandle buffer = System::PacketBufferHandle::New(kMdnsMaxPacketSize);
ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY);
QueryBuilder builder(std::move(buffer));
builder.Header().SetMessageId(0);
mdns::Minimal::Query query(qname);
query.SetType(type).SetClass(mdns::Minimal::QClass::IN);
// TODO(cecille): Not sure why unicast response isn't working - fix.
query.SetAnswerViaUnicast(false);
builder.AddQuery(query);
ReturnErrorCodeIf(!builder.Ok(), CHIP_ERROR_INTERNAL);
return GlobalMinimalMdnsServer::Server().BroadcastSend(builder.ReleasePacket(), kMdnsPort);
}
CHIP_ERROR MinMdnsResolver::FindCommissionableNodes(DiscoveryFilter filter)
{
return BrowseNodes(DiscoveryType::kCommissionableNode, filter);
}
CHIP_ERROR MinMdnsResolver::FindCommissioners(DiscoveryFilter filter)
{
return BrowseNodes(DiscoveryType::kCommissionerNode, filter);
}
// TODO(cecille): Extend filter and use this for Resolve
CHIP_ERROR MinMdnsResolver::BrowseNodes(DiscoveryType type, DiscoveryFilter filter)
{
mDiscoveryType = type;
mdns::Minimal::FullQName qname;
switch (type)
{
case DiscoveryType::kOperational:
qname = CheckAndAllocateQName(kOperationalServiceName, kOperationalProtocol, kLocalDomain);
break;
case DiscoveryType::kCommissionableNode:
if (filter.type == DiscoveryFilterType::kNone)
{
qname = CheckAndAllocateQName(kCommissionableServiceName, kCommissionProtocol, kLocalDomain);
}
else if (filter.type == DiscoveryFilterType::kInstanceName)
{
qname = CheckAndAllocateQName(filter.instanceName, kCommissionableServiceName, kCommissionProtocol, kLocalDomain);
}
else
{
char subtypeStr[kMaxSubtypeDescSize];
ReturnErrorOnFailure(MakeServiceSubtype(subtypeStr, sizeof(subtypeStr), filter));
qname = CheckAndAllocateQName(subtypeStr, kSubtypeServiceNamePart, kCommissionableServiceName, kCommissionProtocol,
kLocalDomain);
}
break;
case DiscoveryType::kCommissionerNode:
if (filter.type == DiscoveryFilterType::kNone)
{
qname = CheckAndAllocateQName(kCommissionerServiceName, kCommissionProtocol, kLocalDomain);
}
else
{
char subtypeStr[kMaxSubtypeDescSize];
ReturnErrorOnFailure(MakeServiceSubtype(subtypeStr, sizeof(subtypeStr), filter));
qname = CheckAndAllocateQName(subtypeStr, kSubtypeServiceNamePart, kCommissionerServiceName, kCommissionProtocol,
kLocalDomain);
}
break;
case DiscoveryType::kUnknown:
break;
}
if (!qname.nameCount)
{
return CHIP_ERROR_NO_MEMORY;
}
return SendQuery(qname, mdns::Minimal::QType::ANY);
}
CHIP_ERROR MinMdnsResolver::ResolveNodeId(const PeerId & peerId, Inet::IPAddressType type)
{
mDiscoveryType = DiscoveryType::kOperational;
System::PacketBufferHandle buffer = System::PacketBufferHandle::New(kMdnsMaxPacketSize);
ReturnErrorCodeIf(buffer.IsNull(), CHIP_ERROR_NO_MEMORY);
QueryBuilder builder(std::move(buffer));
builder.Header().SetMessageId(0);
{
char nameBuffer[64] = "";
// Node and fabricid are encoded in server names.
ReturnErrorOnFailure(MakeInstanceName(nameBuffer, sizeof(nameBuffer), peerId));
const char * instanceQName[] = { nameBuffer, kOperationalServiceName, kOperationalProtocol, kLocalDomain };
Query query(instanceQName);
query
.SetClass(QClass::IN) //
.SetType(QType::ANY) //
.SetAnswerViaUnicast(false) //
;
// NOTE: type above is NOT A or AAAA because the name searched for is
// a SRV record. The layout is:
// SRV -> hostname
// Hostname -> A
// Hostname -> AAAA
//
// Query is sent for ANY and expectation is to receive A/AAAA records
// in the additional section of the reply.
//
// Sending a A/AAAA query will return no results
// Sending a SRV query will return the srv only and an additional query
// would be needed to resolve the host name to an IP address
builder.AddQuery(query);
}
ReturnErrorCodeIf(!builder.Ok(), CHIP_ERROR_INTERNAL);
return GlobalMinimalMdnsServer::Server().BroadcastSend(builder.ReleasePacket(), kMdnsPort);
}
MinMdnsResolver gResolver;
} // namespace
Resolver & chip::Mdns::Resolver::Instance()
{
return gResolver;
}
} // namespace Mdns
} // namespace chip