1 /*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "NetlinkProtocol.h"
18
19 namespace android::nl::protocols {
20
NetlinkProtocol(int protocol,const std::string & name,const MessageDescriptorList && messageDescrs)21 NetlinkProtocol::NetlinkProtocol(int protocol, const std::string& name,
22 const MessageDescriptorList&& messageDescrs)
23 : mProtocol(protocol), mName(name), mMessageDescrs(toMap(messageDescrs, protocol)) {}
24
~NetlinkProtocol()25 NetlinkProtocol::~NetlinkProtocol() {}
26
getProtocol() const27 int NetlinkProtocol::getProtocol() const {
28 return mProtocol;
29 }
30
getName() const31 const std::string& NetlinkProtocol::getName() const {
32 return mName;
33 }
34
35 const std::optional<std::reference_wrapper<MessageDescriptor>>
getMessageDescriptor(nlmsgtype_t nlmsg_type)36 NetlinkProtocol::getMessageDescriptor(nlmsgtype_t nlmsg_type) {
37 if (mMessageDescrs.count(nlmsg_type) == 0) return std::nullopt;
38 return *mMessageDescrs.find(nlmsg_type)->second;
39 }
40
toMap(const NetlinkProtocol::MessageDescriptorList & descrs,int protocol)41 NetlinkProtocol::MessageDescriptorMap NetlinkProtocol::toMap(
42 const NetlinkProtocol::MessageDescriptorList& descrs, int protocol) {
43 MessageDescriptorMap map;
44 for (auto& descr : descrs) {
45 for (const auto& [mtype, mdet] : descr->getMessageDetailsMap()) {
46 map.emplace(mtype, descr);
47 }
48 }
49
50 const MessageDescriptorList baseDescriptors = {
51 std::make_shared<base::Empty>(),
52 std::make_shared<base::Error>(protocol),
53 };
54
55 for (const auto& descr : baseDescriptors) {
56 for (const auto& [mtype, mdet] : descr->getMessageDetailsMap()) {
57 map.emplace(mtype, descr);
58 }
59 }
60
61 return map;
62 }
63
64 } // namespace android::nl::protocols
65