blob: 3c868c399b1f207e5cc7fca2521b638f95ba5c82 [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
19import android.os.Parcelable;
20import android.os.Parcel;
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;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070024
Tobias Thierer69b8b292017-04-11 22:16:53 +010025import libcore.net.http.Dns;
26import libcore.net.http.HttpURLConnectionFactory;
27
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070028import java.io.FileDescriptor;
Paul Jensen2d6f2652014-05-20 11:25:35 -040029import java.io.IOException;
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -070030import java.net.DatagramSocket;
Paul Jensen3e32a4b2014-05-13 19:05:13 -040031import java.net.InetAddress;
Paul Jensen2d6f2652014-05-20 11:25:35 -040032import java.net.InetSocketAddress;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090033import java.net.MalformedURLException;
Robert Greenwalt85956262014-05-18 20:29:39 -070034import java.net.Socket;
Lorenzo Colittif0382892014-07-30 17:17:13 +090035import java.net.SocketAddress;
Paul Jensen32a58f02014-06-20 13:58:14 -040036import java.net.SocketException;
Paul Jensen3e32a4b2014-05-13 19:05:13 -040037import java.net.UnknownHostException;
Lorenzo Colittic473dc42014-07-18 01:34:19 +090038import java.net.URL;
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070039import java.net.URLConnection;
Tobias Thierer851d8062016-06-01 20:51:45 +010040import java.util.Arrays;
Tobias Thierer851d8062016-06-01 20:51:45 +010041import java.util.concurrent.TimeUnit;
Robert Greenwalt85956262014-05-18 20:29:39 -070042import javax.net.SocketFactory;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070043
44/**
Robert Greenwalt85956262014-05-18 20:29:39 -070045 * Identifies a {@code Network}. This is supplied to applications via
Robert Greenwalt6078b502014-06-11 16:05:07 -070046 * {@link ConnectivityManager.NetworkCallback} in response to the active
47 * {@link ConnectivityManager#requestNetwork} or passive
48 * {@link ConnectivityManager#registerNetworkCallback} calls.
Robert Greenwalt85956262014-05-18 20:29:39 -070049 * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis
Paul Jensen0a363a32014-05-29 10:12:39 -040050 * through a targeted {@link SocketFactory} or process-wide via
Paul Jensen72db88e2015-03-10 10:54:12 -040051 * {@link ConnectivityManager#bindProcessToNetwork}.
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070052 */
53public class Network implements Parcelable {
54
Robert Greenwalt85956262014-05-18 20:29:39 -070055 /**
56 * @hide
57 */
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058 public final int netId;
59
Lorenzo Colittic473dc42014-07-18 01:34:19 +090060 // Objects used to perform per-network operations such as getSocketFactory
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070061 // and openConnection, and a lock to protect access to them.
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +090062 private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null;
Tobias Thierer69b8b292017-04-11 22:16:53 +010063 // mLock should be used to control write access to mUrlConnectionFactory.
64 // maybeInitUrlConnectionFactory() must be called prior to reading this field.
65 private volatile HttpURLConnectionFactory mUrlConnectionFactory;
Erik Klined8959992015-06-05 17:37:45 +090066 private final Object mLock = new Object();
Paul Jensen2d6f2652014-05-20 11:25:35 -040067
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -070068 // Default connection pool values. These are evaluated at startup, just
69 // like the OkHttp code. Also like the OkHttp code, we will throw parse
70 // exceptions at class loading time if the properties are set but are not
71 // valid integers.
72 private static final boolean httpKeepAlive =
73 Boolean.parseBoolean(System.getProperty("http.keepAlive", "true"));
74 private static final int httpMaxConnections =
75 httpKeepAlive ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0;
76 private static final long httpKeepAliveDurationMs =
77 Long.parseLong(System.getProperty("http.keepAliveDuration", "300000")); // 5 minutes.
78
Robert Greenwalt85956262014-05-18 20:29:39 -070079 /**
80 * @hide
81 */
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070082 public Network(int netId) {
83 this.netId = netId;
84 }
85
Robert Greenwalt85956262014-05-18 20:29:39 -070086 /**
87 * @hide
88 */
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070089 public Network(Network that) {
90 this.netId = that.netId;
91 }
92
Paul Jensen3e32a4b2014-05-13 19:05:13 -040093 /**
94 * Operates the same as {@code InetAddress.getAllByName} except that host
95 * resolution is done on this network.
96 *
97 * @param host the hostname or literal IP string to be resolved.
98 * @return the array of addresses associated with the specified host.
99 * @throws UnknownHostException if the address lookup fails.
100 */
101 public InetAddress[] getAllByName(String host) throws UnknownHostException {
102 return InetAddress.getAllByNameOnNet(host, netId);
103 }
104
105 /**
106 * Operates the same as {@code InetAddress.getByName} except that host
107 * resolution is done on this network.
108 *
109 * @param host
110 * the hostName to be resolved to an address or {@code null}.
111 * @return the {@code InetAddress} instance representing the host.
112 * @throws UnknownHostException
113 * if the address lookup fails.
114 */
115 public InetAddress getByName(String host) throws UnknownHostException {
116 return InetAddress.getByNameOnNet(host, netId);
117 }
118
Robert Greenwalt85956262014-05-18 20:29:39 -0700119 /**
Paul Jensen2d6f2652014-05-20 11:25:35 -0400120 * A {@code SocketFactory} that produces {@code Socket}'s bound to this network.
121 */
122 private class NetworkBoundSocketFactory extends SocketFactory {
123 private final int mNetId;
124
125 public NetworkBoundSocketFactory(int netId) {
126 super();
127 mNetId = netId;
128 }
129
Lorenzo Colittif0382892014-07-30 17:17:13 +0900130 private Socket connectToHost(String host, int port, SocketAddress localAddress)
131 throws IOException {
Paul Jensen8ef34012014-05-27 10:19:39 -0400132 // Lookup addresses only on this Network.
133 InetAddress[] hostAddresses = getAllByName(host);
Lorenzo Colittif0382892014-07-30 17:17:13 +0900134 // Try all addresses.
135 for (int i = 0; i < hostAddresses.length; i++) {
Paul Jensen8ef34012014-05-27 10:19:39 -0400136 try {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900137 Socket socket = createSocket();
138 if (localAddress != null) socket.bind(localAddress);
Paul Jensen8ef34012014-05-27 10:19:39 -0400139 socket.connect(new InetSocketAddress(hostAddresses[i], port));
Lorenzo Colittif0382892014-07-30 17:17:13 +0900140 return socket;
Paul Jensen8ef34012014-05-27 10:19:39 -0400141 } catch (IOException e) {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900142 if (i == (hostAddresses.length - 1)) throw e;
Paul Jensen8ef34012014-05-27 10:19:39 -0400143 }
144 }
Lorenzo Colittif0382892014-07-30 17:17:13 +0900145 throw new UnknownHostException(host);
Paul Jensen8ef34012014-05-27 10:19:39 -0400146 }
147
Paul Jensen2d6f2652014-05-20 11:25:35 -0400148 @Override
149 public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900150 return connectToHost(host, port, new InetSocketAddress(localHost, localPort));
Paul Jensen2d6f2652014-05-20 11:25:35 -0400151 }
152
153 @Override
154 public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
155 int localPort) throws IOException {
156 Socket socket = createSocket();
157 socket.bind(new InetSocketAddress(localAddress, localPort));
158 socket.connect(new InetSocketAddress(address, port));
159 return socket;
160 }
161
162 @Override
163 public Socket createSocket(InetAddress host, int port) throws IOException {
164 Socket socket = createSocket();
165 socket.connect(new InetSocketAddress(host, port));
166 return socket;
167 }
168
169 @Override
170 public Socket createSocket(String host, int port) throws IOException {
Lorenzo Colittif0382892014-07-30 17:17:13 +0900171 return connectToHost(host, port, null);
Paul Jensen2d6f2652014-05-20 11:25:35 -0400172 }
173
174 @Override
175 public Socket createSocket() throws IOException {
176 Socket socket = new Socket();
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700177 bindSocket(socket);
Paul Jensen2d6f2652014-05-20 11:25:35 -0400178 return socket;
179 }
180 }
181
182 /**
Robert Greenwalt85956262014-05-18 20:29:39 -0700183 * Returns a {@link SocketFactory} bound to this network. Any {@link Socket} created by
184 * this factory will have its traffic sent over this {@code Network}. Note that if this
185 * {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the
186 * past or future will cease to work.
187 *
188 * @return a {@link SocketFactory} which produces {@link Socket} instances bound to this
189 * {@code Network}.
190 */
Paul Jensen0a363a32014-05-29 10:12:39 -0400191 public SocketFactory getSocketFactory() {
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900192 if (mNetworkBoundSocketFactory == null) {
193 synchronized (mLock) {
194 if (mNetworkBoundSocketFactory == null) {
195 mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId);
196 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900197 }
Paul Jensen2d6f2652014-05-20 11:25:35 -0400198 }
199 return mNetworkBoundSocketFactory;
Robert Greenwalt85956262014-05-18 20:29:39 -0700200 }
201
Paul Jensen07ed0742014-09-08 14:59:09 -0400202 // TODO: This creates a connection pool and host resolver for
Lorenzo Colitti0ed0a282014-08-28 17:15:40 -0700203 // every Network object, instead of one for every NetId. This is
204 // suboptimal, because an app could potentially have more than one
205 // Network object for the same NetId, causing increased memory footprint
206 // and performance penalties due to lack of connection reuse (connection
207 // setup time, congestion window growth time, etc.).
208 //
Paul Jensen07ed0742014-09-08 14:59:09 -0400209 // Instead, investigate only having one connection pool and host resolver
210 // for every NetId, perhaps by using a static HashMap of NetIds to
211 // connection pools and host resolvers. The tricky part is deciding when
212 // to remove a map entry; a WeakHashMap shouldn't be used because whether
213 // a Network is referenced doesn't correlate with whether a new Network
214 // will be instantiated in the near future with the same NetID. A good
215 // solution would involve purging empty (or when all connections are timed
216 // out) ConnectionPools.
Tobias Thierer69b8b292017-04-11 22:16:53 +0100217 private void maybeInitUrlConnectionFactory() {
Paul Jensen07ed0742014-09-08 14:59:09 -0400218 synchronized (mLock) {
Tobias Thierer69b8b292017-04-11 22:16:53 +0100219 if (mUrlConnectionFactory == null) {
220 // Set configuration on the HttpURLConnectionFactory that will be good for all
221 // connections created by this Network. Configuration that might vary is left
222 // until openConnection() and passed as arguments.
223 Dns dnsLookup = hostname -> Arrays.asList(Network.this.getAllByName(hostname));
224 HttpURLConnectionFactory urlConnectionFactory = new HttpURLConnectionFactory();
225 urlConnectionFactory.setDns(dnsLookup); // Let traffic go via dnsLookup
226 // A private connection pool just for this Network.
227 urlConnectionFactory.setNewConnectionPool(httpMaxConnections,
Tobias Thierer851d8062016-06-01 20:51:45 +0100228 httpKeepAliveDurationMs, TimeUnit.MILLISECONDS);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100229 mUrlConnectionFactory = urlConnectionFactory;
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900230 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900231 }
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900232 }
233
234 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700235 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
236 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
237 *
238 * @return a {@code URLConnection} to the resource referred to by this URL.
239 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
240 * @throws IOException if an error occurs while opening the connection.
241 * @see java.net.URL#openConnection()
Lorenzo Colitti5b37fa22014-07-29 22:51:27 +0900242 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700243 public URLConnection openConnection(URL url) throws IOException {
Paul Jensen72db88e2015-03-10 10:54:12 -0400244 final ConnectivityManager cm = ConnectivityManager.getInstanceOrNull();
245 if (cm == null) {
246 throw new IOException("No ConnectivityManager yet constructed, please construct one");
247 }
Paul Jensene0bef712014-12-10 15:12:18 -0500248 // TODO: Should this be optimized to avoid fetching the global proxy for every request?
Paul Jensencee9b512015-05-06 07:32:40 -0400249 final ProxyInfo proxyInfo = cm.getProxyForNetwork(this);
Tobias Thierer69b8b292017-04-11 22:16:53 +0100250 final java.net.Proxy proxy;
Paul Jensene0bef712014-12-10 15:12:18 -0500251 if (proxyInfo != null) {
252 proxy = proxyInfo.makeProxy();
253 } else {
254 proxy = java.net.Proxy.NO_PROXY;
255 }
256 return openConnection(url, proxy);
257 }
258
259 /**
260 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
261 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
262 *
263 * @param proxy the proxy through which the connection will be established.
264 * @return a {@code URLConnection} to the resource referred to by this URL.
265 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
266 * @throws IllegalArgumentException if the argument proxy is null.
267 * @throws IOException if an error occurs while opening the connection.
268 * @see java.net.URL#openConnection()
Paul Jensene0bef712014-12-10 15:12:18 -0500269 */
270 public URLConnection openConnection(URL url, java.net.Proxy proxy) throws IOException {
271 if (proxy == null) throw new IllegalArgumentException("proxy is null");
Tobias Thierer69b8b292017-04-11 22:16:53 +0100272 maybeInitUrlConnectionFactory();
273 SocketFactory socketFactory = getSocketFactory();
274 return mUrlConnectionFactory.openConnection(url, socketFactory, proxy);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700275 }
276
277 /**
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700278 * Binds the specified {@link DatagramSocket} to this {@code Network}. All data traffic on the
279 * socket will be sent on this {@code Network}, irrespective of any process-wide network binding
Paul Jensen72db88e2015-03-10 10:54:12 -0400280 * set by {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700281 * connected.
282 */
283 public void bindSocket(DatagramSocket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700284 // Query a property of the underlying socket to ensure that the socket's file descriptor
285 // exists, is available to bind to a network and is not closed.
286 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900287 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700288 }
289
290 /**
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700291 * Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket
292 * will be sent on this {@code Network}, irrespective of any process-wide network binding set by
Paul Jensen72db88e2015-03-10 10:54:12 -0400293 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700294 */
295 public void bindSocket(Socket socket) throws IOException {
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700296 // Query a property of the underlying socket to ensure that the socket's file descriptor
297 // exists, is available to bind to a network and is not closed.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700298 socket.getReuseAddress();
Erik Klined8959992015-06-05 17:37:45 +0900299 bindSocket(socket.getFileDescriptor$());
Sreeram Ramachandrane15db7c2014-10-22 11:10:20 -0700300 }
301
Erik Klined8959992015-06-05 17:37:45 +0900302 /**
303 * Binds the specified {@link FileDescriptor} to this {@code Network}. All data traffic on the
304 * socket represented by this file descriptor will be sent on this {@code Network},
305 * irrespective of any process-wide network binding set by
306 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
307 */
308 public void bindSocket(FileDescriptor fd) throws IOException {
309 try {
310 final SocketAddress peer = Os.getpeername(fd);
311 final InetAddress inetPeer = ((InetSocketAddress) peer).getAddress();
312 if (!inetPeer.isAnyLocalAddress()) {
313 // Apparently, the kernel doesn't update a connected UDP socket's
314 // routing upon mark changes.
315 throw new SocketException("Socket is connected");
316 }
317 } catch (ErrnoException e) {
318 // getpeername() failed.
319 if (e.errno != OsConstants.ENOTCONN) {
320 throw e.rethrowAsSocketException();
321 }
322 } catch (ClassCastException e) {
323 // Wasn't an InetSocketAddress.
324 throw new SocketException("Only AF_INET/AF_INET6 sockets supported");
325 }
326
327 final int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700328 if (err != 0) {
329 // bindSocketToNetwork returns negative errno.
330 throw new ErrnoException("Binding socket to network " + netId, -err)
331 .rethrowAsSocketException();
332 }
Lorenzo Colittic473dc42014-07-18 01:34:19 +0900333 }
334
Erik Kline25f3b7b2015-03-05 15:13:37 +0900335 /**
336 * Returns a handle representing this {@code Network}, for use with the NDK API.
337 */
338 public long getNetworkHandle() {
339 // The network handle is explicitly not the same as the netId.
340 //
341 // The netId is an implementation detail which might be changed in the
342 // future, or which alone (i.e. in the absence of some additional
343 // context) might not be sufficient to fully identify a Network.
344 //
345 // As such, the intention is to prevent accidental misuse of the API
346 // that might result if a developer assumed that handles and netIds
347 // were identical and passing a netId to a call expecting a handle
348 // "just worked". Such accidental misuse, if widely deployed, might
349 // prevent future changes to the semantics of the netId field or
350 // inhibit the expansion of state required for Network objects.
351 //
352 // This extra layer of indirection might be seen as paranoia, and might
353 // never end up being necessary, but the added complexity is trivial.
354 // At some future date it may be desirable to realign the handle with
355 // Multiple Provisioning Domains API recommendations, as made by the
356 // IETF mif working group.
357 //
358 // The HANDLE_MAGIC value MUST be kept in sync with the corresponding
359 // value in the native/android/net.c NDK implementation.
Erik Klinee1a6cf22015-05-14 15:40:07 +0900360 if (netId == 0) {
361 return 0L; // make this zero condition obvious for debugging
362 }
Erik Kline25f3b7b2015-03-05 15:13:37 +0900363 final long HANDLE_MAGIC = 0xfacade;
364 return (((long) netId) << 32) | HANDLE_MAGIC;
365 }
366
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700367 // implement the Parcelable interface
368 public int describeContents() {
369 return 0;
370 }
371 public void writeToParcel(Parcel dest, int flags) {
372 dest.writeInt(netId);
373 }
374
375 public static final Creator<Network> CREATOR =
376 new Creator<Network>() {
377 public Network createFromParcel(Parcel in) {
378 int netId = in.readInt();
379
380 return new Network(netId);
381 }
382
383 public Network[] newArray(int size) {
384 return new Network[size];
385 }
386 };
Robert Greenwalt85956262014-05-18 20:29:39 -0700387
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700388 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700389 public boolean equals(Object obj) {
390 if (obj instanceof Network == false) return false;
391 Network other = (Network)obj;
392 return this.netId == other.netId;
393 }
394
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700395 @Override
Robert Greenwalt85956262014-05-18 20:29:39 -0700396 public int hashCode() {
397 return netId * 11;
398 }
Robert Greenwalt2c7bf2c2014-06-23 16:07:43 -0700399
400 @Override
401 public String toString() {
402 return Integer.toString(netId);
403 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700404}