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