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 #pragma once 18 19 #include <stdint.h> 20 #include <type_traits> 21 #include <vector> 22 23 #include <linux/netlink.h> 24 25 class NetlinkMessage { 26 public: 27 NetlinkMessage() = default; 28 NetlinkMessage(uint16_t type, uint32_t sequence); 29 NetlinkMessage(const char* data, size_t size); 30 31 template<typename T, 32 typename = std::enable_if_t<std::is_pod<T>::value>> getAttribute(int attributeId,T * value)33 bool getAttribute(int attributeId, T* value) const { 34 return getAttribute(attributeId, value, sizeof(T)); 35 } 36 37 uint16_t type() const; 38 uint32_t sequence() const; 39 header()40 nlmsghdr* header() { 41 return reinterpret_cast<nlmsghdr*>(mData.data()); 42 } header()43 const nlmsghdr* header() const { 44 return reinterpret_cast<const nlmsghdr*>(mData.data()); 45 } 46 47 template<typename T> payload()48 T* payload() { 49 return reinterpret_cast<T*>(NLMSG_DATA(header())); 50 } 51 template<typename T> payload()52 const T* payload() const { 53 return reinterpret_cast<T*>(NLMSG_DATA(header())); 54 } 55 data()56 const uint8_t* data() const { return mData.data(); } size()57 size_t size() const { return mData.size(); } 58 private: 59 NetlinkMessage(const NetlinkMessage&) = delete; 60 NetlinkMessage& operator=(const NetlinkMessage&) = delete; 61 62 bool getAttribute(int attributeId, void* data, size_t size) const; 63 bool findAttribute(int attributeId, 64 const void** value, 65 uint16_t* size) const; 66 67 std::vector<uint8_t> mData; 68 }; 69 70