blob: d75d4391dee306420d74ab195ed0afcbabdfeaa8 [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
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070019import android.os.Parcel;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010020import android.os.Parcelable;
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070021import android.system.ErrnoException;
Erik Klined8959992015-06-05 17:37:45 +090022import android.system.Os;
23import android.system.OsConstants;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080024import android.util.proto.ProtoOutputStream;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070025
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010026import com.android.okhttp.internalandroidapi.Dns;
27import com.android.okhttp.internalandroidapi.HttpURLConnectionFactory;
Tobias Thierer69b8b292017-04-11 22:16:53 +010028
Paul Jensen89bb9932018-03-29 07:41:43 -040029import libcore.io.IoUtils;
30
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070031import java.io.FileDescriptor;
Paul Jensen2d6f2652014-05-20 11:25:35 -040032import java.io.IOException;
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070033import java.net.DatagramSocket;
Paul Jensen3e32a4b2014-05-13 19:05:13 -040034import java.net.InetAddress;
Paul Jensen2d6f2652014-05-20 11:25:35 -040035import java.net.InetSocketAddress;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090036import java.net.MalformedURLException;
Robert Greenwalt85956262014-05-18 20:29:39 -070037import java.net.Socket;
Lorenzo Colittif0382892014-07-30 17:17:13 +090038import java.net.SocketAddress;
Paul Jensen32a58f02014-06-20 13:58:14 -040039import java.net.SocketException;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090040import java.net.URL;
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070041import java.net.URLConnection;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010042import java.net.UnknownHostException;
Tobias Thierer851d8062016-06-01 20:51:45 +010043import java.util.Arrays;
Tobias Thierer851d8062016-06-01 20:51:45 +010044import java.util.concurrent.TimeUnit;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010045
Robert Greenwalt85956262014-05-18 20:29:39 -070046import javax.net.SocketFactory;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070047
48/**
Robert Greenwalt85956262014-05-18 20:29:39 -070049 * Identifies a {@code Network}. This is supplied to applications via
Robert Greenwalt6078b502014-06-11 16:05:07 -070050 * {@link ConnectivityManager.NetworkCallback} in response to the active
51 * {@link ConnectivityManager#requestNetwork} or passive
52 * {@link ConnectivityManager#registerNetworkCallback} calls.
Robert Greenwalt85956262014-05-18 20:29:39 -070053 * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis
Paul Jensen0a363a32014-05-29 10:12:39 -040054 * through a targeted {@link SocketFactory} or process-wide via
Paul Jensen72db88e2015-03-10 10:54:12 -040055 * {@link ConnectivityManager#bindProcessToNetwork}.
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056 */
57public class Network implements Parcelable {
58
Robert Greenwalt85956262014-05-18 20:29:39 -070059 /**
60 * @hide
61 */
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070062 public final int netId;
63
Lorenzo Colittic473dc42014-07-18 01:34:19 +090064 // Objects used to perform per-network operations such as getSocketFactory
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070065 // and openConnection, and a lock to protect access to them.
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +090066 private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null;
Tobias Thierer69b8b292017-04-11 22:16:53 +010067 // mLock should be used to control write access to mUrlConnectionFactory.
68 // maybeInitUrlConnectionFactory() must be called prior to reading this field.
69 private volatile HttpURLConnectionFactory mUrlConnectionFactory;
Erik Klined8959992015-06-05 17:37:45 +090070 private final Object mLock = new Object();
Paul Jensen2d6f2652014-05-20 11:25:35 -040071
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -070072 // Default connection pool values. These are evaluated at startup, just
73 // like the OkHttp code. Also like the OkHttp code, we will throw parse
74 // exceptions at class loading time if the properties are set but are not
75 // valid integers.
76 private static final boolean httpKeepAlive =
77 Boolean.parseBoolean(System.getProperty("http.keepAlive", "true"));
78 private static final int httpMaxConnections =
79 httpKeepAlive ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0;
80 private static final long httpKeepAliveDurationMs =
81 Long.parseLong(System.getProperty("http.keepAliveDuration", "300000")); // 5 minutes.
Paul Jensen4af17812018-03-28 09:19:58 -040082 // Value used to obfuscate network handle longs.
83 // The HANDLE_MAGIC value MUST be kept in sync with the corresponding
84 // value in the native/android/net.c NDK implementation.
85 private static final long HANDLE_MAGIC = 0xcafed00dL;
86 private static final int HANDLE_MAGIC_SIZE = 32;
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -070087
Erik Kline7eccfeb2018-05-22 21:15:49 +090088 // A boolean to control how getAllByName()/getByName() behaves in the face
89 // of Private DNS.
90 //
91 // When true, these calls will request that DNS resolution bypass any
92 // Private DNS that might otherwise apply. Use of this feature is restricted
93 // and permission checks are made by netd (attempts to bypass Private DNS
94 // without appropriate permission are silently turned into vanilla DNS
95 // requests). This only affects DNS queries made using this network object.
96 //
97 // It it not parceled to receivers because (a) it can be set or cleared at
98 // anytime and (b) receivers should be explicit about attempts to bypass
99 // Private DNS so that the intent of the code is easily determined and
100 // code search audits are possible.
101 private boolean mPrivateDnsBypass = false;
102
Robert Greenwalt85956262014-05-18 20:29:39 -0700103 /**
104 * @hide
105 */
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700106 public Network(int netId) {
107 this.netId = netId;
108 }
109
Robert Greenwalt85956262014-05-18 20:29:39 -0700110 /**
111 * @hide
112 */
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700113 public Network(Network that) {
114 this.netId = that.netId;
115 }
116
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400117 /**
118 * Operates the same as {@code InetAddress.getAllByName} except that host
119 * resolution is done on this network.
120 *
121 * @param host the hostname or literal IP string to be resolved.
122 * @return the array of addresses associated with the specified host.
123 * @throws UnknownHostException if the address lookup fails.
124 */
125 public InetAddress[] getAllByName(String host) throws UnknownHostException {
Erik Kline7eccfeb2018-05-22 21:15:49 +0900126 return InetAddress.getAllByNameOnNet(host, getNetIdForResolv());
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400127 }
128
129 /**
130 * Operates the same as {@code InetAddress.getByName} except that host
131 * resolution is done on this network.
132 *
133 * @param host
134 * the hostName to be resolved to an address or {@code null}.
135 * @return the {@code InetAddress} instance representing the host.
136 * @throws UnknownHostException
137 * if the address lookup fails.
138 */
139 public InetAddress getByName(String host) throws UnknownHostException {
Erik Kline7eccfeb2018-05-22 21:15:49 +0900140 return InetAddress.getByNameOnNet(host, getNetIdForResolv());
141 }
142
143 /**
144 * Specify whether or not Private DNS should be bypassed when attempting
145 * to use {@link getAllByName()}/{@link getByName()} methods on the given
146 * instance for hostname resolution.
147 *
148 * @hide
149 */
150 public void setPrivateDnsBypass(boolean bypass) {
151 mPrivateDnsBypass = bypass;
152 }
153
154 /**
155 * Returns a netid marked with the Private DNS bypass flag.
156 *
157 * This flag must be kept in sync with the NETID_USE_LOCAL_NAMESERVERS flag
158 * in system/netd/include/NetdClient.h.
159 *
160 * @hide
161 */
162 public int getNetIdForResolv() {
163 return mPrivateDnsBypass
164 ? (int) (0x80000000L | (long) netId) // Non-portable DNS resolution flag.
165 : netId;
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400166 }
167
Robert Greenwalt85956262014-05-18 20:29:39 -0700168 /**
Paul Jensen2d6f2652014-05-20 11:25:35 -0400169 * A {@code SocketFactory} that produces {@code Socket}'s bound to this network.
170 */
171 private class NetworkBoundSocketFactory extends SocketFactory {
172 private final int mNetId;
173
174 public NetworkBoundSocketFactory(int netId) {
175 super();
176 mNetId = netId;
177 }
178
Lorenzo Colittif0382892014-07-30 17:17:13 +0900179 private Socket connectToHost(String host, int port, SocketAddress localAddress)
180 throws IOException {
Paul Jensen8ef34012014-05-27 10:19:39 -0400181 // Lookup addresses only on this Network.
182 InetAddress[] hostAddresses = getAllByName(host);
Lorenzo Colittif0382892014-07-30 17:17:13 +0900183 // Try all addresses.
184 for (int i = 0; i < hostAddresses.length; i++) {
Paul Jensen8ef34012014-05-27 10:19:39 -0400185 try {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900186 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400187 boolean failed = true;
188 try {
189 if (localAddress != null) socket.bind(localAddress);
190 socket.connect(new InetSocketAddress(hostAddresses[i], port));
191 failed = false;
192 return socket;
193 } finally {
194 if (failed) IoUtils.closeQuietly(socket);
195 }
Paul Jensen8ef34012014-05-27 10:19:39 -0400196 } catch (IOException e) {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900197 if (i == (hostAddresses.length - 1)) throw e;
Paul Jensen8ef34012014-05-27 10:19:39 -0400198 }
199 }
Lorenzo Colittif0382892014-07-30 17:17:13 +0900200 throw new UnknownHostException(host);
Paul Jensen8ef34012014-05-27 10:19:39 -0400201 }
202
Paul Jensen2d6f2652014-05-20 11:25:35 -0400203 @Override
204 public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900205 return connectToHost(host, port, new InetSocketAddress(localHost, localPort));
Paul Jensen2d6f2652014-05-20 11:25:35 -0400206 }
207
208 @Override
209 public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
210 int localPort) throws IOException {
211 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400212 boolean failed = true;
213 try {
214 socket.bind(new InetSocketAddress(localAddress, localPort));
215 socket.connect(new InetSocketAddress(address, port));
216 failed = false;
217 } finally {
218 if (failed) IoUtils.closeQuietly(socket);
219 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400220 return socket;
221 }
222
223 @Override
224 public Socket createSocket(InetAddress host, int port) throws IOException {
225 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400226 boolean failed = true;
227 try {
228 socket.connect(new InetSocketAddress(host, port));
229 failed = false;
230 } finally {
231 if (failed) IoUtils.closeQuietly(socket);
232 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400233 return socket;
234 }
235
236 @Override
237 public Socket createSocket(String host, int port) throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900238 return connectToHost(host, port, null);
Paul Jensen2d6f2652014-05-20 11:25:35 -0400239 }
240
241 @Override
242 public Socket createSocket() throws IOException {
243 Socket socket = new Socket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400244 boolean failed = true;
245 try {
246 bindSocket(socket);
247 failed = false;
248 } finally {
249 if (failed) IoUtils.closeQuietly(socket);
250 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400251 return socket;
252 }
253 }
254
255 /**
Robert Greenwalt85956262014-05-18 20:29:39 -0700256 * Returns a {@link SocketFactory} bound to this network. Any {@link Socket} created by
257 * this factory will have its traffic sent over this {@code Network}. Note that if this
258 * {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the
259 * past or future will cease to work.
260 *
261 * @return a {@link SocketFactory} which produces {@link Socket} instances bound to this
262 * {@code Network}.
263 */
Paul Jensen0a363a32014-05-29 10:12:39 -0400264 public SocketFactory getSocketFactory() {
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900265 if (mNetworkBoundSocketFactory == null) {
266 synchronized (mLock) {
267 if (mNetworkBoundSocketFactory == null) {
268 mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId);
269 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900270 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400271 }
272 return mNetworkBoundSocketFactory;
Robert Greenwalt85956262014-05-18 20:29:39 -0700273 }
274
Paul Jensen07ed0742014-09-08 14:59:09 -0400275 // TODO: This creates a connection pool and host resolver for
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -0700276 // every Network object, instead of one for every NetId. This is
277 // suboptimal, because an app could potentially have more than one
278 // Network object for the same NetId, causing increased memory footprint
279 // and performance penalties due to lack of connection reuse (connection
280 // setup time, congestion window growth time, etc.).
281 //
Paul Jensen07ed0742014-09-08 14:59:09 -0400282 // Instead, investigate only having one connection pool and host resolver
283 // for every NetId, perhaps by using a static HashMap of NetIds to
284 // connection pools and host resolvers. The tricky part is deciding when
285 // to remove a map entry; a WeakHashMap shouldn't be used because whether
286 // a Network is referenced doesn't correlate with whether a new Network
287 // will be instantiated in the near future with the same NetID. A good
288 // solution would involve purging empty (or when all connections are timed
289 // out) ConnectionPools.
Tobias Thierer69b8b292017-04-11 22:16:53 +0100290 private void maybeInitUrlConnectionFactory() {
Paul Jensen07ed0742014-09-08 14:59:09 -0400291 synchronized (mLock) {
Tobias Thierer69b8b292017-04-11 22:16:53 +0100292 if (mUrlConnectionFactory == null) {
293 // Set configuration on the HttpURLConnectionFactory that will be good for all
294 // connections created by this Network. Configuration that might vary is left
295 // until openConnection() and passed as arguments.
296 Dns dnsLookup = hostname -> Arrays.asList(Network.this.getAllByName(hostname));
297 HttpURLConnectionFactory urlConnectionFactory = new HttpURLConnectionFactory();
298 urlConnectionFactory.setDns(dnsLookup); // Let traffic go via dnsLookup
299 // A private connection pool just for this Network.
300 urlConnectionFactory.setNewConnectionPool(httpMaxConnections,
Tobias Thierer851d8062016-06-01 20:51:45 +0100301 httpKeepAliveDurationMs, TimeUnit.MILLISECONDS);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100302 mUrlConnectionFactory = urlConnectionFactory;
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900303 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900304 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900305 }
306
307 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700308 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
309 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
310 *
311 * @return a {@code URLConnection} to the resource referred to by this URL.
312 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
313 * @throws IOException if an error occurs while opening the connection.
314 * @see java.net.URL#openConnection()
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900315 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700316 public URLConnection openConnection(URL url) throws IOException {
Paul Jensen72db88e2015-03-10 10:54:12 -0400317 final ConnectivityManager cm = ConnectivityManager.getInstanceOrNull();
318 if (cm == null) {
319 throw new IOException("No ConnectivityManager yet constructed, please construct one");
320 }
Paul Jensene0bef712014-12-10 15:12:18 -0500321 // TODO: Should this be optimized to avoid fetching the global proxy for every request?
Paul Jensencee9b512015-05-06 07:32:40 -0400322 final ProxyInfo proxyInfo = cm.getProxyForNetwork(this);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100323 final java.net.Proxy proxy;
Paul Jensene0bef712014-12-10 15:12:18 -0500324 if (proxyInfo != null) {
325 proxy = proxyInfo.makeProxy();
326 } else {
327 proxy = java.net.Proxy.NO_PROXY;
328 }
329 return openConnection(url, proxy);
330 }
331
332 /**
333 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
334 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
335 *
336 * @param proxy the proxy through which the connection will be established.
337 * @return a {@code URLConnection} to the resource referred to by this URL.
338 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
339 * @throws IllegalArgumentException if the argument proxy is null.
340 * @throws IOException if an error occurs while opening the connection.
341 * @see java.net.URL#openConnection()
Paul Jensene0bef712014-12-10 15:12:18 -0500342 */
343 public URLConnection openConnection(URL url, java.net.Proxy proxy) throws IOException {
344 if (proxy == null) throw new IllegalArgumentException("proxy is null");
Tobias Thierer69b8b292017-04-11 22:16:53 +0100345 maybeInitUrlConnectionFactory();
346 SocketFactory socketFactory = getSocketFactory();
347 return mUrlConnectionFactory.openConnection(url, socketFactory, proxy);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700348 }
349
350 /**
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700351 * Binds the specified {@link DatagramSocket} to this {@code Network}. All data traffic on the
352 * socket will be sent on this {@code Network}, irrespective of any process-wide network binding
Paul Jensen72db88e2015-03-10 10:54:12 -0400353 * set by {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700354 * connected.
355 */
356 public void bindSocket(DatagramSocket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700357 // Query a property of the underlying socket to ensure that the socket's file descriptor
358 // exists, is available to bind to a network and is not closed.
359 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900360 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700361 }
362
363 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700364 * Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket
365 * will be sent on this {@code Network}, irrespective of any process-wide network binding set by
Paul Jensen72db88e2015-03-10 10:54:12 -0400366 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700367 */
368 public void bindSocket(Socket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700369 // Query a property of the underlying socket to ensure that the socket's file descriptor
370 // exists, is available to bind to a network and is not closed.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700371 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900372 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700373 }
374
Erik Klined8959992015-06-05 17:37:45 +0900375 /**
376 * Binds the specified {@link FileDescriptor} to this {@code Network}. All data traffic on the
377 * socket represented by this file descriptor will be sent on this {@code Network},
378 * irrespective of any process-wide network binding set by
379 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
380 */
381 public void bindSocket(FileDescriptor fd) throws IOException {
382 try {
383 final SocketAddress peer = Os.getpeername(fd);
384 final InetAddress inetPeer = ((InetSocketAddress) peer).getAddress();
385 if (!inetPeer.isAnyLocalAddress()) {
386 // Apparently, the kernel doesn't update a connected UDP socket's
387 // routing upon mark changes.
388 throw new SocketException("Socket is connected");
389 }
390 } catch (ErrnoException e) {
391 // getpeername() failed.
392 if (e.errno != OsConstants.ENOTCONN) {
393 throw e.rethrowAsSocketException();
394 }
395 } catch (ClassCastException e) {
396 // Wasn't an InetSocketAddress.
397 throw new SocketException("Only AF_INET/AF_INET6 sockets supported");
398 }
399
400 final int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700401 if (err != 0) {
402 // bindSocketToNetwork returns negative errno.
403 throw new ErrnoException("Binding socket to network " + netId, -err)
404 .rethrowAsSocketException();
405 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900406 }
407
Erik Kline25f3b7b2015-03-05 15:13:37 +0900408 /**
Paul Jensen4af17812018-03-28 09:19:58 -0400409 * Returns a {@link Network} object given a handle returned from {@link #getNetworkHandle}.
410 *
411 * @param networkHandle a handle returned from {@link #getNetworkHandle}.
412 * @return A {@link Network} object derived from {@code networkHandle}.
413 */
414 public static Network fromNetworkHandle(long networkHandle) {
415 if (networkHandle == 0) {
416 throw new IllegalArgumentException(
417 "Network.fromNetworkHandle refusing to instantiate NETID_UNSET Network.");
418 }
419 if ((networkHandle & ((1L << HANDLE_MAGIC_SIZE) - 1)) != HANDLE_MAGIC
420 || networkHandle < 0) {
421 throw new IllegalArgumentException(
422 "Value passed to fromNetworkHandle() is not a network handle.");
423 }
424 return new Network((int) (networkHandle >> HANDLE_MAGIC_SIZE));
425 }
426
427 /**
Erik Kline25f3b7b2015-03-05 15:13:37 +0900428 * Returns a handle representing this {@code Network}, for use with the NDK API.
429 */
430 public long getNetworkHandle() {
431 // The network handle is explicitly not the same as the netId.
432 //
433 // The netId is an implementation detail which might be changed in the
434 // future, or which alone (i.e. in the absence of some additional
435 // context) might not be sufficient to fully identify a Network.
436 //
437 // As such, the intention is to prevent accidental misuse of the API
438 // that might result if a developer assumed that handles and netIds
439 // were identical and passing a netId to a call expecting a handle
440 // "just worked". Such accidental misuse, if widely deployed, might
441 // prevent future changes to the semantics of the netId field or
442 // inhibit the expansion of state required for Network objects.
443 //
444 // This extra layer of indirection might be seen as paranoia, and might
445 // never end up being necessary, but the added complexity is trivial.
446 // At some future date it may be desirable to realign the handle with
447 // Multiple Provisioning Domains API recommendations, as made by the
448 // IETF mif working group.
Erik Klinee1a6cf22015-05-14 15:40:07 +0900449 if (netId == 0) {
450 return 0L; // make this zero condition obvious for debugging
451 }
Paul Jensen4af17812018-03-28 09:19:58 -0400452 return (((long) netId) << HANDLE_MAGIC_SIZE) | HANDLE_MAGIC;
Erik Kline25f3b7b2015-03-05 15:13:37 +0900453 }
454
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700455 // implement the Parcelable interface
456 public int describeContents() {
457 return 0;
458 }
459 public void writeToParcel(Parcel dest, int flags) {
460 dest.writeInt(netId);
461 }
462
463 public static final Creator<Network> CREATOR =
464 new Creator<Network>() {
465 public Network createFromParcel(Parcel in) {
466 int netId = in.readInt();
467
468 return new Network(netId);
469 }
470
471 public Network[] newArray(int size) {
472 return new Network[size];
473 }
474 };
Robert Greenwalt85956262014-05-18 20:29:39 -0700475
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700476 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700477 public boolean equals(Object obj) {
478 if (obj instanceof Network == false) return false;
479 Network other = (Network)obj;
480 return this.netId == other.netId;
481 }
482
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700483 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700484 public int hashCode() {
485 return netId * 11;
486 }
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700487
488 @Override
489 public String toString() {
490 return Integer.toString(netId);
491 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800492
493 /** @hide */
494 public void writeToProto(ProtoOutputStream proto, long fieldId) {
495 final long token = proto.start(fieldId);
496 proto.write(NetworkProto.NET_ID, netId);
497 proto.end(token);
498 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700499}