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 <ios> 18#include <linux/netlink.h> 19 20#include "netdutils/Math.h" 21#include "netdutils/Netlink.h" 22 23namespace android { 24namespace netdutils { 25 26void forEachNetlinkMessage(const Slice buf, 27 const std::function<void(const nlmsghdr&, const Slice)>& onMsg) { 28 Slice tail = buf; 29 while (tail.size() >= sizeof(nlmsghdr)) { 30 nlmsghdr hdr = {}; 31 extract(tail, hdr); 32 const auto len = std::max<size_t>(hdr.nlmsg_len, sizeof(hdr)); 33 onMsg(hdr, drop(take(tail, len), sizeof(hdr))); 34 tail = drop(tail, align(len, 2)); 35 } 36} 37 38void forEachNetlinkAttribute(const Slice buf, 39 const std::function<void(const nlattr&, const Slice)>& onAttr) { 40 Slice tail = buf; 41 while (tail.size() >= sizeof(nlattr)) { 42 nlattr hdr = {}; 43 extract(tail, hdr); 44 const auto len = std::max<size_t>(hdr.nla_len, sizeof(hdr)); 45 onAttr(hdr, drop(take(tail, len), sizeof(hdr))); 46 tail = drop(tail, align(len, 2)); 47 } 48} 49 50} // namespace netdutils 51} // namespace android 52 53bool operator==(const sockaddr_nl& lhs, const sockaddr_nl& rhs) { 54 return (lhs.nl_family == rhs.nl_family) && (lhs.nl_pid == rhs.nl_pid) && 55 (lhs.nl_groups == rhs.nl_groups); 56} 57 58bool operator!=(const sockaddr_nl& lhs, const sockaddr_nl& rhs) { 59 return !(lhs == rhs); 60} 61 62std::ostream& operator<<(std::ostream& os, const nlmsghdr& hdr) { 63 return os << std::hex << "nlmsghdr[" 64 << "len: 0x" << hdr.nlmsg_len << ", type: 0x" << hdr.nlmsg_type << ", flags: 0x" 65 << hdr.nlmsg_flags << ", seq: 0x" << hdr.nlmsg_seq << ", pid: 0x" << hdr.nlmsg_pid 66 << "]" << std::dec; 67} 68 69std::ostream& operator<<(std::ostream& os, const nlattr& attr) { 70 return os << std::hex << "nlattr[" 71 << "len: 0x" << attr.nla_len << ", type: 0x" << attr.nla_type << "]" << std::dec; 72} 73 74std::ostream& operator<<(std::ostream& os, const sockaddr_nl& addr) { 75 return os << std::hex << "sockaddr_nl[" 76 << "family: " << addr.nl_family << ", pid: " << addr.nl_pid 77 << ", groups: " << addr.nl_groups << "]" << std::dec; 78} 79