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 <map>
25 
26 namespace android::netdevice::ifreqs {
27 
28 static constexpr int defaultSocketDomain = AF_INET;
29 std::atomic_int socketDomain = defaultSocketDomain;
30 
31 struct SocketParams {
32     int domain;
33     int type;
34     int protocol;
35 };
36 
37 static const std::map<int, SocketParams> socketParams = {
38         {AF_INET, {AF_INET, SOCK_DGRAM, 0}},
39         {AF_CAN, {AF_CAN, SOCK_RAW, CAN_RAW}},
40 };
41 
getSocketParams(int domain)42 static SocketParams getSocketParams(int domain) {
43     if (socketParams.count(domain)) return socketParams.find(domain)->second;
44 
45     auto params = socketParams.find(defaultSocketDomain)->second;
46     params.domain = domain;
47     return params;
48 }
49 
send(unsigned long request,struct ifreq & ifr)50 bool send(unsigned long request, struct ifreq& ifr) {
51     const auto sp = getSocketParams(socketDomain);
52     base::unique_fd sock(socket(sp.domain, sp.type, sp.protocol));
53     if (!sock.ok()) {
54         LOG(ERROR) << "Can't create socket";
55         return false;
56     }
57 
58     if (ioctl(sock.get(), request, &ifr) < 0) {
59         PLOG(ERROR) << "ioctl(" << std::hex << request << std::dec << ") failed";
60         return false;
61     }
62 
63     return true;
64 }
65 
fromName(const std::string & ifname)66 struct ifreq fromName(const std::string& ifname) {
67     struct ifreq ifr = {};
68     strlcpy(ifr.ifr_name, ifname.c_str(), IF_NAMESIZE);
69     return ifr;
70 }
71 
72 }  // namespace android::netdevice::ifreqs
73