-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Advertiser_ImplMinimalMdns.cpp
692 lines (583 loc) · 20.7 KB
/
Advertiser_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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*
*
* Copyright (c) 2020 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 "Advertiser.h"
#include <inttypes.h>
#include <stdio.h>
#include <mdns/minimal/ResponseSender.h>
#include <mdns/minimal/Server.h>
#include <mdns/minimal/core/FlatAllocatedQName.h>
#include <mdns/minimal/responders/IP.h>
#include <mdns/minimal/responders/Ptr.h>
#include <mdns/minimal/responders/QueryResponder.h>
#include <mdns/minimal/responders/Srv.h>
#include <mdns/minimal/responders/Txt.h>
#include <support/CHIPMem.h>
#include <support/RandUtils.h>
#include <support/ReturnMacros.h>
#include <support/StringBuilder.h>
namespace chip {
namespace Mdns {
namespace {
using namespace mdns::Minimal;
const char * ToString(QClass qClass)
{
switch (qClass)
{
case QClass::IN:
return "IN";
default:
return "???";
}
}
const char * ToString(QType qType)
{
switch (qType)
{
case QType::ANY:
return "ANY";
case QType::A:
return "A";
case QType::AAAA:
return "AAAA";
case QType::TXT:
return "TXT";
case QType::SRV:
return "SRV";
case QType::PTR:
return "PTR";
default:
return "???";
}
}
void LogQuery(const QueryData & data)
{
StringBuilder<128> logString;
logString.Add("QUERY ").Add(ToString(data.GetClass())).Add("/").Add(ToString(data.GetType())).Add(": ");
SerializedQNameIterator name = data.GetName();
while (name.Next())
{
logString.Add(name.Value()).Add(".");
}
ChipLogDetail(Discovery, "%s", logString.c_str());
}
/// Checks if the current interface is powered on
/// and not local loopback.
template <typename T>
bool IsCurrentInterfaceUsable(T & iterator)
{
if (!iterator.IsUp() || !iterator.SupportsMulticast())
{
return false; // not a usable interface
}
char name[chip::Inet::InterfaceIterator::kMaxIfNameLength];
if (iterator.GetInterfaceName(name, sizeof(name)) != CHIP_NO_ERROR)
{
ChipLogError(Discovery, "Failed to get interface name.");
return false;
}
// TODO: need a better way to ignore local loopback interfaces/addresses
// We do not want to listen on local loopback even though they are up and
// support multicast
//
// Some way to detect 'is local looback' that is smarter (e.g. at least
// strict string compare on linux instead of substring) would be better.
//
// This would reject likely valid interfaces like 'lollipop' or 'lostinspace'
if (strncmp(name, "lo", 2) == 0)
{
/// local loopback interface is not usable by MDNS
return false;
}
return true;
}
class AllInterfaces : public ListenIterator
{
private:
public:
AllInterfaces() { SkipToFirstValidInterface(); }
bool Next(chip::Inet::InterfaceId * id, chip::Inet::IPAddressType * type) override
{
if (!mIterator.HasCurrent())
{
return false;
}
#if INET_CONFIG_ENABLE_IPV4
if (mState == State::kIpV4)
{
*id = mIterator.GetInterfaceId();
*type = chip::Inet::kIPAddressType_IPv4;
mState = State::kIpV6;
return true;
}
#endif
*id = mIterator.GetInterfaceId();
*type = chip::Inet::kIPAddressType_IPv6;
#if INET_CONFIG_ENABLE_IPV4
mState = State::kIpV4;
#endif
for (mIterator.Next(); SkipCurrentInterface(); mIterator.Next())
{
}
return true;
}
private:
enum class State
{
kIpV4,
kIpV6,
};
#if INET_CONFIG_ENABLE_IPV4
State mState = State::kIpV4;
#else
State mState = State::kIpV6;
#endif
chip::Inet::InterfaceIterator mIterator;
void SkipToFirstValidInterface()
{
do
{
if (!SkipCurrentInterface())
{
break;
}
} while (mIterator.Next());
}
bool SkipCurrentInterface()
{
if (!mIterator.HasCurrent())
{
return false; // nothing to try.
}
return !IsCurrentInterfaceUsable(mIterator);
}
};
class AdvertiserMinMdns : public ServiceAdvertiser,
public ServerDelegate, // gets queries
public ParserDelegate // parses queries
{
public:
AdvertiserMinMdns() : mResponseSender(&mServer, &mQueryResponder)
{
mServer.SetDelegate(this);
for (size_t i = 0; i < kMaxAllocatedResponders; i++)
{
mAllocatedResponders[i] = nullptr;
}
for (size_t i = 0; i < kMaxAllocatedQNameData; i++)
{
mAllocatedQNameParts[i] = nullptr;
}
}
~AdvertiserMinMdns() { Clear(); }
// Service advertiser
CHIP_ERROR Start(chip::Inet::InetLayer * inetLayer, uint16_t port) override;
CHIP_ERROR Advertise(const OperationalAdvertisingParameters & params) override;
CHIP_ERROR Advertise(const CommissionAdvertisingParameters & params) override;
// ServerDelegate
void OnQuery(const BytesRange & data, const chip::Inet::IPPacketInfo * info) override;
void OnResponse(const BytesRange & data, const chip::Inet::IPPacketInfo * info) override {}
// ParserDelegate
void OnHeader(ConstHeaderRef & header) override { mMessageId = header.GetMessageId(); }
void OnResource(ResourceType type, const ResourceData & data) override {}
void OnQuery(const QueryData & data) override;
private:
/// Sets the query responder to a blank state and frees up any
/// allocated memory.
void Clear();
/// Advertise available records configured within the server
///
/// Usable as boot-time advertisement of available SRV records.
void AdvertiseRecords();
/// Determine if advertisement on the specified interface/address is ok given the
/// interfaces on which the mDNS server is listening
bool ShouldAdvertiseOn(const chip::Inet::InterfaceId id, const chip::Inet::IPAddress & addr);
QueryResponderSettings AddAllocatedResponder(Responder * responder)
{
if (responder == nullptr)
{
ChipLogError(Discovery, "Responder memory allocation failed");
return QueryResponderSettings(); // failed
}
for (size_t i = 0; i < kMaxAllocatedResponders; i++)
{
if (mAllocatedResponders[i] != nullptr)
{
continue;
}
mAllocatedResponders[i] = responder;
return mQueryResponder.AddResponder(mAllocatedResponders[i]);
}
Platform::Delete(responder);
ChipLogError(Discovery, "Failed to find free slot for adding a responder");
return QueryResponderSettings();
}
/// Appends another responder to the internal replies.
template <typename ResponderType, typename... Args>
QueryResponderSettings AddResponder(Args &&... args)
{
return AddAllocatedResponder(chip::Platform::New<ResponderType>(std::forward<Args>(args)...));
}
template <typename... Args>
FullQName AllocateQName(Args &&... names)
{
for (size_t i = 0; i < kMaxAllocatedQNameData; i++)
{
if (mAllocatedQNameParts[i] != nullptr)
{
continue;
}
mAllocatedQNameParts[i] =
chip::Platform::MemoryAlloc(FlatAllocatedQName::RequiredStorageSize(std::forward<Args>(names)...));
if (mAllocatedQNameParts[i] == nullptr)
{
ChipLogError(Discovery, "QName memory allocation failed");
return FullQName();
}
return FlatAllocatedQName::Build(mAllocatedQNameParts[i], std::forward<Args>(names)...);
}
ChipLogError(Discovery, "Failed to find free slot for adding a qname");
return FullQName();
}
FullQName GetCommisioningTextEntries(const CommissionAdvertisingParameters & params);
static constexpr size_t kMaxEndPoints = 10;
static constexpr size_t kMaxRecords = 16;
static constexpr size_t kMaxAllocatedResponders = 16;
static constexpr size_t kMaxAllocatedQNameData = 8;
Server<kMaxEndPoints> mServer;
QueryResponder<kMaxRecords> mQueryResponder;
ResponseSender mResponseSender;
// current request handling
const chip::Inet::IPPacketInfo * mCurrentSource = nullptr;
uint32_t mMessageId = 0;
// dynamically allocated items
Responder * mAllocatedResponders[kMaxAllocatedResponders];
void * mAllocatedQNameParts[kMaxAllocatedQNameData];
const char * mEmptyTextEntries[1] = {
"=",
};
};
void AdvertiserMinMdns::OnQuery(const BytesRange & data, const chip::Inet::IPPacketInfo * info)
{
ChipLogDetail(Discovery, "MinMdns received a query.");
mCurrentSource = info;
if (!ParsePacket(data, this))
{
ChipLogError(Discovery, "Failed to parse mDNS query");
}
mCurrentSource = nullptr;
}
void AdvertiserMinMdns::OnQuery(const QueryData & data)
{
if (mCurrentSource == nullptr)
{
ChipLogError(Discovery, "INTERNAL CONSISTENCY ERROR: missing query source");
return;
}
LogQuery(data);
CHIP_ERROR err = mResponseSender.Respond(mMessageId, data, mCurrentSource);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Discovery, "Failed to reply to query: %s", ErrorStr(err));
}
}
CHIP_ERROR AdvertiserMinMdns::Start(chip::Inet::InetLayer * inetLayer, uint16_t port)
{
mServer.Shutdown();
AllInterfaces allInterfaces;
ReturnErrorOnFailure(mServer.Listen(inetLayer, &allInterfaces, port));
ChipLogProgress(Discovery, "CHIP minimal mDNS started advertising.");
AdvertiseRecords();
return CHIP_NO_ERROR;
}
void AdvertiserMinMdns::Clear()
{
// Init clears all responders, so that data can be freed
mQueryResponder.Init();
// Free all allocated data
for (size_t i = 0; i < kMaxAllocatedResponders; i++)
{
if (mAllocatedResponders[i] != nullptr)
{
chip::Platform::Delete(mAllocatedResponders[i]);
mAllocatedResponders[i] = nullptr;
}
}
for (size_t i = 0; i < kMaxAllocatedQNameData; i++)
{
if (mAllocatedQNameParts[i] != nullptr)
{
chip::Platform::MemoryFree(mAllocatedQNameParts[i]);
mAllocatedQNameParts[i] = nullptr;
}
}
}
CHIP_ERROR AdvertiserMinMdns::Advertise(const OperationalAdvertisingParameters & params)
{
Clear();
char uniqueName[64] = "";
/// need to set server name
size_t len = snprintf(uniqueName, sizeof(uniqueName), "%" PRIX64 "-%" PRIX64, params.GetFabricId(), params.GetNodeId());
if (len >= sizeof(uniqueName))
{
ChipLogError(Discovery, "Failed to allocate QNames.");
return CHIP_ERROR_NO_MEMORY;
}
FullQName operationalServiceName = AllocateQName("_chip", "_tcp", "local");
FullQName operationalServerName = AllocateQName(uniqueName, "_chip", "_tcp", "local");
FullQName serverName = AllocateQName(uniqueName, "local");
if ((operationalServiceName.nameCount == 0) || (operationalServerName.nameCount == 0) || (serverName.nameCount == 0))
{
ChipLogError(Discovery, "Failed to allocate QNames.");
return CHIP_ERROR_NO_MEMORY;
}
if (!AddResponder<PtrResponder>(operationalServiceName, operationalServerName)
.SetReportAdditional(operationalServerName)
.SetReportInServiceListing(true)
.IsValid())
{
ChipLogError(Discovery, "Failed to add service PTR record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
if (!AddResponder<SrvResponder>(SrvResourceRecord(operationalServerName, serverName, params.GetPort()))
.SetReportAdditional(serverName)
.IsValid())
{
ChipLogError(Discovery, "Failed to add SRV record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
if (!AddResponder<TxtResponder>(TxtResourceRecord(operationalServerName, mEmptyTextEntries))
.SetReportAdditional(serverName)
.IsValid())
{
ChipLogError(Discovery, "Failed to add TXT record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
if (!AddResponder<IPv6Responder>(serverName).IsValid())
{
ChipLogError(Discovery, "Failed to add IPv6 mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
if (params.IsIPv4Enabled())
{
if (!AddResponder<IPv4Responder>(serverName).IsValid())
{
ChipLogError(Discovery, "Failed to add IPv4 mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
}
ChipLogProgress(Discovery, "CHIP minimal mDNS configured as 'Operational device'.");
return CHIP_NO_ERROR;
}
CHIP_ERROR AdvertiserMinMdns::Advertise(const CommissionAdvertisingParameters & params)
{
Clear();
// TODO: need to detect colisions here
char nameBuffer[64] = "";
size_t len = snprintf(nameBuffer, sizeof(nameBuffer), "%016" PRIX64, GetRandU64());
if (len >= sizeof(nameBuffer))
{
return CHIP_ERROR_NO_MEMORY;
}
const char * serviceType = params.GetCommissionAdvertiseMode() == CommssionAdvertiseMode::kCommissioning ? "_chipc" : "_chipd";
FullQName operationalServiceName = AllocateQName(serviceType, "_udp", "local");
FullQName operationalServerName = AllocateQName(nameBuffer, serviceType, "_udp", "local");
FullQName serverName = AllocateQName(nameBuffer, "local");
if ((operationalServiceName.nameCount == 0) || (operationalServerName.nameCount == 0) || (serverName.nameCount == 0))
{
ChipLogError(Discovery, "Failed to allocate QNames.");
return CHIP_ERROR_NO_MEMORY;
}
if (!AddResponder<PtrResponder>(operationalServiceName, operationalServerName)
.SetReportAdditional(operationalServerName)
.SetReportInServiceListing(true)
.IsValid())
{
ChipLogError(Discovery, "Failed to add service PTR record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
if (!AddResponder<SrvResponder>(SrvResourceRecord(operationalServerName, serverName, params.GetPort()))
.SetReportAdditional(serverName)
.IsValid())
{
ChipLogError(Discovery, "Failed to add SRV record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
if (!AddResponder<IPv6Responder>(serverName).IsValid())
{
ChipLogError(Discovery, "Failed to add IPv6 mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
if (params.IsIPv4Enabled())
{
if (!AddResponder<IPv4Responder>(serverName).IsValid())
{
ChipLogError(Discovery, "Failed to add IPv4 mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
}
{
sprintf(nameBuffer, "S%03d", params.GetShortDiscriminator());
FullQName shortServiceName = AllocateQName(nameBuffer, "_sub", serviceType, "_udp", "local");
ReturnErrorCodeIf(shortServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY);
if (!AddResponder<PtrResponder>(shortServiceName, operationalServerName)
.SetReportAdditional(operationalServerName)
.SetReportInServiceListing(true)
.IsValid())
{
ChipLogError(Discovery, "Failed to add short discriminator PTR record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
}
{
sprintf(nameBuffer, "L%04d", params.GetLongDiscriminator());
FullQName longServiceName = AllocateQName(nameBuffer, "_sub", serviceType, "_udp", "local");
ReturnErrorCodeIf(longServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY);
if (!AddResponder<PtrResponder>(longServiceName, operationalServerName)
.SetReportAdditional(operationalServerName)
.SetReportInServiceListing(true)
.IsValid())
{
ChipLogError(Discovery, "Failed to add long discriminator PTR record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
}
if (params.GetVendorId().HasValue())
{
sprintf(nameBuffer, "V%d", params.GetVendorId().Value());
FullQName vendorServiceName = AllocateQName(nameBuffer, "_sub", serviceType, "_udp", "local");
ReturnErrorCodeIf(vendorServiceName.nameCount == 0, CHIP_ERROR_NO_MEMORY);
if (!AddResponder<PtrResponder>(vendorServiceName, operationalServerName)
.SetReportAdditional(operationalServerName)
.SetReportInServiceListing(true)
.IsValid())
{
ChipLogError(Discovery, "Failed to add vendor discriminator PTR record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
}
if (!AddResponder<TxtResponder>(TxtResourceRecord(operationalServerName, GetCommisioningTextEntries(params)))
.SetReportAdditional(serverName)
.IsValid())
{
ChipLogError(Discovery, "Failed to add TXT record mDNS responder");
return CHIP_ERROR_NO_MEMORY;
}
ChipLogProgress(Discovery, "CHIP minimal mDNS configured as 'Commisioning device'.");
return CHIP_NO_ERROR;
}
FullQName AdvertiserMinMdns::GetCommisioningTextEntries(const CommissionAdvertisingParameters & params)
{
// a discriminator always exists
char txtDiscriminator[32];
sprintf(txtDiscriminator, "D=%d", params.GetLongDiscriminator());
if (!params.GetVendorId().HasValue())
{
return AllocateQName(txtDiscriminator);
}
// Need to also set a vid/pid string
char txtVidPid[64];
if (params.GetProductId().HasValue())
{
sprintf(txtVidPid, "V=%d+%d", params.GetVendorId().Value(), params.GetProductId().Value());
}
else
{
sprintf(txtVidPid, "V=%d", params.GetVendorId().Value());
}
char txtPairingInstrHint[128];
if (params.GetPairingInstr().HasValue() && params.GetPairingHint().HasValue())
{
sprintf(txtPairingInstrHint, "P=%s+%d", params.GetPairingInstr().Value(), params.GetPairingHint().Value());
return AllocateQName(txtDiscriminator, txtVidPid, txtPairingInstrHint);
}
else
{
return AllocateQName(txtDiscriminator, txtVidPid);
}
}
bool AdvertiserMinMdns::ShouldAdvertiseOn(const chip::Inet::InterfaceId id, const chip::Inet::IPAddress & addr)
{
for (unsigned i = 0; i < mServer.GetEndpointCount(); i++)
{
const ServerBase::EndpointInfo & info = mServer.GetEndpoints()[i];
if (info.udp == nullptr)
{
continue;
}
if (info.interfaceId != id)
{
continue;
}
if (info.addressType != addr.Type())
{
continue;
}
return true;
}
return false;
}
void AdvertiserMinMdns::AdvertiseRecords()
{
chip::Inet::InterfaceAddressIterator interfaceAddress;
if (!interfaceAddress.Next())
{
return;
}
for (; interfaceAddress.HasCurrent(); interfaceAddress.Next())
{
if (!IsCurrentInterfaceUsable(interfaceAddress))
{
continue;
}
if (!ShouldAdvertiseOn(interfaceAddress.GetInterfaceId(), interfaceAddress.GetAddress()))
{
continue;
}
chip::Inet::IPPacketInfo packetInfo;
packetInfo.Clear();
packetInfo.SrcAddress = interfaceAddress.GetAddress();
if (interfaceAddress.GetAddress().IsIPv4())
{
BroadcastIpAddresses::GetIpv4Into(packetInfo.DestAddress);
}
else
{
BroadcastIpAddresses::GetIpv6Into(packetInfo.DestAddress);
}
packetInfo.SrcPort = kMdnsPort;
packetInfo.DestPort = kMdnsPort;
packetInfo.Interface = interfaceAddress.GetInterfaceId();
QueryData queryData(QType::PTR, QClass::IN, false /* unicast */);
queryData.SetIsBootAdvertising(true);
mQueryResponder.ClearBroadcastThrottle();
CHIP_ERROR err = mResponseSender.Respond(0, queryData, &packetInfo);
if (err != CHIP_NO_ERROR)
{
ChipLogError(Discovery, "Failed to advertise records: %s", ErrorStr(err));
}
}
// Once all automatic broadcasts are done, allow immediate replies once.
mQueryResponder.ClearBroadcastThrottle();
}
AdvertiserMinMdns gAdvertiser;
} // namespace
ServiceAdvertiser & ServiceAdvertiser::Instance()
{
return gAdvertiser;
}
} // namespace Mdns
} // namespace chip