xref: /aosp_15_r20/hardware/interfaces/automotive/can/1.0/default/libnl++/protocols/generic/FamilyTracker.cpp (revision 4d7e907c777eeecc4c5bd7cf640a754fac206ff7)
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 <libnl++/generic/FamilyTracker.h>
18 
19 #include <android-base/logging.h>
20 
21 // should be in linux/genetlink.h
22 #define GENL_START_ALLOC (NLMSG_MIN_TYPE + 3)
23 
24 namespace android::nl::generic {
25 
track(const Buffer<nlmsghdr> & buffer)26 bool FamilyTracker::track(const Buffer<nlmsghdr>& buffer) {
27     const auto msgMaybe = nl::Message<genlmsghdr>::parse(buffer, {GENL_ID_CTRL});
28     if (!msgMaybe.has_value()) return false;
29 
30     const auto msg = *msgMaybe;
31     if (msg->cmd != CTRL_CMD_NEWFAMILY) return true;
32 
33     const auto familyName = msg.attributes.get<std::string>(CTRL_ATTR_FAMILY_NAME);
34     const auto familyId = msg.attributes.get<uint16_t>(CTRL_ATTR_FAMILY_ID);
35 
36     // TODO(224845900): NETLINK_GENERIC == 16, and (erroneously?) sets off this warning
37     if (familyId < GENL_START_ALLOC) {
38         LOG(WARNING) << "Invalid family ID: " << familyId;
39         return true;
40     }
41 
42     if (familyName == "nl80211") mNl80211FamilyId = familyId;
43 
44     return true;
45 }
46 
parseNl80211(Buffer<nlmsghdr> msg)47 std::optional<Message<genlmsghdr>> FamilyTracker::parseNl80211(Buffer<nlmsghdr> msg) {
48     if (track(msg)) return std::nullopt;
49     if (!mNl80211FamilyId.has_value()) return std::nullopt;
50 
51     return nl::Message<genlmsghdr>::parse(msg, {*mNl80211FamilyId});
52 }
53 
54 }  // namespace android::nl::generic
55