blob: 28c59db6b93273bcc957780f39846cc41c5499f5 [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 "jni.h"
Steven Moreland2279b252017-07-19 09:50:45 -070022#include <nativehelper/JNIHelp.h>
Luke Huang92ae35e2019-01-04 19:46:47 +080023#include <nativehelper/ScopedLocalRef.h>
Paul Jensen38764952014-05-20 11:25:35 -040024#include "NetdClient.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025#include <utils/misc.h>
26#include <android_runtime/AndroidRuntime.h>
27#include <utils/Log.h>
28#include <arpa/inet.h>
Lorenzo Colitticbe4f7c2015-03-06 19:57:39 +090029#include <net/if.h>
30#include <linux/filter.h>
Paul Jensen578a76e2016-01-14 14:54:39 -050031#include <linux/if_arp.h>
markchien150e1912018-12-27 22:49:51 +080032#include <linux/tcp.h>
Elliott Hughes7691b782016-05-11 15:18:13 -070033#include <netinet/ether.h>
Paul Jensen578a76e2016-01-14 14:54:39 -050034#include <netinet/icmp6.h>
Lorenzo Colitticbe4f7c2015-03-06 19:57:39 +090035#include <netinet/ip.h>
Paul Jensen578a76e2016-01-14 14:54:39 -050036#include <netinet/ip6.h>
Lorenzo Colitticbe4f7c2015-03-06 19:57:39 +090037#include <netinet/udp.h>
Robert Greenwalt0216e612011-01-14 16:29:58 -080038#include <cutils/properties.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039
Andreas Gampe987f79f2014-11-18 17:29:46 -080040#include "core_jni_helpers.h"
41
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;
52// FrameworkListener limits the size of commands to 1024 bytes. TODO: fix this.
53constexpr int MAXCMDSIZE = 1024;
54
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 +0900104static void android_net_utils_setupRaSocket(JNIEnv *env, jobject clazz, jobject javaFd,
105 jint ifIndex)
106{
107 static const int kLinkLocalHopLimit = 255;
108
109 int fd = jniGetFDFromFileDescriptor(env, javaFd);
110
111 // Set an ICMPv6 filter that only passes Router Solicitations.
112 struct icmp6_filter rs_only;
113 ICMP6_FILTER_SETBLOCKALL(&rs_only);
114 ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &rs_only);
115 socklen_t len = sizeof(rs_only);
116 if (setsockopt(fd, IPPROTO_ICMPV6, ICMP6_FILTER, &rs_only, len) != 0) {
117 jniThrowExceptionFmt(env, "java/net/SocketException",
118 "setsockopt(ICMP6_FILTER): %s", strerror(errno));
119 return;
120 }
121
122 // Most/all of the rest of these options can be set via Java code, but
123 // because we're here on account of setting an icmp6_filter go ahead
124 // and do it all natively for now.
125 //
126 // TODO: Consider moving these out to Java.
127
128 // Set the multicast hoplimit to 255 (link-local only).
129 int hops = kLinkLocalHopLimit;
130 len = sizeof(hops);
131 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, len) != 0) {
132 jniThrowExceptionFmt(env, "java/net/SocketException",
133 "setsockopt(IPV6_MULTICAST_HOPS): %s", strerror(errno));
134 return;
135 }
136
137 // Set the unicast hoplimit to 255 (link-local only).
138 hops = kLinkLocalHopLimit;
139 len = sizeof(hops);
140 if (setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &hops, len) != 0) {
141 jniThrowExceptionFmt(env, "java/net/SocketException",
142 "setsockopt(IPV6_UNICAST_HOPS): %s", strerror(errno));
143 return;
144 }
145
146 // Explicitly disable multicast loopback.
147 int off = 0;
148 len = sizeof(off);
149 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &off, len) != 0) {
150 jniThrowExceptionFmt(env, "java/net/SocketException",
151 "setsockopt(IPV6_MULTICAST_LOOP): %s", strerror(errno));
152 return;
153 }
154
155 // Specify the IPv6 interface to use for outbound multicast.
156 len = sizeof(ifIndex);
157 if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, &ifIndex, len) != 0) {
158 jniThrowExceptionFmt(env, "java/net/SocketException",
159 "setsockopt(IPV6_MULTICAST_IF): %s", strerror(errno));
160 return;
161 }
162
163 // Additional options to be considered:
164 // - IPV6_TCLASS
165 // - IPV6_RECVPKTINFO
166 // - IPV6_RECVHOPLIMIT
167
168 // Bind to [::].
169 const struct sockaddr_in6 sin6 = {
170 .sin6_family = AF_INET6,
171 .sin6_port = 0,
172 .sin6_flowinfo = 0,
173 .sin6_addr = IN6ADDR_ANY_INIT,
174 .sin6_scope_id = 0,
175 };
176 auto sa = reinterpret_cast<const struct sockaddr *>(&sin6);
177 len = sizeof(sin6);
178 if (bind(fd, sa, len) != 0) {
179 jniThrowExceptionFmt(env, "java/net/SocketException",
180 "bind(IN6ADDR_ANY): %s", strerror(errno));
181 return;
182 }
183
184 // Join the all-routers multicast group, ff02::2%index.
185 struct ipv6_mreq all_rtrs = {
186 .ipv6mr_multiaddr = {{{0xff,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2}}},
187 .ipv6mr_interface = ifIndex,
188 };
189 len = sizeof(all_rtrs);
190 if (setsockopt(fd, IPPROTO_IPV6, IPV6_JOIN_GROUP, &all_rtrs, len) != 0) {
191 jniThrowExceptionFmt(env, "java/net/SocketException",
192 "setsockopt(IPV6_JOIN_GROUP): %s", strerror(errno));
193 return;
194 }
195}
196
Paul Jensen32a58f02014-06-20 13:58:14 -0400197static jboolean android_net_utils_bindProcessToNetwork(JNIEnv *env, jobject thiz, jint netId)
Paul Jensen38764952014-05-20 11:25:35 -0400198{
Paul Jensen32a58f02014-06-20 13:58:14 -0400199 return (jboolean) !setNetworkForProcess(netId);
Paul Jensen38764952014-05-20 11:25:35 -0400200}
201
Paul Jensen72db88e2015-03-10 10:54:12 -0400202static jint android_net_utils_getBoundNetworkForProcess(JNIEnv *env, jobject thiz)
Paul Jensen38764952014-05-20 11:25:35 -0400203{
204 return getNetworkForProcess();
205}
206
Paul Jensen32a58f02014-06-20 13:58:14 -0400207static jboolean android_net_utils_bindProcessToNetworkForHostResolution(JNIEnv *env, jobject thiz,
208 jint netId)
Paul Jensen38764952014-05-20 11:25:35 -0400209{
Paul Jensen32a58f02014-06-20 13:58:14 -0400210 return (jboolean) !setNetworkForResolv(netId);
Paul Jensen38764952014-05-20 11:25:35 -0400211}
212
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700213static jint android_net_utils_bindSocketToNetwork(JNIEnv *env, jobject thiz, jint socket,
Paul Jensen32a58f02014-06-20 13:58:14 -0400214 jint netId)
Paul Jensen38764952014-05-20 11:25:35 -0400215{
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700216 return setNetworkForSocket(netId, socket);
Paul Jensen38764952014-05-20 11:25:35 -0400217}
218
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400219static jboolean android_net_utils_protectFromVpn(JNIEnv *env, jobject thiz, jint socket)
220{
221 return (jboolean) !protectFromVpn(socket);
222}
223
Paul Jensencee9b512015-05-06 07:32:40 -0400224static jboolean android_net_utils_queryUserAccess(JNIEnv *env, jobject thiz, jint uid, jint netId)
225{
226 return (jboolean) !queryUserAccess(uid, netId);
227}
228
Remi NGUYEN VAN12da4a52018-07-04 11:15:56 +0900229static bool checkLenAndCopy(JNIEnv* env, const jbyteArray& addr, int len, void* dst)
230{
231 if (env->GetArrayLength(addr) != len) {
232 return false;
233 }
234 env->GetByteArrayRegion(addr, 0, len, reinterpret_cast<jbyte*>(dst));
235 return true;
236}
237
Luke Huang92ae35e2019-01-04 19:46:47 +0800238static jobject android_net_utils_resNetworkQuery(JNIEnv *env, jobject thiz, jint netId,
239 jstring dname, jint ns_class, jint ns_type, jint flags) {
240 const jsize javaCharsCount = env->GetStringLength(dname);
241 const jsize byteCountUTF8 = env->GetStringUTFLength(dname);
242
243 // Only allow dname which could be simply formatted to UTF8.
244 // In native layer, res_mkquery would re-format the input char array to packet.
245 std::vector<char> queryname(byteCountUTF8 + 1, 0);
246
247 env->GetStringUTFRegion(dname, 0, javaCharsCount, queryname.data());
248 int fd = resNetworkQuery(netId, queryname.data(), ns_class, ns_type, flags);
249
250 if (fd < 0) {
251 throwErrnoException(env, "resNetworkQuery", -fd);
252 return nullptr;
253 }
254
255 return jniCreateFileDescriptor(env, fd);
256}
257
258static jobject android_net_utils_resNetworkSend(JNIEnv *env, jobject thiz, jint netId,
259 jbyteArray msg, jint msgLen, jint flags) {
260 uint8_t data[MAXCMDSIZE];
261
262 checkLenAndCopy(env, msg, msgLen, data);
263 int fd = resNetworkSend(netId, data, msgLen, flags);
264
265 if (fd < 0) {
266 throwErrnoException(env, "resNetworkSend", -fd);
267 return nullptr;
268 }
269
270 return jniCreateFileDescriptor(env, fd);
271}
272
Luke Huangec214472019-04-11 17:54:41 -0700273static jobject android_net_utils_resNetworkResult(JNIEnv *env, jobject thiz, jobject javaFd) {
Luke Huang92ae35e2019-01-04 19:46:47 +0800274 int fd = jniGetFDFromFileDescriptor(env, javaFd);
275 int rcode;
276 std::vector<uint8_t> buf(MAXPACKETSIZE, 0);
277
278 int res = resNetworkResult(fd, &rcode, buf.data(), MAXPACKETSIZE);
Luke Huang5386f492019-03-26 15:50:10 +0800279 jniSetFileDescriptorOfFD(env, javaFd, -1);
Luke Huang92ae35e2019-01-04 19:46:47 +0800280 if (res < 0) {
281 throwErrnoException(env, "resNetworkResult", -res);
282 return nullptr;
283 }
284
285 jbyteArray answer = env->NewByteArray(res);
286 if (answer == nullptr) {
287 throwErrnoException(env, "resNetworkResult", ENOMEM);
288 return nullptr;
289 } else {
290 env->SetByteArrayRegion(answer, 0, res,
291 reinterpret_cast<jbyte*>(buf.data()));
292 }
293
Luke Huangec214472019-04-11 17:54:41 -0700294 jclass class_DnsResponse = env->FindClass("android/net/DnsResolver$DnsResponse");
295 jmethodID ctor = env->GetMethodID(class_DnsResponse, "<init>", "([BI)V");
296
297 return env->NewObject(class_DnsResponse, ctor, answer, rcode);
Luke Huang92ae35e2019-01-04 19:46:47 +0800298}
Lorenzo Colitticbe4f7c2015-03-06 19:57:39 +0900299
Luke Huangc09f2d62019-03-08 14:48:59 +0800300static void android_net_utils_resNetworkCancel(JNIEnv *env, jobject thiz, jobject javaFd) {
301 int fd = jniGetFDFromFileDescriptor(env, javaFd);
302 resNetworkCancel(fd);
Luke Huang5386f492019-03-26 15:50:10 +0800303 jniSetFileDescriptorOfFD(env, javaFd, -1);
Luke Huangc09f2d62019-03-08 14:48:59 +0800304}
305
markchien150e1912018-12-27 22:49:51 +0800306static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
307 if (javaFd == NULL) {
308 jniThrowNullPointerException(env, NULL);
309 return NULL;
310 }
311
312 int fd = jniGetFDFromFileDescriptor(env, javaFd);
313 struct tcp_repair_window trw = {};
314 socklen_t size = sizeof(trw);
315
316 // Obtain the parameters of the TCP repair window.
317 int rc = getsockopt(fd, IPPROTO_TCP, TCP_REPAIR_WINDOW, &trw, &size);
318 if (rc == -1) {
319 throwErrnoException(env, "getsockopt : TCP_REPAIR_WINDOW", errno);
320 return NULL;
321 }
322
323 struct tcp_info tcpinfo = {};
324 socklen_t tcpinfo_size = sizeof(tcp_info);
325
326 // Obtain the window scale from the tcp info structure. This contains a scale factor that
327 // should be applied to the window size.
328 rc = getsockopt(fd, IPPROTO_TCP, TCP_INFO, &tcpinfo, &tcpinfo_size);
329 if (rc == -1) {
330 throwErrnoException(env, "getsockopt : TCP_INFO", errno);
331 return NULL;
332 }
333
334 jclass class_TcpRepairWindow = env->FindClass("android/net/TcpRepairWindow");
335 jmethodID ctor = env->GetMethodID(class_TcpRepairWindow, "<init>", "(IIIIII)V");
336
337 return env->NewObject(class_TcpRepairWindow, ctor, trw.snd_wl1, trw.snd_wnd, trw.max_window,
338 trw.rcv_wnd, trw.rcv_wup, tcpinfo.tcpi_rcv_wscale);
339}
340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341// ----------------------------------------------------------------------------
342
343/*
344 * JNI registration.
345 */
Daniel Micay76f6a862015-09-19 17:31:01 -0400346static const JNINativeMethod gNetworkUtilMethods[] = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 /* name, signature, funcPtr */
Paul Jensen32a58f02014-06-20 13:58:14 -0400348 { "bindProcessToNetwork", "(I)Z", (void*) android_net_utils_bindProcessToNetwork },
Paul Jensen72db88e2015-03-10 10:54:12 -0400349 { "getBoundNetworkForProcess", "()I", (void*) android_net_utils_getBoundNetworkForProcess },
Paul Jensen32a58f02014-06-20 13:58:14 -0400350 { "bindProcessToNetworkForHostResolution", "(I)Z", (void*) android_net_utils_bindProcessToNetworkForHostResolution },
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700351 { "bindSocketToNetwork", "(II)I", (void*) android_net_utils_bindSocketToNetwork },
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400352 { "protectFromVpn", "(I)Z", (void*)android_net_utils_protectFromVpn },
Paul Jensencee9b512015-05-06 07:32:40 -0400353 { "queryUserAccess", "(II)Z", (void*)android_net_utils_queryUserAccess },
markchien150e1912018-12-27 22:49:51 +0800354 { "attachDropAllBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_attachDropAllBPFFilter },
355 { "detachBPFFilter", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_detachBPFFilter },
356 { "getTcpRepairWindow", "(Ljava/io/FileDescriptor;)Landroid/net/TcpRepairWindow;", (void*) android_net_utils_getTcpRepairWindow },
Erik Klinea3ca6bd2016-05-24 20:12:08 +0900357 { "setupRaSocket", "(Ljava/io/FileDescriptor;I)V", (void*) android_net_utils_setupRaSocket },
Luke Huang92ae35e2019-01-04 19:46:47 +0800358 { "resNetworkSend", "(I[BII)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkSend },
359 { "resNetworkQuery", "(ILjava/lang/String;III)Ljava/io/FileDescriptor;", (void*) android_net_utils_resNetworkQuery },
Luke Huangec214472019-04-11 17:54:41 -0700360 { "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
Luke Huangc09f2d62019-03-08 14:48:59 +0800361 { "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800362};
363
364int register_android_net_NetworkUtils(JNIEnv* env)
365{
Andreas Gampe987f79f2014-11-18 17:29:46 -0800366 return RegisterMethodsOrDie(env, NETUTILS_PKG_NAME, gNetworkUtilMethods,
367 NELEM(gNetworkUtilMethods));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800368}
369
370}; // namespace android