blob: d4805acb06d08b7e5c3c65a4bbd79b9b36910729 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright 2008, The Android Open Source Project
3 *
Elliott Hughesdd66bcb2011-04-12 11:28:59 -07004 * 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007 *
Elliott Hughesdd66bcb2011-04-12 11:28:59 -07008 * http://www.apache.org/licenses/LICENSE-2.0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009 *
Elliott Hughesdd66bcb2011-04-12 11:28:59 -070010 * 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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014 * limitations under the License.
15 */
16
17#define LOG_TAG "NetUtils"
18
Luke Huang92ae35e2019-01-04 19:46:47 +080019#include <vector>
20
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021#include <arpa/inet.h>
Lorenzo Colitticbe4f7c2015-03-06 19:57:39 +090022#include <linux/filter.h>
Paul Jensen578a76e2016-01-14 14:54:39 -050023#include <linux/if_arp.h>
markchien150e1912018-12-27 22:49:51 +080024#include <linux/tcp.h>
Luke Huang247d83a2019-04-17 22:27:56 +080025#include <net/if.h>
Elliott Hughes7691b782016-05-11 15:18:13 -070026#include <netinet/ether.h>
Lorenzo Colitticbe4f7c2015-03-06 19:57:39 +090027#include <netinet/ip.h>
28#include <netinet/udp.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
Luke Huang141ec962020-05-28 15:41:46 +080030#include <DnsProxydProtocol.h> // NETID_USE_LOCAL_NAMESERVERS
Luke Huang247d83a2019-04-17 22:27:56 +080031#include <android_runtime/AndroidRuntime.h>
32#include <cutils/properties.h>
Luke Huang247d83a2019-04-17 22:27:56 +080033#include <nativehelper/JNIHelp.h>
34#include <nativehelper/ScopedLocalRef.h>
Luke Huang141ec962020-05-28 15:41:46 +080035#include <utils/Log.h>
36#include <utils/misc.h>
Luke Huang247d83a2019-04-17 22:27:56 +080037
38#include "NetdClient.h"
Andreas Gampe987f79f2014-11-18 17:29:46 -080039#include "core_jni_helpers.h"
Luke Huang247d83a2019-04-17 22:27:56 +080040#include "jni.h"
Andreas Gampe987f79f2014-11-18 17:29:46 -080041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042extern "C" {
Mike Lockwood0900f362009-07-10 17:24:07 -040043int ifc_enable(const char *ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044int ifc_disable(const char *ifname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045}
46
47#define NETUTILS_PKG_NAME "android/net/NetworkUtils"
48
49namespace android {
50
Luke Huang92ae35e2019-01-04 19:46:47 +080051constexpr int MAXPACKETSIZE = 8 * 1024;
Luke Huangf482a322019-05-02 11:46:25 +080052// FrameworkListener limits the size of commands to 4096 bytes.
53constexpr int MAXCMDSIZE = 4096;
Luke Huang92ae35e2019-01-04 19:46:47 +080054
55static void throwErrnoException(JNIEnv* env, const char* functionName, int error) {
56 ScopedLocalRef<jstring> detailMessage(env, env->NewStringUTF(functionName));
57 if (detailMessage.get() == NULL) {
58 // Not really much we can do here. We're probably dead in the water,
59 // but let's try to stumble on...
60 env->ExceptionClear();
61 }
62 static jclass errnoExceptionClass =
63 MakeGlobalRefOrDie(env, FindClassOrDie(env, "android/system/ErrnoException"));
64
65 static jmethodID errnoExceptionCtor =
66 GetMethodIDOrDie(env, errnoExceptionClass,
67 "<init>", "(Ljava/lang/String;I)V");
68
69 jobject exception = env->NewObject(errnoExceptionClass,
70 errnoExceptionCtor,
71 detailMessage.get(),
72 error);
73 env->Throw(reinterpret_cast<jthrowable>(exception));
74}
75
markchien150e1912018-12-27 22:49:51 +080076static void android_net_utils_attachDropAllBPFFilter(JNIEnv *env, jobject clazz, jobject javaFd)
77{
78 struct sock_filter filter_code[] = {
79 // Reject all.
80 BPF_STMT(BPF_RET | BPF_K, 0)
81 };
82 struct sock_fprog filter = {
83 sizeof(filter_code) / sizeof(filter_code[0]),
84 filter_code,
85 };
86
87 int fd = jniGetFDFromFileDescriptor(env, javaFd);
88 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter, sizeof(filter)) != 0) {
89 jniThrowExceptionFmt(env, "java/net/SocketException",
90 "setsockopt(SO_ATTACH_FILTER): %s", strerror(errno));
91 }
92}
93
94static void android_net_utils_detachBPFFilter(JNIEnv *env, jobject clazz, jobject javaFd)
95{
96 int dummy = 0;
97 int fd = jniGetFDFromFileDescriptor(env, javaFd);
98 if (setsockopt(fd, SOL_SOCKET, SO_DETACH_FILTER, &dummy, sizeof(dummy)) != 0) {
99 jniThrowExceptionFmt(env, "java/net/SocketException",
100 "setsockopt(SO_DETACH_FILTER): %s", strerror(errno));
101 }
102
103}
Erik Klinea3ca6bd2016-05-24 20:12:08 +0900104
Paul Jensen32a58f02014-06-20 13:58:14 -0400105static jboolean android_net_utils_bindProcessToNetwork(JNIEnv *env, jobject thiz, jint netId)
Paul Jensen38764952014-05-20 11:25:35 -0400106{
Paul Jensen32a58f02014-06-20 13:58:14 -0400107 return (jboolean) !setNetworkForProcess(netId);
Paul Jensen38764952014-05-20 11:25:35 -0400108}
109
Paul Jensen72db88e2015-03-10 10:54:12 -0400110static jint android_net_utils_getBoundNetworkForProcess(JNIEnv *env, jobject thiz)
Paul Jensen38764952014-05-20 11:25:35 -0400111{
112 return getNetworkForProcess();
113}
114
Paul Jensen32a58f02014-06-20 13:58:14 -0400115static jboolean android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv *env, jobject thiz,
116 jint netId)
Paul Jensen38764952014-05-20 11:25:35 -0400117{
Paul Jensen32a58f02014-06-20 13:58:14 -0400118 return (jboolean) !setNetworkForResolv(netId);
Paul Jensen38764952014-05-20 11:25:35 -0400119}
120
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700121static jint android_net_utils_bindSocketToNetwork(JNIEnv *env, jobject thiz, jint socket,
Paul Jensen32a58f02014-06-20 13:58:14 -0400122 jint netId)
Paul Jensen38764952014-05-20 11:25:35 -0400123{
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700124 return setNetworkForSocket(netId, socket);
Paul Jensen38764952014-05-20 11:25:35 -0400125}
126
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400127static jboolean android_net_utils_protectFromVpn(JNIEnv *env, jobject thiz, jint socket)
128{
129 return (jboolean) !protectFromVpn(socket);
130}
131
Paul Jensencee9b512015-05-06 07:32:40 -0400132static jboolean android_net_utils_queryUserAccess(JNIEnv *env, jobject thiz, jint uid, jint netId)
133{
134 return (jboolean) !queryUserAccess(uid, netId);
135}
136
Remi NGUYEN VAN12da4a52018-07-04 11:15:56 +0900137static bool checkLenAndCopy(JNIEnv* env, const jbyteArray& addr, int len, void* dst)
138{
139 if (env->GetArrayLength(addr) != len) {
140 return false;
141 }
142 env->GetByteArrayRegion(addr, 0, len, reinterpret_cast<jbyte*>(dst));
143 return true;
144}
145
Luke Huang92ae35e2019-01-04 19:46:47 +0800146static jobject android_net_utils_resNetworkQuery(JNIEnv *env, jobject thiz, jint netId,
147 jstring dname, jint ns_class, jint ns_type, jint flags) {
148 const jsize javaCharsCount = env->GetStringLength(dname);
149 const jsize byteCountUTF8 = env->GetStringUTFLength(dname);
150
151 // Only allow dname which could be simply formatted to UTF8.
152 // In native layer, res_mkquery would re-format the input char array to packet.
153 std::vector<char> queryname(byteCountUTF8 + 1, 0);
154
155 env->GetStringUTFRegion(dname, 0, javaCharsCount, queryname.data());
156 int fd = resNetworkQuery(netId, queryname.data(), ns_class, ns_type, flags);
157
158 if (fd < 0) {
159 throwErrnoException(env, "resNetworkQuery", -fd);
160 return nullptr;
161 }
162
163 return jniCreateFileDescriptor(env, fd);
164}
165
166static jobject android_net_utils_resNetworkSend(JNIEnv *env, jobject thiz, jint netId,
167 jbyteArray msg, jint msgLen, jint flags) {
168 uint8_t data[MAXCMDSIZE];
169
170 checkLenAndCopy(env, msg, msgLen, data);
171 int fd = resNetworkSend(netId, data, msgLen, flags);
172
173 if (fd < 0) {
174 throwErrnoException(env, "resNetworkSend", -fd);
175 return nullptr;
176 }
177
178 return jniCreateFileDescriptor(env, fd);
179}
180
Luke Huang4219ab62019-04-08 15:16:04 +0800181static jobject android_net_utils_resNetworkResult(JNIEnv *env, jobject thiz, jobject javaFd) {
Luke Huang92ae35e2019-01-04 19:46:47 +0800182 int fd = jniGetFDFromFileDescriptor(env, javaFd);
183 int rcode;
184 std::vector<uint8_t> buf(MAXPACKETSIZE, 0);
185
186 int res = resNetworkResult(fd, &rcode, buf.data(), MAXPACKETSIZE);
Luke Huang5386f492019-03-26 15:50:10 +0800187 jniSetFileDescriptorOfFD(env, javaFd, -1);
Luke Huang92ae35e2019-01-04 19:46:47 +0800188 if (res < 0) {
189 throwErrnoException(env, "resNetworkResult", -res);
190 return nullptr;
191 }
192
193 jbyteArray answer = env->NewByteArray(res);
194 if (answer == nullptr) {
195 throwErrnoException(env, "resNetworkResult", ENOMEM);
196 return nullptr;
197 } else {
198 env->SetByteArrayRegion(answer, 0, res,
199 reinterpret_cast<jbyte*>(buf.data()));
200 }
201
Luke Huang4219ab62019-04-08 15:16:04 +0800202 jclass class_DnsResponse = env->FindClass("android/net/DnsResolver$DnsResponse");
203 jmethodID ctor = env->GetMethodID(class_DnsResponse, "<init>", "([BI)V");
204
205 return env->NewObject(class_DnsResponse, ctor, answer, rcode);
Luke Huang92ae35e2019-01-04 19:46:47 +0800206}
Lorenzo Colitticbe4f7c2015-03-06 19:57:39 +0900207
Luke Huangc09f2d62019-03-08 14:48:59 +0800208static void android_net_utils_resNetworkCancel(JNIEnv *env, jobject thiz, jobject javaFd) {
209 int fd = jniGetFDFromFileDescriptor(env, javaFd);
210 resNetworkCancel(fd);
Luke Huang5386f492019-03-26 15:50:10 +0800211 jniSetFileDescriptorOfFD(env, javaFd, -1);
Luke Huangc09f2d62019-03-08 14:48:59 +0800212}
213
Luke Huangc211b272019-05-29 01:30:07 +0800214static jobject android_net_utils_getDnsNetwork(JNIEnv *env, jobject thiz) {
215 unsigned dnsNetId = 0;
216 if (int res = getNetworkForDns(&dnsNetId) < 0) {
217 throwErrnoException(env, "getDnsNetId", -res);
218 return nullptr;
Luke Huang247d83a2019-04-17 22:27:56 +0800219 }
Luke Huangc211b272019-05-29 01:30:07 +0800220 bool privateDnsBypass = dnsNetId & NETID_USE_LOCAL_NAMESERVERS;
Luke Huang247d83a2019-04-17 22:27:56 +0800221
Luke Huangc211b272019-05-29 01:30:07 +0800222 static jclass class_Network = MakeGlobalRefOrDie(
223 env, FindClassOrDie(env, "android/net/Network"));
224 static jmethodID ctor = env->GetMethodID(class_Network, "<init>", "(IZ)V");
225 return env->NewObject(
226 class_Network, ctor, dnsNetId & ~NETID_USE_LOCAL_NAMESERVERS, privateDnsBypass);
Luke Huang247d83a2019-04-17 22:27:56 +0800227}
228
Luke Huang6f214e82020-06-16 19:10:02 +0800229static void android_net_utils_setAllowNetworkingForProcess(JNIEnv *env, jobject thiz,
230 jboolean hasConnectivity) {
231 setAllowNetworkingForProcess(hasConnectivity == JNI_TRUE);
232}
233
markchien150e1912018-12-27 22:49:51 +0800234static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
235 if (javaFd == NULL) {
236 jniThrowNullPointerException(env, NULL);
237 return NULL;
238 }
239
240 int fd = jniGetFDFromFileDescriptor(env, javaFd);
241 struct tcp_repair_window trw = {};
242 socklen_t size = sizeof(trw);
243
244 // Obtain the parameters of the TCP repair window.
245 int rc = getsockopt(fd, IPPROTO_TCP, TCP_REPAIR_WINDOW, &trw, &size);
246 if (rc == -1) {
247 throwErrnoException(env, "getsockopt : TCP_REPAIR_WINDOW", errno);
248 return NULL;
249 }
250
251 struct tcp_info tcpinfo = {};
252 socklen_t tcpinfo_size = sizeof(tcp_info);
253
254 // Obtain the window scale from the tcp info structure. This contains a scale factor that
255 // should be applied to the window size.
256 rc = getsockopt(fd, IPPROTO_TCP, TCP_INFO, &tcpinfo, &tcpinfo_size);
257 if (rc == -1) {
258 throwErrnoException(env, "getsockopt : TCP_INFO", errno);
259 return NULL;
260 }
261
262 jclass class_TcpRepairWindow = env->FindClass("android/net/TcpRepairWindow");
263 jmethodID ctor = env->GetMethodID(class_TcpRepairWindow, "<init>", "(IIIIII)V");
264
265 return env->NewObject(class_TcpRepairWindow, ctor, trw.snd_wl1, trw.snd_wnd, trw.max_window,
266 trw.rcv_wnd, trw.rcv_wup, tcpinfo.tcpi_rcv_wscale);
267}
268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269// ----------------------------------------------------------------------------
270
271/*
272 * JNI registration.
273 */
Luke Huang6f214e82020-06-16 19:10:02 +0800274// clang-format off
Daniel Micay76f6a862015-09-19 17:31:01 -0400275static const JNINativeMethod gNetworkUtilMethods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276 /* name, signature, funcPtr */
Paul Jensen32a58f02014-06-20 13:58:14 -0400277 { "bindProcessToNetwork", "(I)Z", (void*) android_net_utils_bindProcessToNetwork },
Paul Jensen72db88e2015-03-10 10:54:12 -0400278 { "getBoundNetworkForProcess", "()I", (void*) android_net_utils_getBoundNetworkForProcess },
Paul Jensen32a58f02014-06-20 13:58:14 -0400279 { "bindProcessToNetworkForHostResolution", "(I)Z", (void*) android_net_utils_bindProcessToNetworkForHostResolution },
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700280 { "bindSocketToNetwork", "(II)I", (void*) android_net_utils_bindSocketToNetwork },
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400281 { "protectFromVpn", "(I)Z", (void*)android_net_utils_protectFromVpn },
Paul Jensencee9b512015-05-06 07:32:40 -0400282 { "queryUserAccess", "(II)Z", (void*)android_net_utils_queryUserAccess },
markchien150e1912018-12-27 22:49:51 +0800283 { "attachDropAllBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDropAllBPFFilter },
284 { "detachBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_detachBPFFilter },
285 { "getTcpRepairWindow", "(Ljava/io/FileDescriptor;)Landroid/net/TcpRepairWindow;", (void*) android_net_utils_getTcpRepairWindow },
Luke Huang92ae35e2019-01-04 19:46:47 +0800286 { "resNetworkSend", "(I[BII)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkSend },
287 { "resNetworkQuery", "(ILjava/lang/String;III)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkQuery },
Luke Huang4219ab62019-04-08 15:16:04 +0800288 { "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
Luke Huangc09f2d62019-03-08 14:48:59 +0800289 { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
Luke Huangc211b272019-05-29 01:30:07 +0800290 { "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork },
Luke Huang6f214e82020-06-16 19:10:02 +0800291 { "setAllowNetworkingForProcess", "(Z)V", (void *)android_net_utils_setAllowNetworkingForProcess },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292};
Luke Huang6f214e82020-06-16 19:10:02 +0800293// clang-format on
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294
295int register_android_net_NetworkUtils(JNIEnv* env)
296{
Andreas Gampe987f79f2014-11-18 17:29:46 -0800297 return RegisterMethodsOrDie(env, NETUTILS_PKG_NAME, gNetworkUtilMethods,
298 NELEM(gNetworkUtilMethods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299}
300
301}; // namespace android