blob: f807a4968d7254d0a5844e9d2d48e35b69c8cf36 [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
paulhud9736de2019-03-08 16:35:20 +080019import android.annotation.NonNull;
Remi NGUYEN VAN31f1d0c2019-01-20 12:52:43 +090020import android.annotation.SystemApi;
21import android.annotation.TestApi;
Artur Satayev26958002019-12-10 17:47:52 +000022import android.compat.annotation.UnsupportedAppUsage;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070023import android.os.Parcel;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010024import android.os.Parcelable;
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070025import android.system.ErrnoException;
Erik Klined8959992015-06-05 17:37:45 +090026import android.system.Os;
27import android.system.OsConstants;
Kweku Adams85f2fbc2017-12-18 12:04:12 -080028import android.util.proto.ProtoOutputStream;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070029
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010030import com.android.okhttp.internalandroidapi.Dns;
31import com.android.okhttp.internalandroidapi.HttpURLConnectionFactory;
Tobias Thierer69b8b292017-04-11 22:16:53 +010032
Paul Jensen89bb9932018-03-29 07:41:43 -040033import libcore.io.IoUtils;
34
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070035import java.io.FileDescriptor;
Paul Jensen2d6f2652014-05-20 11:25:35 -040036import java.io.IOException;
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070037import java.net.DatagramSocket;
Paul Jensen3e32a4b2014-05-13 19:05:13 -040038import java.net.InetAddress;
Paul Jensen2d6f2652014-05-20 11:25:35 -040039import java.net.InetSocketAddress;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090040import java.net.MalformedURLException;
Robert Greenwalt85956262014-05-18 20:29:39 -070041import java.net.Socket;
Lorenzo Colittif0382892014-07-30 17:17:13 +090042import java.net.SocketAddress;
Paul Jensen32a58f02014-06-20 13:58:14 -040043import java.net.SocketException;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090044import java.net.URL;
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070045import java.net.URLConnection;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010046import java.net.UnknownHostException;
Tobias Thierer851d8062016-06-01 20:51:45 +010047import java.util.Arrays;
Tobias Thierer851d8062016-06-01 20:51:45 +010048import java.util.concurrent.TimeUnit;
Tobias Thierer4c6d2ec2017-10-25 00:58:29 +010049
Robert Greenwalt85956262014-05-18 20:29:39 -070050import javax.net.SocketFactory;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070051
52/**
Robert Greenwalt85956262014-05-18 20:29:39 -070053 * Identifies a {@code Network}. This is supplied to applications via
Robert Greenwalt6078b502014-06-11 16:05:07 -070054 * {@link ConnectivityManager.NetworkCallback} in response to the active
55 * {@link ConnectivityManager#requestNetwork} or passive
56 * {@link ConnectivityManager#registerNetworkCallback} calls.
Robert Greenwalt85956262014-05-18 20:29:39 -070057 * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis
Paul Jensen0a363a32014-05-29 10:12:39 -040058 * through a targeted {@link SocketFactory} or process-wide via
Paul Jensen72db88e2015-03-10 10:54:12 -040059 * {@link ConnectivityManager#bindProcessToNetwork}.
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070060 */
61public class Network implements Parcelable {
62
Robert Greenwalt85956262014-05-18 20:29:39 -070063 /**
Automerger Merge Workerf75c46a2020-03-12 11:12:31 +000064 * The unique id of the network.
Robert Greenwalt85956262014-05-18 20:29:39 -070065 * @hide
66 */
markchien587ecb32020-03-18 08:43:07 +080067 @UnsupportedAppUsage
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070068 public final int netId;
69
Lorenzo Colittic473dc42014-07-18 01:34:19 +090070 // Objects used to perform per-network operations such as getSocketFactory
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070071 // and openConnection, and a lock to protect access to them.
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +090072 private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null;
Tobias Thierer69b8b292017-04-11 22:16:53 +010073 // mLock should be used to control write access to mUrlConnectionFactory.
74 // maybeInitUrlConnectionFactory() must be called prior to reading this field.
75 private volatile HttpURLConnectionFactory mUrlConnectionFactory;
Erik Klined8959992015-06-05 17:37:45 +090076 private final Object mLock = new Object();
Paul Jensen2d6f2652014-05-20 11:25:35 -040077
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -070078 // Default connection pool values. These are evaluated at startup, just
79 // like the OkHttp code. Also like the OkHttp code, we will throw parse
80 // exceptions at class loading time if the properties are set but are not
81 // valid integers.
82 private static final boolean httpKeepAlive =
83 Boolean.parseBoolean(System.getProperty("http.keepAlive", "true"));
84 private static final int httpMaxConnections =
85 httpKeepAlive ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0;
86 private static final long httpKeepAliveDurationMs =
87 Long.parseLong(System.getProperty("http.keepAliveDuration", "300000")); // 5 minutes.
Paul Jensen4af17812018-03-28 09:19:58 -040088 // Value used to obfuscate network handle longs.
89 // The HANDLE_MAGIC value MUST be kept in sync with the corresponding
90 // value in the native/android/net.c NDK implementation.
91 private static final long HANDLE_MAGIC = 0xcafed00dL;
92 private static final int HANDLE_MAGIC_SIZE = 32;
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -070093
Erik Kline7eccfeb2018-05-22 21:15:49 +090094 // A boolean to control how getAllByName()/getByName() behaves in the face
95 // of Private DNS.
96 //
97 // When true, these calls will request that DNS resolution bypass any
98 // Private DNS that might otherwise apply. Use of this feature is restricted
99 // and permission checks are made by netd (attempts to bypass Private DNS
100 // without appropriate permission are silently turned into vanilla DNS
101 // requests). This only affects DNS queries made using this network object.
102 //
103 // It it not parceled to receivers because (a) it can be set or cleared at
104 // anytime and (b) receivers should be explicit about attempts to bypass
105 // Private DNS so that the intent of the code is easily determined and
106 // code search audits are possible.
Erik Klinef4fa9822018-04-27 22:48:33 +0900107 private final transient boolean mPrivateDnsBypass;
Erik Kline7eccfeb2018-05-22 21:15:49 +0900108
Robert Greenwalt85956262014-05-18 20:29:39 -0700109 /**
110 * @hide
111 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100112 @UnsupportedAppUsage
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700113 public Network(int netId) {
Erik Klinef4fa9822018-04-27 22:48:33 +0900114 this(netId, false);
115 }
116
117 /**
118 * @hide
119 */
120 public Network(int netId, boolean privateDnsBypass) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700121 this.netId = netId;
Erik Klinef4fa9822018-04-27 22:48:33 +0900122 this.mPrivateDnsBypass = privateDnsBypass;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700123 }
124
Robert Greenwalt85956262014-05-18 20:29:39 -0700125 /**
126 * @hide
127 */
Remi NGUYEN VAN5c5f1ba2019-01-29 12:08:43 +0900128 @SystemApi
129 @TestApi
paulhud9736de2019-03-08 16:35:20 +0800130 public Network(@NonNull Network that) {
Erik Klinef4fa9822018-04-27 22:48:33 +0900131 this(that.netId, that.mPrivateDnsBypass);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700132 }
133
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400134 /**
135 * Operates the same as {@code InetAddress.getAllByName} except that host
136 * resolution is done on this network.
137 *
138 * @param host the hostname or literal IP string to be resolved.
139 * @return the array of addresses associated with the specified host.
140 * @throws UnknownHostException if the address lookup fails.
141 */
142 public InetAddress[] getAllByName(String host) throws UnknownHostException {
Erik Kline7eccfeb2018-05-22 21:15:49 +0900143 return InetAddress.getAllByNameOnNet(host, getNetIdForResolv());
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400144 }
145
146 /**
147 * Operates the same as {@code InetAddress.getByName} except that host
148 * resolution is done on this network.
149 *
Erik Klinef4fa9822018-04-27 22:48:33 +0900150 * @param host the hostname to be resolved to an address or {@code null}.
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400151 * @return the {@code InetAddress} instance representing the host.
152 * @throws UnknownHostException
153 * if the address lookup fails.
154 */
155 public InetAddress getByName(String host) throws UnknownHostException {
Erik Kline7eccfeb2018-05-22 21:15:49 +0900156 return InetAddress.getByNameOnNet(host, getNetIdForResolv());
157 }
158
159 /**
Erik Klinef4fa9822018-04-27 22:48:33 +0900160 * Obtain a Network object for which Private DNS is to be bypassed when attempting
Chalard Jean68237442018-06-07 13:46:52 +0900161 * to use {@link #getAllByName(String)}/{@link #getByName(String)} methods on the given
Erik Kline7eccfeb2018-05-22 21:15:49 +0900162 * instance for hostname resolution.
163 *
164 * @hide
165 */
Remi NGUYEN VAN31f1d0c2019-01-20 12:52:43 +0900166 @TestApi
167 @SystemApi
paulhud9736de2019-03-08 16:35:20 +0800168 public @NonNull Network getPrivateDnsBypassingCopy() {
Erik Klinef4fa9822018-04-27 22:48:33 +0900169 return new Network(netId, true);
Erik Kline7eccfeb2018-05-22 21:15:49 +0900170 }
171
172 /**
markchien587ecb32020-03-18 08:43:07 +0800173 * Get the unique id of the network.
174 *
175 * @hide
176 */
177 @TestApi
178 @SystemApi
179 public int getNetId() {
180 return netId;
181 }
182
183 /**
Erik Kline7eccfeb2018-05-22 21:15:49 +0900184 * Returns a netid marked with the Private DNS bypass flag.
185 *
186 * This flag must be kept in sync with the NETID_USE_LOCAL_NAMESERVERS flag
187 * in system/netd/include/NetdClient.h.
188 *
189 * @hide
190 */
191 public int getNetIdForResolv() {
192 return mPrivateDnsBypass
193 ? (int) (0x80000000L | (long) netId) // Non-portable DNS resolution flag.
194 : netId;
Paul Jensen3e32a4b2014-05-13 19:05:13 -0400195 }
196
Robert Greenwalt85956262014-05-18 20:29:39 -0700197 /**
Paul Jensen2d6f2652014-05-20 11:25:35 -0400198 * A {@code SocketFactory} that produces {@code Socket}'s bound to this network.
199 */
200 private class NetworkBoundSocketFactory extends SocketFactory {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900201 private Socket connectToHost(String host, int port, SocketAddress localAddress)
202 throws IOException {
Paul Jensen8ef34012014-05-27 10:19:39 -0400203 // Lookup addresses only on this Network.
204 InetAddress[] hostAddresses = getAllByName(host);
Lorenzo Colittif0382892014-07-30 17:17:13 +0900205 // Try all addresses.
206 for (int i = 0; i < hostAddresses.length; i++) {
Paul Jensen8ef34012014-05-27 10:19:39 -0400207 try {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900208 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400209 boolean failed = true;
210 try {
211 if (localAddress != null) socket.bind(localAddress);
212 socket.connect(new InetSocketAddress(hostAddresses[i], port));
213 failed = false;
214 return socket;
215 } finally {
216 if (failed) IoUtils.closeQuietly(socket);
217 }
Paul Jensen8ef34012014-05-27 10:19:39 -0400218 } catch (IOException e) {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900219 if (i == (hostAddresses.length - 1)) throw e;
Paul Jensen8ef34012014-05-27 10:19:39 -0400220 }
221 }
Lorenzo Colittif0382892014-07-30 17:17:13 +0900222 throw new UnknownHostException(host);
Paul Jensen8ef34012014-05-27 10:19:39 -0400223 }
224
Paul Jensen2d6f2652014-05-20 11:25:35 -0400225 @Override
Chalard Jean68237442018-06-07 13:46:52 +0900226 public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
227 throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900228 return connectToHost(host, port, new InetSocketAddress(localHost, localPort));
Paul Jensen2d6f2652014-05-20 11:25:35 -0400229 }
230
231 @Override
232 public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
233 int localPort) throws IOException {
234 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400235 boolean failed = true;
236 try {
237 socket.bind(new InetSocketAddress(localAddress, localPort));
238 socket.connect(new InetSocketAddress(address, port));
239 failed = false;
240 } finally {
241 if (failed) IoUtils.closeQuietly(socket);
242 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400243 return socket;
244 }
245
246 @Override
247 public Socket createSocket(InetAddress host, int port) throws IOException {
248 Socket socket = createSocket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400249 boolean failed = true;
250 try {
251 socket.connect(new InetSocketAddress(host, port));
252 failed = false;
253 } finally {
254 if (failed) IoUtils.closeQuietly(socket);
255 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400256 return socket;
257 }
258
259 @Override
260 public Socket createSocket(String host, int port) throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900261 return connectToHost(host, port, null);
Paul Jensen2d6f2652014-05-20 11:25:35 -0400262 }
263
264 @Override
265 public Socket createSocket() throws IOException {
266 Socket socket = new Socket();
Paul Jensen89bb9932018-03-29 07:41:43 -0400267 boolean failed = true;
268 try {
269 bindSocket(socket);
270 failed = false;
271 } finally {
272 if (failed) IoUtils.closeQuietly(socket);
273 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400274 return socket;
275 }
276 }
277
278 /**
Robert Greenwalt85956262014-05-18 20:29:39 -0700279 * Returns a {@link SocketFactory} bound to this network. Any {@link Socket} created by
280 * this factory will have its traffic sent over this {@code Network}. Note that if this
281 * {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the
282 * past or future will cease to work.
283 *
284 * @return a {@link SocketFactory} which produces {@link Socket} instances bound to this
285 * {@code Network}.
286 */
Paul Jensen0a363a32014-05-29 10:12:39 -0400287 public SocketFactory getSocketFactory() {
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900288 if (mNetworkBoundSocketFactory == null) {
289 synchronized (mLock) {
290 if (mNetworkBoundSocketFactory == null) {
Chalard Jean68237442018-06-07 13:46:52 +0900291 mNetworkBoundSocketFactory = new NetworkBoundSocketFactory();
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900292 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900293 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400294 }
295 return mNetworkBoundSocketFactory;
Robert Greenwalt85956262014-05-18 20:29:39 -0700296 }
297
Paul Jensen07ed0742014-09-08 14:59:09 -0400298 // TODO: This creates a connection pool and host resolver for
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -0700299 // every Network object, instead of one for every NetId. This is
300 // suboptimal, because an app could potentially have more than one
301 // Network object for the same NetId, causing increased memory footprint
302 // and performance penalties due to lack of connection reuse (connection
303 // setup time, congestion window growth time, etc.).
304 //
Paul Jensen07ed0742014-09-08 14:59:09 -0400305 // Instead, investigate only having one connection pool and host resolver
306 // for every NetId, perhaps by using a static HashMap of NetIds to
307 // connection pools and host resolvers. The tricky part is deciding when
308 // to remove a map entry; a WeakHashMap shouldn't be used because whether
309 // a Network is referenced doesn't correlate with whether a new Network
310 // will be instantiated in the near future with the same NetID. A good
311 // solution would involve purging empty (or when all connections are timed
312 // out) ConnectionPools.
Tobias Thierer69b8b292017-04-11 22:16:53 +0100313 private void maybeInitUrlConnectionFactory() {
Paul Jensen07ed0742014-09-08 14:59:09 -0400314 synchronized (mLock) {
Tobias Thierer69b8b292017-04-11 22:16:53 +0100315 if (mUrlConnectionFactory == null) {
316 // Set configuration on the HttpURLConnectionFactory that will be good for all
317 // connections created by this Network. Configuration that might vary is left
318 // until openConnection() and passed as arguments.
319 Dns dnsLookup = hostname -> Arrays.asList(Network.this.getAllByName(hostname));
320 HttpURLConnectionFactory urlConnectionFactory = new HttpURLConnectionFactory();
321 urlConnectionFactory.setDns(dnsLookup); // Let traffic go via dnsLookup
322 // A private connection pool just for this Network.
323 urlConnectionFactory.setNewConnectionPool(httpMaxConnections,
Tobias Thierer851d8062016-06-01 20:51:45 +0100324 httpKeepAliveDurationMs, TimeUnit.MILLISECONDS);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100325 mUrlConnectionFactory = urlConnectionFactory;
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900326 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900327 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900328 }
329
330 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700331 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
332 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
333 *
334 * @return a {@code URLConnection} to the resource referred to by this URL.
335 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
336 * @throws IOException if an error occurs while opening the connection.
337 * @see java.net.URL#openConnection()
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900338 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700339 public URLConnection openConnection(URL url) throws IOException {
Paul Jensen72db88e2015-03-10 10:54:12 -0400340 final ConnectivityManager cm = ConnectivityManager.getInstanceOrNull();
341 if (cm == null) {
342 throw new IOException("No ConnectivityManager yet constructed, please construct one");
343 }
Paul Jensene0bef712014-12-10 15:12:18 -0500344 // TODO: Should this be optimized to avoid fetching the global proxy for every request?
Paul Jensencee9b512015-05-06 07:32:40 -0400345 final ProxyInfo proxyInfo = cm.getProxyForNetwork(this);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100346 final java.net.Proxy proxy;
Paul Jensene0bef712014-12-10 15:12:18 -0500347 if (proxyInfo != null) {
348 proxy = proxyInfo.makeProxy();
349 } else {
350 proxy = java.net.Proxy.NO_PROXY;
351 }
352 return openConnection(url, proxy);
353 }
354
355 /**
356 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
357 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
358 *
359 * @param proxy the proxy through which the connection will be established.
360 * @return a {@code URLConnection} to the resource referred to by this URL.
361 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
362 * @throws IllegalArgumentException if the argument proxy is null.
363 * @throws IOException if an error occurs while opening the connection.
364 * @see java.net.URL#openConnection()
Paul Jensene0bef712014-12-10 15:12:18 -0500365 */
366 public URLConnection openConnection(URL url, java.net.Proxy proxy) throws IOException {
367 if (proxy == null) throw new IllegalArgumentException("proxy is null");
Tobias Thierer69b8b292017-04-11 22:16:53 +0100368 maybeInitUrlConnectionFactory();
369 SocketFactory socketFactory = getSocketFactory();
370 return mUrlConnectionFactory.openConnection(url, socketFactory, proxy);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700371 }
372
373 /**
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700374 * Binds the specified {@link DatagramSocket} to this {@code Network}. All data traffic on the
375 * socket will be sent on this {@code Network}, irrespective of any process-wide network binding
Paul Jensen72db88e2015-03-10 10:54:12 -0400376 * set by {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700377 * connected.
378 */
379 public void bindSocket(DatagramSocket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700380 // Query a property of the underlying socket to ensure that the socket's file descriptor
381 // exists, is available to bind to a network and is not closed.
382 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900383 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700384 }
385
386 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700387 * Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket
388 * will be sent on this {@code Network}, irrespective of any process-wide network binding set by
Paul Jensen72db88e2015-03-10 10:54:12 -0400389 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700390 */
391 public void bindSocket(Socket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700392 // Query a property of the underlying socket to ensure that the socket's file descriptor
393 // exists, is available to bind to a network and is not closed.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700394 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900395 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700396 }
397
Erik Klined8959992015-06-05 17:37:45 +0900398 /**
399 * Binds the specified {@link FileDescriptor} to this {@code Network}. All data traffic on the
400 * socket represented by this file descriptor will be sent on this {@code Network},
401 * irrespective of any process-wide network binding set by
402 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
403 */
404 public void bindSocket(FileDescriptor fd) throws IOException {
405 try {
406 final SocketAddress peer = Os.getpeername(fd);
407 final InetAddress inetPeer = ((InetSocketAddress) peer).getAddress();
408 if (!inetPeer.isAnyLocalAddress()) {
409 // Apparently, the kernel doesn't update a connected UDP socket's
410 // routing upon mark changes.
411 throw new SocketException("Socket is connected");
412 }
413 } catch (ErrnoException e) {
414 // getpeername() failed.
415 if (e.errno != OsConstants.ENOTCONN) {
416 throw e.rethrowAsSocketException();
417 }
418 } catch (ClassCastException e) {
419 // Wasn't an InetSocketAddress.
420 throw new SocketException("Only AF_INET/AF_INET6 sockets supported");
421 }
422
423 final int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700424 if (err != 0) {
425 // bindSocketToNetwork returns negative errno.
426 throw new ErrnoException("Binding socket to network " + netId, -err)
427 .rethrowAsSocketException();
428 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900429 }
430
Erik Kline25f3b7b2015-03-05 15:13:37 +0900431 /**
Paul Jensen4af17812018-03-28 09:19:58 -0400432 * Returns a {@link Network} object given a handle returned from {@link #getNetworkHandle}.
433 *
434 * @param networkHandle a handle returned from {@link #getNetworkHandle}.
435 * @return A {@link Network} object derived from {@code networkHandle}.
436 */
437 public static Network fromNetworkHandle(long networkHandle) {
438 if (networkHandle == 0) {
439 throw new IllegalArgumentException(
440 "Network.fromNetworkHandle refusing to instantiate NETID_UNSET Network.");
441 }
442 if ((networkHandle & ((1L << HANDLE_MAGIC_SIZE) - 1)) != HANDLE_MAGIC
443 || networkHandle < 0) {
444 throw new IllegalArgumentException(
445 "Value passed to fromNetworkHandle() is not a network handle.");
446 }
447 return new Network((int) (networkHandle >> HANDLE_MAGIC_SIZE));
448 }
449
450 /**
Erik Kline25f3b7b2015-03-05 15:13:37 +0900451 * Returns a handle representing this {@code Network}, for use with the NDK API.
452 */
453 public long getNetworkHandle() {
454 // The network handle is explicitly not the same as the netId.
455 //
456 // The netId is an implementation detail which might be changed in the
457 // future, or which alone (i.e. in the absence of some additional
458 // context) might not be sufficient to fully identify a Network.
459 //
460 // As such, the intention is to prevent accidental misuse of the API
461 // that might result if a developer assumed that handles and netIds
462 // were identical and passing a netId to a call expecting a handle
463 // "just worked". Such accidental misuse, if widely deployed, might
464 // prevent future changes to the semantics of the netId field or
465 // inhibit the expansion of state required for Network objects.
466 //
467 // This extra layer of indirection might be seen as paranoia, and might
468 // never end up being necessary, but the added complexity is trivial.
469 // At some future date it may be desirable to realign the handle with
470 // Multiple Provisioning Domains API recommendations, as made by the
471 // IETF mif working group.
Erik Klinee1a6cf22015-05-14 15:40:07 +0900472 if (netId == 0) {
473 return 0L; // make this zero condition obvious for debugging
474 }
Paul Jensen4af17812018-03-28 09:19:58 -0400475 return (((long) netId) << HANDLE_MAGIC_SIZE) | HANDLE_MAGIC;
Erik Kline25f3b7b2015-03-05 15:13:37 +0900476 }
477
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700478 // implement the Parcelable interface
479 public int describeContents() {
480 return 0;
481 }
482 public void writeToParcel(Parcel dest, int flags) {
483 dest.writeInt(netId);
484 }
485
Jeff Sharkey9e8f83d2019-02-28 12:06:45 -0700486 public static final @android.annotation.NonNull Creator<Network> CREATOR =
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700487 new Creator<Network>() {
488 public Network createFromParcel(Parcel in) {
489 int netId = in.readInt();
490
491 return new Network(netId);
492 }
493
494 public Network[] newArray(int size) {
495 return new Network[size];
496 }
497 };
Robert Greenwalt85956262014-05-18 20:29:39 -0700498
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700499 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700500 public boolean equals(Object obj) {
Chalard Jean68237442018-06-07 13:46:52 +0900501 if (!(obj instanceof Network)) return false;
Robert Greenwalt85956262014-05-18 20:29:39 -0700502 Network other = (Network)obj;
503 return this.netId == other.netId;
504 }
505
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700506 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700507 public int hashCode() {
508 return netId * 11;
509 }
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700510
511 @Override
512 public String toString() {
513 return Integer.toString(netId);
514 }
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800515
516 /** @hide */
Jeffrey Huangcb782852019-12-05 11:28:11 -0800517 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
Kweku Adams85f2fbc2017-12-18 12:04:12 -0800518 final long token = proto.start(fieldId);
519 proto.write(NetworkProto.NET_ID, netId);
520 proto.end(token);
521 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700522}