blob: 8471173d245c0b78db2f4f8cd474c2ce7bbd8f72 [file] [log] [blame]
Tomasz Wasilczyka5c83a52020-06-16 15:58:19 -07001/*
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
Tomasz Wasilczyk2aa1a122020-07-20 14:03:05 -070024#include <map>
25
Tomasz Wasilczyka5c83a52020-06-16 15:58:19 -070026namespace android::netdevice::ifreqs {
27
Tomasz Wasilczyk2aa1a122020-07-20 14:03:05 -070028static constexpr int defaultSocketDomain = AF_INET;
29std::atomic_int socketDomain = defaultSocketDomain;
30
31struct SocketParams {
32 int domain;
33 int type;
34 int protocol;
35};
36
37static 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
42static 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
Tomasz Wasilczyk2b162da2022-07-21 18:11:21 +000050int trySend(unsigned long request, struct ifreq& ifr) {
Tomasz Wasilczyk2aa1a122020-07-20 14:03:05 -070051 const auto sp = getSocketParams(socketDomain);
52 base::unique_fd sock(socket(sp.domain, sp.type, sp.protocol));
Tomasz Wasilczyka5c83a52020-06-16 15:58:19 -070053 if (!sock.ok()) {
54 LOG(ERROR) << "Can't create socket";
55 return false;
56 }
57
Tomasz Wasilczyk2b162da2022-07-21 18:11:21 +000058 if (ioctl(sock.get(), request, &ifr) < 0) return errno;
59 return 0;
60}
61
62bool send(unsigned long request, struct ifreq& ifr) {
63 if (trySend(request, ifr) != 0) {
Tomasz Wasilczyka5c83a52020-06-16 15:58:19 -070064 PLOG(ERROR) << "ioctl(" << std::hex << request << std::dec << ") failed";
65 return false;
66 }
67
68 return true;
69}
70
71struct ifreq fromName(const std::string& ifname) {
72 struct ifreq ifr = {};
73 strlcpy(ifr.ifr_name, ifname.c_str(), IF_NAMESIZE);
74 return ifr;
75}
76
77} // namespace android::netdevice::ifreqs