1 /*
2 * Copyright (C) 2017 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 "netlinkmessage.h"
18
19 #include <linux/netlink.h>
20 #include <linux/rtnetlink.h>
21 #include <netlink/msg.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24
getSpaceForMessageType(uint16_t type)25 size_t getSpaceForMessageType(uint16_t type) {
26 switch (type) {
27 case RTM_NEWLINK:
28 case RTM_GETLINK:
29 return NLMSG_SPACE(sizeof(ifinfomsg));
30 default:
31 return 0;
32 }
33 }
34
NetlinkMessage(uint16_t type,uint32_t sequence)35 NetlinkMessage::NetlinkMessage(uint16_t type,
36 uint32_t sequence)
37 : mData(getSpaceForMessageType(type), 0) {
38
39 auto header = reinterpret_cast<nlmsghdr*>(mData.data());
40 header->nlmsg_len = mData.size();
41 header->nlmsg_flags = NLM_F_REQUEST;
42 header->nlmsg_type = type;
43 header->nlmsg_seq = sequence;
44 header->nlmsg_pid = getpid();
45 }
46
NetlinkMessage(const char * data,size_t size)47 NetlinkMessage::NetlinkMessage(const char* data, size_t size)
48 : mData(data, data + size) {
49 }
50
getAttribute(int attributeId,void * const data,const size_t size) const51 bool NetlinkMessage::getAttribute(int attributeId, void* const data, const size_t size) const {
52 const void* value = nullptr;
53 const auto attr = nlmsg_find_attr((struct nlmsghdr*)mData.data(), sizeof(ifinfomsg), attributeId);
54 if (!attr) {
55 return false;
56 }
57 value = (const uint8_t*) attr + NLA_HDRLEN;
58 const size_t attr_len = attr->nla_len - NLA_HDRLEN;
59 if (attr_len > size) {
60 return false;
61 }
62 memcpy(data, value, attr_len);
63 return true;
64 }
65
type() const66 uint16_t NetlinkMessage::type() const {
67 auto header = reinterpret_cast<const nlmsghdr*>(mData.data());
68 return header->nlmsg_type;
69 }
70
sequence() const71 uint32_t NetlinkMessage::sequence() const {
72 auto header = reinterpret_cast<const nlmsghdr*>(mData.data());
73 return header->nlmsg_seq;
74 }
75