1 /*
2 * Copyright (C) 2020 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 "ifreqs.h"
18
19 #include "common.h"
20
21 #include <android-base/logging.h>
22 #include <android-base/unique_fd.h>
23
24 #include <sys/ioctl.h>
25
26 #include <map>
27
28 namespace android::netdevice::ifreqs {
29
30 static constexpr int defaultSocketDomain = AF_INET;
31 std::atomic_int socketDomain = defaultSocketDomain;
32
33 struct SocketParams {
34 int domain;
35 int type;
36 int protocol;
37 };
38
39 static const std::map<int, SocketParams> socketParams = {
40 {AF_INET, {AF_INET, SOCK_DGRAM, 0}},
41 {AF_CAN, {AF_CAN, SOCK_RAW, CAN_RAW}},
42 };
43
getSocketParams(int domain)44 static SocketParams getSocketParams(int domain) {
45 if (socketParams.count(domain)) return socketParams.find(domain)->second;
46
47 auto params = socketParams.find(defaultSocketDomain)->second;
48 params.domain = domain;
49 return params;
50 }
51
trySend(unsigned long request,struct ifreq & ifr)52 int trySend(unsigned long request, struct ifreq& ifr) {
53 const auto sp = getSocketParams(socketDomain);
54 base::unique_fd sock(socket(sp.domain, sp.type, sp.protocol));
55 if (!sock.ok()) {
56 LOG(ERROR) << "Can't create socket";
57 return false;
58 }
59
60 if (ioctl(sock.get(), request, &ifr) < 0) return errno;
61 return 0;
62 }
63
send(unsigned long request,struct ifreq & ifr)64 bool send(unsigned long request, struct ifreq& ifr) {
65 if (trySend(request, ifr) != 0) {
66 PLOG(ERROR) << "ioctl(" << std::hex << request << std::dec << ") failed";
67 return false;
68 }
69
70 return true;
71 }
72
fromName(std::string_view ifname)73 struct ifreq fromName(std::string_view ifname) {
74 struct ifreq ifr = {};
75 // memcpy: last \0 initialized with ifreq above
76 memcpy(ifr.ifr_name, ifname.data(),
77 std::min(ifname.size(), static_cast<size_t>(IF_NAMESIZE - 1)));
78 return ifr;
79 }
80
81 } // namespace android::netdevice::ifreqs
82