blob: 2c831de7205142a4c6b1636be4743f579a93d71d [file] [log] [blame]
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07001/*
2 * Copyright (C) 2014 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
17package android.net;
18
Remi NGUYEN VAN31f1d0c2019-01-20 12:52:43 +090019import android.annotation.SystemApi;
20import android.annotation.TestApi;
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010021import android.annotation.UnsupportedAppUsage;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070022import android.os.Parcel;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010023import android.os.Parcelable;
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070024import android.system.ErrnoException;
Erik Klined8959992015-06-05 17:37:45 +090025import android.system.Os;
26import android.system.OsConstants;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080027import android.util.proto.ProtoOutputStream;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070028
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010029import com.android.okhttp.internalandroidapi.Dns;
30import com.android.okhttp.internalandroidapi.HttpURLConnectionFactory;
Tobias Thierer69b8b292017-04-11 22:16:53 +010031
Paul Jensen89bb9932018-03-29 07:41:43 -040032import libcore.io.IoUtils;
33
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070034import java.io.FileDescriptor;
Paul Jensen2d6f2652014-05-20 11:25:35 -040035import java.io.IOException;
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070036import java.net.DatagramSocket;
Paul Jensen3e32a4b2014-05-13 19:05:13 -040037import java.net.InetAddress;
Paul Jensen2d6f2652014-05-20 11:25:35 -040038import java.net.InetSocketAddress;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090039import java.net.MalformedURLException;
Robert Greenwalt85956262014-05-18 20:29:39 -070040import java.net.Socket;
Lorenzo Colittif0382892014-07-30 17:17:13 +090041import java.net.SocketAddress;
Paul Jensen32a58f02014-06-20 13:58:14 -040042import java.net.SocketException;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090043import java.net.URL;
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070044import java.net.URLConnection;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010045import java.net.UnknownHostException;
Tobias Thierer851d8062016-06-01 20:51:45 +010046import java.util.Arrays;
Tobias Thierer851d8062016-06-01 20:51:45 +010047import java.util.concurrent.TimeUnit;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010048
Robert Greenwalt85956262014-05-18 20:29:39 -070049import javax.net.SocketFactory;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070050
51/**
Robert Greenwalt85956262014-05-18 20:29:39 -070052 * Identifies a {@code Network}. This is supplied to applications via
Robert Greenwalt6078b502014-06-11 16:05:07 -070053 * {@link ConnectivityManager.NetworkCallback} in response to the active
54 * {@link ConnectivityManager#requestNetwork} or passive
55 * {@link ConnectivityManager#registerNetworkCallback} calls.
Robert Greenwalt85956262014-05-18 20:29:39 -070056 * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis
Paul Jensen0a363a32014-05-29 10:12:39 -040057 * through a targeted {@link SocketFactory} or process-wide via
Paul Jensen72db88e2015-03-10 10:54:12 -040058 * {@link ConnectivityManager#bindProcessToNetwork}.
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070059 */
60public class Network implements Parcelable {
61
Robert Greenwalt85956262014-05-18 20:29:39 -070062 /**
63 * @hide
64 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +010065 @UnsupportedAppUsage
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070066 public final int netId;
67
Lorenzo Colittic473dc42014-07-18 01:34:19 +090068 // Objects used to perform per-network operations such as getSocketFactory
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070069 // and openConnection, and a lock to protect access to them.
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +090070 private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null;
Tobias Thierer69b8b292017-04-11 22:16:53 +010071 // mLock should be used to control write access to mUrlConnectionFactory.
72 // maybeInitUrlConnectionFactory() must be called prior to reading this field.
73 private volatile HttpURLConnectionFactory mUrlConnectionFactory;
Erik Klined8959992015-06-05 17:37:45 +090074 private final Object mLock = new Object();
Paul Jensen2d6f2652014-05-20 11:25:35 -040075
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -070076 // Default connection pool values. These are evaluated at startup, just
77 // like the OkHttp code. Also like the OkHttp code, we will throw parse
78 // exceptions at class loading time if the properties are set but are not
79 // valid integers.
80 private static final boolean httpKeepAlive =
81 Boolean.parseBoolean(System.getProperty("http.keepAlive", "true"));
82 private static final int httpMaxConnections =
83 httpKeepAlive ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0;
84 private static final long httpKeepAliveDurationMs =
85 Long.parseLong(System.getProperty("http.keepAliveDuration", "300000")); // 5 minutes.
Paul Jensen4af17812018-03-28 09:19:58 -040086 // Value used to obfuscate network handle longs.
87 // The HANDLE_MAGIC value MUST be kept in sync with the corresponding
88 // value in the native/android/net.c NDK implementation.
89 private static final long HANDLE_MAGIC = 0xcafed00dL;
90 private static final int HANDLE_MAGIC_SIZE = 32;
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -070091
Erik Kline7eccfeb2018-05-22 21:15:49 +090092 // A boolean to control how getAllByName()/getByName() behaves in the face
93 // of Private DNS.
94 //
95 // When true, these calls will request that DNS resolution bypass any
96 // Private DNS that might otherwise apply. Use of this feature is restricted
97 // and permission checks are made by netd (attempts to bypass Private DNS
98 // without appropriate permission are silently turned into vanilla DNS
99 // requests). This only affects DNS queries made using this network object.
100 //
101 // It it not parceled to receivers because (a) it can be set or cleared at
102 // anytime and (b) receivers should be explicit about attempts to bypass
103 // Private DNS so that the intent of the code is easily determined and
104 // code search audits are possible.
Erik Klinef4fa9822018-04-27 22:48:33 +0900105 private final transient boolean mPrivateDnsBypass;
Erik Kline7eccfeb2018-05-22 21:15:49 +0900106
Robert Greenwalt85956262014-05-18 20:29:39 -0700107 /**
108 * @hide
109 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100110 @UnsupportedAppUsage
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700111 public Network(int netId) {
Erik Klinef4fa9822018-04-27 22:48:33 +0900112 this(netId, false);
113 }
114
115 /**
116 * @hide
117 */
118 public Network(int netId, boolean privateDnsBypass) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700119 this.netId = netId;
Erik Klinef4fa9822018-04-27 22:48:33 +0900120 this.mPrivateDnsBypass = privateDnsBypass;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700121 }
122
Robert Greenwalt85956262014-05-18 20:29:39 -0700123 /**
124 * @hide
125 */
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700126 public Network(Network that) {
Erik Klinef4fa9822018-04-27 22:48:33 +0900127 this(that.netId, that.mPrivateDnsBypass);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700128 }
129
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400130 /**
131 * Operates the same as {@code InetAddress.getAllByName} except that host
132 * resolution is done on this network.
133 *
134 * @param host the hostname or literal IP string to be resolved.
135 * @return the array of addresses associated with the specified host.
136 * @throws UnknownHostException if the address lookup fails.
137 */
138 public InetAddress[] getAllByName(String host) throws UnknownHostException {
Erik Kline7eccfeb2018-05-22 21:15:49 +0900139 return InetAddress.getAllByNameOnNet(host, getNetIdForResolv());
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400140 }
141
142 /**
143 * Operates the same as {@code InetAddress.getByName} except that host
144 * resolution is done on this network.
145 *
Erik Klinef4fa9822018-04-27 22:48:33 +0900146 * @param host the hostname to be resolved to an address or {@code null}.
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400147 * @return the {@code InetAddress} instance representing the host.
148 * @throws UnknownHostException
149 * if the address lookup fails.
150 */
151 public InetAddress getByName(String host) throws UnknownHostException {
Erik Kline7eccfeb2018-05-22 21:15:49 +0900152 return InetAddress.getByNameOnNet(host, getNetIdForResolv());
153 }
154
155 /**
Erik Klinef4fa9822018-04-27 22:48:33 +0900156 * Obtain a Network object for which Private DNS is to be bypassed when attempting
Chalard Jean68237442018-06-07 13:46:52 +0900157 * to use {@link #getAllByName(String)}/{@link #getByName(String)} methods on the given
Erik Kline7eccfeb2018-05-22 21:15:49 +0900158 * instance for hostname resolution.
159 *
160 * @hide
161 */
Remi NGUYEN VAN31f1d0c2019-01-20 12:52:43 +0900162 @TestApi
163 @SystemApi
Erik Klinef4fa9822018-04-27 22:48:33 +0900164 public Network getPrivateDnsBypassingCopy() {
165 return new Network(netId, true);
Erik Kline7eccfeb2018-05-22 21:15:49 +0900166 }
167
168 /**
169 * Returns a netid marked with the Private DNS bypass flag.
170 *
171 * This flag must be kept in sync with the NETID_USE_LOCAL_NAMESERVERS flag
172 * in system/netd/include/NetdClient.h.
173 *
174 * @hide
175 */
176 public int getNetIdForResolv() {
177 return mPrivateDnsBypass
178 ? (int) (0x80000000L | (long) netId) // Non-portable DNS resolution flag.
179 : netId;
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400180 }
181
Robert Greenwalt85956262014-05-18 20:29:39 -0700182 /**
Paul Jensen2d6f2652014-05-20 11:25:35 -0400183 * A {@code SocketFactory} that produces {@code Socket}'s bound to this network.
184 */
185 private class NetworkBoundSocketFactory extends SocketFactory {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900186 private Socket connectToHost(String host, int port, SocketAddress localAddress)
187 throws IOException {
Paul Jensen8ef34012014-05-27 10:19:39 -0400188 // Lookup addresses only on this Network.
189 InetAddress[] hostAddresses = getAllByName(host);
Lorenzo Colittif0382892014-07-30 17:17:13 +0900190 // Try all addresses.
191 for (int i = 0; i < hostAddresses.length; i++) {
Paul Jensen8ef34012014-05-27 10:19:39 -0400192 try {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900193 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400194 boolean failed = true;
195 try {
196 if (localAddress != null) socket.bind(localAddress);
197 socket.connect(new InetSocketAddress(hostAddresses[i], port));
198 failed = false;
199 return socket;
200 } finally {
201 if (failed) IoUtils.closeQuietly(socket);
202 }
Paul Jensen8ef34012014-05-27 10:19:39 -0400203 } catch (IOException e) {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900204 if (i == (hostAddresses.length - 1)) throw e;
Paul Jensen8ef34012014-05-27 10:19:39 -0400205 }
206 }
Lorenzo Colittif0382892014-07-30 17:17:13 +0900207 throw new UnknownHostException(host);
Paul Jensen8ef34012014-05-27 10:19:39 -0400208 }
209
Paul Jensen2d6f2652014-05-20 11:25:35 -0400210 @Override
Chalard Jean68237442018-06-07 13:46:52 +0900211 public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
212 throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900213 return connectToHost(host, port, new InetSocketAddress(localHost, localPort));
Paul Jensen2d6f2652014-05-20 11:25:35 -0400214 }
215
216 @Override
217 public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
218 int localPort) throws IOException {
219 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400220 boolean failed = true;
221 try {
222 socket.bind(new InetSocketAddress(localAddress, localPort));
223 socket.connect(new InetSocketAddress(address, port));
224 failed = false;
225 } finally {
226 if (failed) IoUtils.closeQuietly(socket);
227 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400228 return socket;
229 }
230
231 @Override
232 public Socket createSocket(InetAddress host, int port) throws IOException {
233 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400234 boolean failed = true;
235 try {
236 socket.connect(new InetSocketAddress(host, port));
237 failed = false;
238 } finally {
239 if (failed) IoUtils.closeQuietly(socket);
240 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400241 return socket;
242 }
243
244 @Override
245 public Socket createSocket(String host, int port) throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900246 return connectToHost(host, port, null);
Paul Jensen2d6f2652014-05-20 11:25:35 -0400247 }
248
249 @Override
250 public Socket createSocket() throws IOException {
251 Socket socket = new Socket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400252 boolean failed = true;
253 try {
254 bindSocket(socket);
255 failed = false;
256 } finally {
257 if (failed) IoUtils.closeQuietly(socket);
258 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400259 return socket;
260 }
261 }
262
263 /**
Robert Greenwalt85956262014-05-18 20:29:39 -0700264 * Returns a {@link SocketFactory} bound to this network. Any {@link Socket} created by
265 * this factory will have its traffic sent over this {@code Network}. Note that if this
266 * {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the
267 * past or future will cease to work.
268 *
269 * @return a {@link SocketFactory} which produces {@link Socket} instances bound to this
270 * {@code Network}.
271 */
Paul Jensen0a363a32014-05-29 10:12:39 -0400272 public SocketFactory getSocketFactory() {
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900273 if (mNetworkBoundSocketFactory == null) {
274 synchronized (mLock) {
275 if (mNetworkBoundSocketFactory == null) {
Chalard Jean68237442018-06-07 13:46:52 +0900276 mNetworkBoundSocketFactory = new NetworkBoundSocketFactory();
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900277 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900278 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400279 }
280 return mNetworkBoundSocketFactory;
Robert Greenwalt85956262014-05-18 20:29:39 -0700281 }
282
Paul Jensen07ed0742014-09-08 14:59:09 -0400283 // TODO: This creates a connection pool and host resolver for
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -0700284 // every Network object, instead of one for every NetId. This is
285 // suboptimal, because an app could potentially have more than one
286 // Network object for the same NetId, causing increased memory footprint
287 // and performance penalties due to lack of connection reuse (connection
288 // setup time, congestion window growth time, etc.).
289 //
Paul Jensen07ed0742014-09-08 14:59:09 -0400290 // Instead, investigate only having one connection pool and host resolver
291 // for every NetId, perhaps by using a static HashMap of NetIds to
292 // connection pools and host resolvers. The tricky part is deciding when
293 // to remove a map entry; a WeakHashMap shouldn't be used because whether
294 // a Network is referenced doesn't correlate with whether a new Network
295 // will be instantiated in the near future with the same NetID. A good
296 // solution would involve purging empty (or when all connections are timed
297 // out) ConnectionPools.
Tobias Thierer69b8b292017-04-11 22:16:53 +0100298 private void maybeInitUrlConnectionFactory() {
Paul Jensen07ed0742014-09-08 14:59:09 -0400299 synchronized (mLock) {
Tobias Thierer69b8b292017-04-11 22:16:53 +0100300 if (mUrlConnectionFactory == null) {
301 // Set configuration on the HttpURLConnectionFactory that will be good for all
302 // connections created by this Network. Configuration that might vary is left
303 // until openConnection() and passed as arguments.
304 Dns dnsLookup = hostname -> Arrays.asList(Network.this.getAllByName(hostname));
305 HttpURLConnectionFactory urlConnectionFactory = new HttpURLConnectionFactory();
306 urlConnectionFactory.setDns(dnsLookup); // Let traffic go via dnsLookup
307 // A private connection pool just for this Network.
308 urlConnectionFactory.setNewConnectionPool(httpMaxConnections,
Tobias Thierer851d8062016-06-01 20:51:45 +0100309 httpKeepAliveDurationMs, TimeUnit.MILLISECONDS);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100310 mUrlConnectionFactory = urlConnectionFactory;
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900311 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900312 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900313 }
314
315 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700316 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
317 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
318 *
319 * @return a {@code URLConnection} to the resource referred to by this URL.
320 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
321 * @throws IOException if an error occurs while opening the connection.
322 * @see java.net.URL#openConnection()
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900323 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700324 public URLConnection openConnection(URL url) throws IOException {
Paul Jensen72db88e2015-03-10 10:54:12 -0400325 final ConnectivityManager cm = ConnectivityManager.getInstanceOrNull();
326 if (cm == null) {
327 throw new IOException("No ConnectivityManager yet constructed, please construct one");
328 }
Paul Jensene0bef712014-12-10 15:12:18 -0500329 // TODO: Should this be optimized to avoid fetching the global proxy for every request?
Paul Jensencee9b512015-05-06 07:32:40 -0400330 final ProxyInfo proxyInfo = cm.getProxyForNetwork(this);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100331 final java.net.Proxy proxy;
Paul Jensene0bef712014-12-10 15:12:18 -0500332 if (proxyInfo != null) {
333 proxy = proxyInfo.makeProxy();
334 } else {
335 proxy = java.net.Proxy.NO_PROXY;
336 }
337 return openConnection(url, proxy);
338 }
339
340 /**
341 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
342 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
343 *
344 * @param proxy the proxy through which the connection will be established.
345 * @return a {@code URLConnection} to the resource referred to by this URL.
346 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
347 * @throws IllegalArgumentException if the argument proxy is null.
348 * @throws IOException if an error occurs while opening the connection.
349 * @see java.net.URL#openConnection()
Paul Jensene0bef712014-12-10 15:12:18 -0500350 */
351 public URLConnection openConnection(URL url, java.net.Proxy proxy) throws IOException {
352 if (proxy == null) throw new IllegalArgumentException("proxy is null");
Tobias Thierer69b8b292017-04-11 22:16:53 +0100353 maybeInitUrlConnectionFactory();
354 SocketFactory socketFactory = getSocketFactory();
355 return mUrlConnectionFactory.openConnection(url, socketFactory, proxy);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700356 }
357
358 /**
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700359 * Binds the specified {@link DatagramSocket} to this {@code Network}. All data traffic on the
360 * socket will be sent on this {@code Network}, irrespective of any process-wide network binding
Paul Jensen72db88e2015-03-10 10:54:12 -0400361 * set by {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700362 * connected.
363 */
364 public void bindSocket(DatagramSocket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700365 // Query a property of the underlying socket to ensure that the socket's file descriptor
366 // exists, is available to bind to a network and is not closed.
367 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900368 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700369 }
370
371 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700372 * Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket
373 * will be sent on this {@code Network}, irrespective of any process-wide network binding set by
Paul Jensen72db88e2015-03-10 10:54:12 -0400374 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700375 */
376 public void bindSocket(Socket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700377 // Query a property of the underlying socket to ensure that the socket's file descriptor
378 // exists, is available to bind to a network and is not closed.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700379 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900380 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700381 }
382
Erik Klined8959992015-06-05 17:37:45 +0900383 /**
384 * Binds the specified {@link FileDescriptor} to this {@code Network}. All data traffic on the
385 * socket represented by this file descriptor will be sent on this {@code Network},
386 * irrespective of any process-wide network binding set by
387 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
388 */
389 public void bindSocket(FileDescriptor fd) throws IOException {
390 try {
391 final SocketAddress peer = Os.getpeername(fd);
392 final InetAddress inetPeer = ((InetSocketAddress) peer).getAddress();
393 if (!inetPeer.isAnyLocalAddress()) {
394 // Apparently, the kernel doesn't update a connected UDP socket's
395 // routing upon mark changes.
396 throw new SocketException("Socket is connected");
397 }
398 } catch (ErrnoException e) {
399 // getpeername() failed.
400 if (e.errno != OsConstants.ENOTCONN) {
401 throw e.rethrowAsSocketException();
402 }
403 } catch (ClassCastException e) {
404 // Wasn't an InetSocketAddress.
405 throw new SocketException("Only AF_INET/AF_INET6 sockets supported");
406 }
407
408 final int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700409 if (err != 0) {
410 // bindSocketToNetwork returns negative errno.
411 throw new ErrnoException("Binding socket to network " + netId, -err)
412 .rethrowAsSocketException();
413 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900414 }
415
Erik Kline25f3b7b2015-03-05 15:13:37 +0900416 /**
Paul Jensen4af17812018-03-28 09:19:58 -0400417 * Returns a {@link Network} object given a handle returned from {@link #getNetworkHandle}.
418 *
419 * @param networkHandle a handle returned from {@link #getNetworkHandle}.
420 * @return A {@link Network} object derived from {@code networkHandle}.
421 */
422 public static Network fromNetworkHandle(long networkHandle) {
423 if (networkHandle == 0) {
424 throw new IllegalArgumentException(
425 "Network.fromNetworkHandle refusing to instantiate NETID_UNSET Network.");
426 }
427 if ((networkHandle & ((1L << HANDLE_MAGIC_SIZE) - 1)) != HANDLE_MAGIC
428 || networkHandle < 0) {
429 throw new IllegalArgumentException(
430 "Value passed to fromNetworkHandle() is not a network handle.");
431 }
432 return new Network((int) (networkHandle >> HANDLE_MAGIC_SIZE));
433 }
434
435 /**
Erik Kline25f3b7b2015-03-05 15:13:37 +0900436 * Returns a handle representing this {@code Network}, for use with the NDK API.
437 */
438 public long getNetworkHandle() {
439 // The network handle is explicitly not the same as the netId.
440 //
441 // The netId is an implementation detail which might be changed in the
442 // future, or which alone (i.e. in the absence of some additional
443 // context) might not be sufficient to fully identify a Network.
444 //
445 // As such, the intention is to prevent accidental misuse of the API
446 // that might result if a developer assumed that handles and netIds
447 // were identical and passing a netId to a call expecting a handle
448 // "just worked". Such accidental misuse, if widely deployed, might
449 // prevent future changes to the semantics of the netId field or
450 // inhibit the expansion of state required for Network objects.
451 //
452 // This extra layer of indirection might be seen as paranoia, and might
453 // never end up being necessary, but the added complexity is trivial.
454 // At some future date it may be desirable to realign the handle with
455 // Multiple Provisioning Domains API recommendations, as made by the
456 // IETF mif working group.
Erik Klinee1a6cf22015-05-14 15:40:07 +0900457 if (netId == 0) {
458 return 0L; // make this zero condition obvious for debugging
459 }
Paul Jensen4af17812018-03-28 09:19:58 -0400460 return (((long) netId) << HANDLE_MAGIC_SIZE) | HANDLE_MAGIC;
Erik Kline25f3b7b2015-03-05 15:13:37 +0900461 }
462
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700463 // implement the Parcelable interface
464 public int describeContents() {
465 return 0;
466 }
467 public void writeToParcel(Parcel dest, int flags) {
468 dest.writeInt(netId);
469 }
470
471 public static final Creator<Network> CREATOR =
472 new Creator<Network>() {
473 public Network createFromParcel(Parcel in) {
474 int netId = in.readInt();
475
476 return new Network(netId);
477 }
478
479 public Network[] newArray(int size) {
480 return new Network[size];
481 }
482 };
Robert Greenwalt85956262014-05-18 20:29:39 -0700483
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700484 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700485 public boolean equals(Object obj) {
Chalard Jean68237442018-06-07 13:46:52 +0900486 if (!(obj instanceof Network)) return false;
Robert Greenwalt85956262014-05-18 20:29:39 -0700487 Network other = (Network)obj;
488 return this.netId == other.netId;
489 }
490
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700491 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700492 public int hashCode() {
493 return netId * 11;
494 }
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700495
496 @Override
497 public String toString() {
498 return Integer.toString(netId);
499 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800500
501 /** @hide */
502 public void writeToProto(ProtoOutputStream proto, long fieldId) {
503 final long token = proto.start(fieldId);
504 proto.write(NetworkProto.NET_ID, netId);
505 proto.end(token);
506 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700507}