Line data Source code
1 : /*
2 : *
3 : * Copyright (c) 2020 Project CHIP Authors
4 : *
5 : * Licensed under the Apache License, Version 2.0 (the "License");
6 : * you may not use this file except in compliance with the License.
7 : * You may obtain a copy of the License at
8 : *
9 : * http://www.apache.org/licenses/LICENSE-2.0
10 : *
11 : * Unless required by applicable law or agreed to in writing, software
12 : * distributed under the License is distributed on an "AS IS" BASIS,
13 : * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 : * See the License for the specific language governing permissions and
15 : * limitations under the License.
16 : */
17 :
18 : #pragma once
19 :
20 : #include <system/SystemPacketBuffer.h>
21 :
22 : #include <lib/dnssd/minimal_mdns/Query.h>
23 : #include <lib/dnssd/minimal_mdns/core/DnsHeader.h>
24 :
25 : namespace mdns {
26 : namespace Minimal {
27 :
28 : class QueryBuilder
29 : {
30 : public:
31 : QueryBuilder() : mHeader(nullptr) {}
32 0 : QueryBuilder(chip::System::PacketBufferHandle && packet) : mHeader(nullptr) { Reset(std::move(packet)); }
33 :
34 0 : QueryBuilder & Reset(chip::System::PacketBufferHandle && packet)
35 : {
36 0 : mPacket = std::move(packet);
37 0 : mHeader = HeaderRef(mPacket->Start());
38 :
39 0 : if (mPacket->AvailableDataLength() >= HeaderRef::kSizeBytes)
40 : {
41 0 : mPacket->SetDataLength(HeaderRef::kSizeBytes);
42 0 : mHeader.Clear();
43 : }
44 : else
45 : {
46 0 : mQueryBuildOk = false;
47 : }
48 :
49 0 : mHeader.SetFlags(mHeader.GetFlags().SetQuery());
50 0 : return *this;
51 : }
52 :
53 : CHECK_RETURN_VALUE
54 0 : chip::System::PacketBufferHandle && ReleasePacket()
55 : {
56 0 : mHeader = HeaderRef(nullptr);
57 0 : mQueryBuildOk = false;
58 0 : return std::move(mPacket);
59 : }
60 :
61 0 : HeaderRef & Header() { return mHeader; }
62 :
63 0 : QueryBuilder & AddQuery(const Query & query)
64 : {
65 0 : if (!mQueryBuildOk)
66 : {
67 0 : return *this;
68 : }
69 :
70 0 : chip::Encoding::BigEndian::BufferWriter out(mPacket->Start() + mPacket->DataLength(), mPacket->AvailableDataLength());
71 0 : RecordWriter writer(&out);
72 :
73 0 : if (!query.Append(mHeader, writer))
74 : {
75 0 : mQueryBuildOk = false;
76 : }
77 : else
78 : {
79 0 : mPacket->SetDataLength(static_cast<uint16_t>(mPacket->DataLength() + out.Needed()));
80 : }
81 0 : return *this;
82 : }
83 :
84 0 : bool Ok() const { return mQueryBuildOk; }
85 :
86 : private:
87 : chip::System::PacketBufferHandle mPacket;
88 : HeaderRef mHeader;
89 : bool mQueryBuildOk = true;
90 : };
91 :
92 : } // namespace Minimal
93 : } // namespace mdns
|