1 /*
2 * Copyright 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 "interface.h"
18
19 #include "netlink.h"
20
21 #include <errno.h>
22 #include <linux/if.h>
23 #include <linux/if_ether.h>
24 #include <linux/route.h>
25 #include <linux/rtnetlink.h>
26 #include <string.h>
27 #include <unistd.h>
28
broadcastFromNetmask(in_addr_t address,in_addr_t netmask)29 in_addr_t broadcastFromNetmask(in_addr_t address, in_addr_t netmask) {
30 // The broadcast address is the address with the bits excluded in the
31 // netmask set to 1. For example if address = 10.0.2.15 and netmask is
32 // 255.255.255.0 then the broadcast is 10.0.2.255. If instead netmask was
33 // 255.0.0.0.0 then the broadcast would be 10.255.255.255
34 //
35 // Simply set all the lower bits to 1 and that should do it.
36 return address | (~netmask);
37 }
38
Interface()39 Interface::Interface() : mSocketFd(-1) {}
40
~Interface()41 Interface::~Interface() {
42 if (mSocketFd != -1) {
43 close(mSocketFd);
44 mSocketFd = -1;
45 }
46 }
47
init(const char * interfaceName)48 Result Interface::init(const char* interfaceName) {
49 mInterfaceName = interfaceName;
50
51 if (mSocketFd != -1) {
52 return Result::error("Interface initialized more than once");
53 }
54
55 mSocketFd = ::socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
56 if (mSocketFd == -1) {
57 return Result::error("Failed to create interface socket for '%s': %s", interfaceName,
58 strerror(errno));
59 }
60
61 Result res = populateIndex();
62 if (!res) {
63 return res;
64 }
65
66 res = populateMacAddress();
67 if (!res) {
68 return res;
69 }
70
71 res = bringUp();
72 if (!res) {
73 return res;
74 }
75
76 res = setAddress(0, 0);
77 if (!res) {
78 return res;
79 }
80
81 return Result::success();
82 }
83
bringUp()84 Result Interface::bringUp() {
85 return setInterfaceUp(true);
86 }
87
bringDown()88 Result Interface::bringDown() {
89 return setInterfaceUp(false);
90 }
91
setMtu(uint16_t mtu)92 Result Interface::setMtu(uint16_t mtu) {
93 struct ifreq request = createRequest();
94
95 strncpy(request.ifr_name, mInterfaceName.c_str(), sizeof(request.ifr_name));
96 request.ifr_mtu = mtu;
97 int status = ::ioctl(mSocketFd, SIOCSIFMTU, &request);
98 if (status != 0) {
99 return Result::error("Failed to set interface MTU %u for '%s': %s",
100 static_cast<unsigned int>(mtu), mInterfaceName.c_str(),
101 strerror(errno));
102 }
103
104 return Result::success();
105 }
106
setAddress(in_addr_t address,in_addr_t subnetMask)107 Result Interface::setAddress(in_addr_t address, in_addr_t subnetMask) {
108 struct Request {
109 struct nlmsghdr hdr;
110 struct ifaddrmsg msg;
111 char buf[256];
112 } request;
113
114 memset(&request, 0, sizeof(request));
115
116 request.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(request.msg));
117 request.hdr.nlmsg_type = RTM_NEWADDR;
118 request.hdr.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_REPLACE;
119
120 request.msg.ifa_family = AF_INET;
121 // Count the number of bits in the subnet mask, this is the length.
122 request.msg.ifa_prefixlen = __builtin_popcount(subnetMask);
123 request.msg.ifa_index = mIndex;
124
125 addRouterAttribute(request, IFA_ADDRESS, &address, sizeof(address));
126 addRouterAttribute(request, IFA_LOCAL, &address, sizeof(address));
127 in_addr_t broadcast = broadcastFromNetmask(address, subnetMask);
128 addRouterAttribute(request, IFA_BROADCAST, &broadcast, sizeof(broadcast));
129
130 struct sockaddr_nl nlAddr;
131 memset(&nlAddr, 0, sizeof(nlAddr));
132 nlAddr.nl_family = AF_NETLINK;
133
134 int status = ::sendto(mSocketFd, &request, request.hdr.nlmsg_len, 0,
135 reinterpret_cast<sockaddr*>(&nlAddr), sizeof(nlAddr));
136 if (status == -1) {
137 return Result::error("Unable to set interface address: %s", strerror(errno));
138 }
139 char buffer[8192];
140 status = ::recv(mSocketFd, buffer, sizeof(buffer), 0);
141 if (status < 0) {
142 return Result::error("Unable to read netlink response: %s", strerror(errno));
143 }
144 size_t responseSize = static_cast<size_t>(status);
145 if (responseSize < sizeof(nlmsghdr)) {
146 return Result::error("Received incomplete response from netlink");
147 }
148 auto response = reinterpret_cast<const nlmsghdr*>(buffer);
149 if (response->nlmsg_type == NLMSG_ERROR) {
150 if (responseSize < NLMSG_HDRLEN + sizeof(nlmsgerr)) {
151 return Result::error("Received an error from netlink but the "
152 "response was incomplete");
153 }
154 auto err = reinterpret_cast<const nlmsgerr*>(NLMSG_DATA(response));
155 if (err->error) {
156 return Result::error("Could not set interface address: %s", strerror(-err->error));
157 }
158 }
159 return Result::success();
160 }
161
createRequest() const162 struct ifreq Interface::createRequest() const {
163 struct ifreq request;
164 memset(&request, 0, sizeof(request));
165 strncpy(request.ifr_name, mInterfaceName.c_str(), sizeof(request.ifr_name));
166 request.ifr_name[sizeof(request.ifr_name) - 1] = '\0';
167
168 return request;
169 }
170
populateIndex()171 Result Interface::populateIndex() {
172 struct ifreq request = createRequest();
173
174 int status = ::ioctl(mSocketFd, SIOCGIFINDEX, &request);
175 if (status != 0) {
176 return Result::error("Failed to get interface index for '%s': %s", mInterfaceName.c_str(),
177 strerror(errno));
178 }
179 mIndex = request.ifr_ifindex;
180 return Result::success();
181 }
182
populateMacAddress()183 Result Interface::populateMacAddress() {
184 struct ifreq request = createRequest();
185
186 int status = ::ioctl(mSocketFd, SIOCGIFHWADDR, &request);
187 if (status != 0) {
188 return Result::error("Failed to get MAC address for '%s': %s", mInterfaceName.c_str(),
189 strerror(errno));
190 }
191 memcpy(mMacAddress, &request.ifr_hwaddr.sa_data, ETH_ALEN);
192 return Result::success();
193 }
194
setInterfaceUp(bool shouldBeUp)195 Result Interface::setInterfaceUp(bool shouldBeUp) {
196 struct ifreq request = createRequest();
197
198 int status = ::ioctl(mSocketFd, SIOCGIFFLAGS, &request);
199 if (status != 0) {
200 return Result::error("Failed to get interface flags for '%s': %s", mInterfaceName.c_str(),
201 strerror(errno));
202 }
203
204 bool isUp = (request.ifr_flags & IFF_UP) != 0;
205 if (isUp != shouldBeUp) {
206 // Toggle the up flag
207 request.ifr_flags ^= IFF_UP;
208 } else {
209 // Interface is already in desired state, do nothing
210 return Result::success();
211 }
212
213 status = ::ioctl(mSocketFd, SIOCSIFFLAGS, &request);
214 if (status != 0) {
215 return Result::error("Failed to set interface flags for '%s': %s", mInterfaceName.c_str(),
216 strerror(errno));
217 }
218
219 return Result::success();
220 }
221