1 #include "system_queries.hpp"
2
3 #include "netlink.hpp"
4
5 #include <linux/ethtool.h>
6 #include <linux/rtnetlink.h>
7 #include <linux/sockios.h>
8 #include <net/if.h>
9
10 #include <phosphor-logging/lg2.hpp>
11 #include <stdplus/fd/create.hpp>
12 #include <stdplus/hash/tuple.hpp>
13 #include <stdplus/util/cexec.hpp>
14
15 #include <algorithm>
16 #include <format>
17 #include <optional>
18 #include <stdexcept>
19 #include <string_view>
20 #include <unordered_set>
21
22 namespace phosphor::network::system
23 {
24
25 using std::literals::string_view_literals::operator""sv;
26
getIFSock()27 static stdplus::Fd& getIFSock()
28 {
29 using namespace stdplus::fd;
30 static auto fd =
31 socket(SocketDomain::INet, SocketType::Datagram, SocketProto::IP);
32 return fd;
33 }
34
makeIFReq(std::string_view ifname)35 static ifreq makeIFReq(std::string_view ifname)
36 {
37 ifreq ifr = {};
38 const auto copied = std::min<std::size_t>(ifname.size(), IFNAMSIZ - 1);
39 std::copy_n(ifname.begin(), copied, ifr.ifr_name);
40 return ifr;
41 }
42
executeIFReq(std::string_view ifname,unsigned long cmd,void * data=nullptr)43 static ifreq executeIFReq(std::string_view ifname, unsigned long cmd,
44 void* data = nullptr)
45 {
46 ifreq ifr = makeIFReq(ifname);
47 ifr.ifr_data = reinterpret_cast<char*>(data);
48 getIFSock().ioctl(cmd, &ifr);
49 return ifr;
50 }
51
optionalIFReq(stdplus::zstring_view ifname,unsigned long long cmd,std::string_view cmdname,auto && complete,void * data=nullptr)52 inline auto optionalIFReq(stdplus::zstring_view ifname, unsigned long long cmd,
53 std::string_view cmdname, auto&& complete,
54 void* data = nullptr)
55 {
56 ifreq ifr;
57 std::optional<decltype(complete(ifr))> ret;
58 auto ukey = std::make_tuple(std::string(ifname), cmd);
59 static std::unordered_set<std::tuple<std::string, unsigned long long>>
60 unsupported;
61 try
62 {
63 ifr = executeIFReq(ifname, cmd, data);
64 }
65 catch (const std::system_error& e)
66 {
67 if (e.code() == std::errc::operation_not_supported)
68 {
69 if (unsupported.find(ukey) == unsupported.end())
70 {
71 unsupported.emplace(std::move(ukey));
72 lg2::info("{NET_IFREQ} not supported on {NET_INTF}",
73 "NET_IFREQ", cmdname, "NET_INTF", ifname);
74 }
75 return ret;
76 }
77 throw;
78 }
79 unsupported.erase(ukey);
80 ret.emplace(complete(ifr));
81 return ret;
82 }
83
getEthInfo(stdplus::zstring_view ifname)84 EthInfo getEthInfo(stdplus::zstring_view ifname)
85 {
86 ethtool_cmd edata = {};
87 edata.cmd = ETHTOOL_GSET;
88 return optionalIFReq(
89 ifname, SIOCETHTOOL, "ETHTOOL"sv,
90 [&](const ifreq&) {
91 return EthInfo{.autoneg = edata.autoneg != 0,
92 .speed = edata.speed,
93 .fullDuplex = (edata.duplex == DUPLEX_FULL)};
94 },
95 &edata)
96 .value_or(EthInfo{});
97 }
98
setMTU(std::string_view ifname,unsigned mtu)99 void setMTU(std::string_view ifname, unsigned mtu)
100 {
101 auto ifr = makeIFReq(ifname);
102 ifr.ifr_mtu = mtu;
103 getIFSock().ioctl(SIOCSIFMTU, &ifr);
104 }
105
setNICUp(std::string_view ifname,bool up)106 void setNICUp(std::string_view ifname, bool up)
107 {
108 ifreq ifr = executeIFReq(ifname, SIOCGIFFLAGS);
109 ifr.ifr_flags &= ~IFF_UP;
110 ifr.ifr_flags |= up ? IFF_UP : 0;
111 lg2::info("Setting NIC {UPDOWN} on {NET_INTF}", "UPDOWN",
112 up ? "up"sv : "down"sv, "NET_INTF", ifname);
113 getIFSock().ioctl(SIOCSIFFLAGS, &ifr);
114 }
115
deleteIntf(unsigned idx)116 void deleteIntf(unsigned idx)
117 {
118 if (idx == 0)
119 {
120 return;
121 }
122 ifinfomsg msg = {};
123 msg.ifi_family = AF_UNSPEC;
124 msg.ifi_index = idx;
125 netlink::performRequest(
126 NETLINK_ROUTE, RTM_DELLINK, NLM_F_REPLACE, msg,
127 [&](const nlmsghdr& hdr, std::string_view data) {
128 int err = 0;
129 if (hdr.nlmsg_type == NLMSG_ERROR)
130 {
131 err = netlink::extractRtData<nlmsgerr>(data).error;
132 }
133 throw std::runtime_error(
134 std::format("Failed to delete `{}`: {}", idx, strerror(err)));
135 });
136 }
137
deleteLinkLocalIPv4ViaNetlink(unsigned ifidx,const stdplus::SubnetAny & ip)138 bool deleteLinkLocalIPv4ViaNetlink(unsigned ifidx, const stdplus::SubnetAny& ip)
139 {
140 bool success = false;
141
142 std::visit(
143 [&](const auto& wrappedAddr) {
144 using T = std::decay_t<decltype(wrappedAddr)>;
145 if constexpr (std::is_same_v<T, stdplus::In4Addr>)
146 {
147 in_addr addr = static_cast<in_addr>(wrappedAddr);
148
149 if ((ntohl(addr.s_addr) & 0xFFFF0000) != 0xA9FE0000)
150 return;
151
152 int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
153 if (sock < 0)
154 {
155 lg2::error("Failed to open the NETLINK_ROUTE socket");
156 return;
157 }
158
159 sockaddr_nl nladdr{};
160 memset(&nladdr, 0, sizeof(nladdr));
161 nladdr.nl_family = AF_NETLINK;
162 nladdr.nl_pid = 0;
163 nladdr.nl_groups = 0;
164
165 if (bind(sock, reinterpret_cast<sockaddr*>(&nladdr),
166 sizeof(nladdr)) < 0)
167 {
168 lg2::error("Failed to bind the NETLINK_ROUTE socket");
169 close(sock);
170 return;
171 }
172
173 struct
174 {
175 nlmsghdr nlh;
176 ifaddrmsg ifa;
177 char buf[256];
178 } req{};
179
180 req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(ifaddrmsg));
181 req.nlh.nlmsg_type = RTM_DELADDR;
182 req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
183 req.ifa.ifa_family = AF_INET;
184 req.ifa.ifa_index = ifidx;
185 req.ifa.ifa_prefixlen = ip.getPfx();
186
187 rtattr* rta = reinterpret_cast<rtattr*>(req.buf);
188 rta->rta_type = IFA_LOCAL;
189 rta->rta_len = RTA_LENGTH(sizeof(in_addr));
190 std::memcpy(RTA_DATA(rta), &addr, sizeof(in_addr));
191
192 req.nlh.nlmsg_len += rta->rta_len;
193
194 const ssize_t sent = send(sock, &req, req.nlh.nlmsg_len, 0);
195 if (sent != static_cast<ssize_t>(req.nlh.nlmsg_len))
196 {
197 lg2::error(
198 "Failed to send netlink message for RTM_DELADDR");
199 close(sock);
200 return;
201 }
202
203 std::array<char, 4096> resp;
204 ssize_t len = recv(sock, resp.data(), resp.size(), 0);
205 close(sock);
206
207 if (len >= NLMSG_LENGTH(0))
208 {
209 const nlmsghdr* hdr =
210 reinterpret_cast<nlmsghdr*>(resp.data());
211 if (hdr->nlmsg_type == NLMSG_ERROR)
212 {
213 const nlmsgerr* err =
214 reinterpret_cast<nlmsgerr*>(NLMSG_DATA(hdr));
215 if (err->error != 0)
216 {
217 std::ostringstream oss;
218 oss << "Failed to delete link-local IP on ifidx "
219 << ifidx << ": " << strerror(-err->error);
220 success = false;
221 return;
222 }
223 }
224 }
225 success = true;
226 }
227 },
228 ip.getAddr());
229
230 return success;
231 }
232
233 } // namespace phosphor::network::system
234