blob: e972513174f72ddac7d5c94c6d930d21d8ff4d7f [file] [log] [blame]
Maciej Żenczykowskib70da762019-01-28 15:20:48 -08001/*
2 * Copyright (C) 2019 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 "ClatUtils.h"
18
Maciej Żenczykowski0a7dce82019-01-28 15:31:55 -080019#include <errno.h>
20#include <linux/if.h>
21#include <sys/ioctl.h>
22#include <sys/socket.h>
23#include <sys/types.h>
24#include <unistd.h>
25
Maciej Żenczykowskib70da762019-01-28 15:20:48 -080026#define LOG_TAG "ClatUtils"
27#include <log/log.h>
28
Maciej Żenczykowski0a7dce82019-01-28 15:31:55 -080029#include "android-base/unique_fd.h"
Maciej Żenczykowski88d28ff2019-03-25 11:54:32 -070030#include "bpf/BpfUtils.h"
31#include "netdbpf/bpf_shared.h"
Maciej Żenczykowski0a7dce82019-01-28 15:31:55 -080032
Maciej Żenczykowskib70da762019-01-28 15:20:48 -080033namespace android {
34namespace net {
35
Maciej Żenczykowski0a7dce82019-01-28 15:31:55 -080036int hardwareAddressType(const std::string& interface) {
37 base::unique_fd ufd(socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0));
38
39 if (ufd < 0) {
40 const int err = errno;
41 ALOGE("socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, 0)");
42 return -err;
43 };
44
45 struct ifreq ifr = {};
46 // We use strncpy() instead of strlcpy() since kernel has to be able
47 // to handle non-zero terminated junk passed in by userspace anyway,
48 // and this way too long interface names (more than IFNAMSIZ-1 = 15
49 // characters plus terminating NULL) will not get truncated to 15
50 // characters and zero-terminated and thus potentially erroneously
51 // match a truncated interface if one were to exist.
52 strncpy(ifr.ifr_name, interface.c_str(), sizeof(ifr.ifr_name));
53
54 if (ioctl(ufd, SIOCGIFHWADDR, &ifr, sizeof(ifr))) return -errno;
55
56 return ifr.ifr_hwaddr.sa_family;
57}
58
Maciej Żenczykowski88d28ff2019-03-25 11:54:32 -070059int getClatMapFd(void) {
60 const int fd = bpf::bpfFdGet(CLAT_MAP_PATH, 0);
61 return (fd == -1) ? -errno : fd;
62}
63
Maciej Żenczykowski949d84a2019-01-28 17:22:30 -080064int getClatProgFd(bool with_ethernet_header) {
65 const int fd =
66 bpf::bpfFdGet(with_ethernet_header ? CLAT_PROG_ETHER_PATH : CLAT_PROG_RAWIP_PATH, 0);
67 return (fd == -1) ? -errno : fd;
68}
69
Maciej Żenczykowskib70da762019-01-28 15:20:48 -080070} // namespace net
71} // namespace android