Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | package android.net; |
| 18 | |
Remi NGUYEN VAN | 31f1d0c | 2019-01-20 12:52:43 +0900 | [diff] [blame] | 19 | import android.annotation.SystemApi; |
| 20 | import android.annotation.TestApi; |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 21 | import android.annotation.UnsupportedAppUsage; |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 22 | import android.os.Parcel; |
Tobias Thierer | 4c6d2ec | 2017-10-25 00:58:29 +0100 | [diff] [blame] | 23 | import android.os.Parcelable; |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 24 | import android.system.ErrnoException; |
Erik Kline | d895999 | 2015-06-05 17:37:45 +0900 | [diff] [blame] | 25 | import android.system.Os; |
| 26 | import android.system.OsConstants; |
Kweku Adams | 85f2fbc | 2017-12-18 12:04:12 -0800 | [diff] [blame] | 27 | import android.util.proto.ProtoOutputStream; |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 28 | |
Tobias Thierer | 4c6d2ec | 2017-10-25 00:58:29 +0100 | [diff] [blame] | 29 | import com.android.okhttp.internalandroidapi.Dns; |
| 30 | import com.android.okhttp.internalandroidapi.HttpURLConnectionFactory; |
Tobias Thierer | 69b8b29 | 2017-04-11 22:16:53 +0100 | [diff] [blame] | 31 | |
Paul Jensen | 89bb993 | 2018-03-29 07:41:43 -0400 | [diff] [blame] | 32 | import libcore.io.IoUtils; |
| 33 | |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 34 | import java.io.FileDescriptor; |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 35 | import java.io.IOException; |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 36 | import java.net.DatagramSocket; |
Paul Jensen | 3e32a4b | 2014-05-13 19:05:13 -0400 | [diff] [blame] | 37 | import java.net.InetAddress; |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 38 | import java.net.InetSocketAddress; |
Lorenzo Colitti | c473dc4 | 2014-07-18 01:34:19 +0900 | [diff] [blame] | 39 | import java.net.MalformedURLException; |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 40 | import java.net.Socket; |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 41 | import java.net.SocketAddress; |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 42 | import java.net.SocketException; |
Lorenzo Colitti | c473dc4 | 2014-07-18 01:34:19 +0900 | [diff] [blame] | 43 | import java.net.URL; |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 44 | import java.net.URLConnection; |
Tobias Thierer | 4c6d2ec | 2017-10-25 00:58:29 +0100 | [diff] [blame] | 45 | import java.net.UnknownHostException; |
Tobias Thierer | 851d806 | 2016-06-01 20:51:45 +0100 | [diff] [blame] | 46 | import java.util.Arrays; |
Tobias Thierer | 851d806 | 2016-06-01 20:51:45 +0100 | [diff] [blame] | 47 | import java.util.concurrent.TimeUnit; |
Tobias Thierer | 4c6d2ec | 2017-10-25 00:58:29 +0100 | [diff] [blame] | 48 | |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 49 | import javax.net.SocketFactory; |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 50 | |
| 51 | /** |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 52 | * Identifies a {@code Network}. This is supplied to applications via |
Robert Greenwalt | 6078b50 | 2014-06-11 16:05:07 -0700 | [diff] [blame] | 53 | * {@link ConnectivityManager.NetworkCallback} in response to the active |
| 54 | * {@link ConnectivityManager#requestNetwork} or passive |
| 55 | * {@link ConnectivityManager#registerNetworkCallback} calls. |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 56 | * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis |
Paul Jensen | 0a363a3 | 2014-05-29 10:12:39 -0400 | [diff] [blame] | 57 | * through a targeted {@link SocketFactory} or process-wide via |
Paul Jensen | 72db88e | 2015-03-10 10:54:12 -0400 | [diff] [blame] | 58 | * {@link ConnectivityManager#bindProcessToNetwork}. |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 59 | */ |
| 60 | public class Network implements Parcelable { |
| 61 | |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 62 | /** |
| 63 | * @hide |
| 64 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 65 | @UnsupportedAppUsage |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 66 | public final int netId; |
| 67 | |
Lorenzo Colitti | c473dc4 | 2014-07-18 01:34:19 +0900 | [diff] [blame] | 68 | // Objects used to perform per-network operations such as getSocketFactory |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 69 | // and openConnection, and a lock to protect access to them. |
Lorenzo Colitti | 5b37fa2 | 2014-07-29 22:51:27 +0900 | [diff] [blame] | 70 | private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null; |
Tobias Thierer | 69b8b29 | 2017-04-11 22:16:53 +0100 | [diff] [blame] | 71 | // 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 Kline | d895999 | 2015-06-05 17:37:45 +0900 | [diff] [blame] | 74 | private final Object mLock = new Object(); |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 75 | |
Lorenzo Colitti | 0ed0a28 | 2014-08-28 17:15:40 -0700 | [diff] [blame] | 76 | // 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 Jensen | 4af1781 | 2018-03-28 09:19:58 -0400 | [diff] [blame] | 86 | // 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 Colitti | 0ed0a28 | 2014-08-28 17:15:40 -0700 | [diff] [blame] | 91 | |
Erik Kline | 7eccfeb | 2018-05-22 21:15:49 +0900 | [diff] [blame] | 92 | // 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 Kline | f4fa982 | 2018-04-27 22:48:33 +0900 | [diff] [blame] | 105 | private final transient boolean mPrivateDnsBypass; |
Erik Kline | 7eccfeb | 2018-05-22 21:15:49 +0900 | [diff] [blame] | 106 | |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 107 | /** |
| 108 | * @hide |
| 109 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 110 | @UnsupportedAppUsage |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 111 | public Network(int netId) { |
Erik Kline | f4fa982 | 2018-04-27 22:48:33 +0900 | [diff] [blame] | 112 | this(netId, false); |
| 113 | } |
| 114 | |
| 115 | /** |
| 116 | * @hide |
| 117 | */ |
| 118 | public Network(int netId, boolean privateDnsBypass) { |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 119 | this.netId = netId; |
Erik Kline | f4fa982 | 2018-04-27 22:48:33 +0900 | [diff] [blame] | 120 | this.mPrivateDnsBypass = privateDnsBypass; |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 121 | } |
| 122 | |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 123 | /** |
| 124 | * @hide |
| 125 | */ |
Remi NGUYEN VAN | 5c5f1ba | 2019-01-29 12:08:43 +0900 | [diff] [blame] | 126 | @SystemApi |
| 127 | @TestApi |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 128 | public Network(Network that) { |
Erik Kline | f4fa982 | 2018-04-27 22:48:33 +0900 | [diff] [blame] | 129 | this(that.netId, that.mPrivateDnsBypass); |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 130 | } |
| 131 | |
Paul Jensen | 3e32a4b | 2014-05-13 19:05:13 -0400 | [diff] [blame] | 132 | /** |
| 133 | * Operates the same as {@code InetAddress.getAllByName} except that host |
| 134 | * resolution is done on this network. |
| 135 | * |
| 136 | * @param host the hostname or literal IP string to be resolved. |
| 137 | * @return the array of addresses associated with the specified host. |
| 138 | * @throws UnknownHostException if the address lookup fails. |
| 139 | */ |
| 140 | public InetAddress[] getAllByName(String host) throws UnknownHostException { |
Erik Kline | 7eccfeb | 2018-05-22 21:15:49 +0900 | [diff] [blame] | 141 | return InetAddress.getAllByNameOnNet(host, getNetIdForResolv()); |
Paul Jensen | 3e32a4b | 2014-05-13 19:05:13 -0400 | [diff] [blame] | 142 | } |
| 143 | |
| 144 | /** |
| 145 | * Operates the same as {@code InetAddress.getByName} except that host |
| 146 | * resolution is done on this network. |
| 147 | * |
Erik Kline | f4fa982 | 2018-04-27 22:48:33 +0900 | [diff] [blame] | 148 | * @param host the hostname to be resolved to an address or {@code null}. |
Paul Jensen | 3e32a4b | 2014-05-13 19:05:13 -0400 | [diff] [blame] | 149 | * @return the {@code InetAddress} instance representing the host. |
| 150 | * @throws UnknownHostException |
| 151 | * if the address lookup fails. |
| 152 | */ |
| 153 | public InetAddress getByName(String host) throws UnknownHostException { |
Erik Kline | 7eccfeb | 2018-05-22 21:15:49 +0900 | [diff] [blame] | 154 | return InetAddress.getByNameOnNet(host, getNetIdForResolv()); |
| 155 | } |
| 156 | |
| 157 | /** |
Erik Kline | f4fa982 | 2018-04-27 22:48:33 +0900 | [diff] [blame] | 158 | * Obtain a Network object for which Private DNS is to be bypassed when attempting |
Chalard Jean | 6823744 | 2018-06-07 13:46:52 +0900 | [diff] [blame] | 159 | * to use {@link #getAllByName(String)}/{@link #getByName(String)} methods on the given |
Erik Kline | 7eccfeb | 2018-05-22 21:15:49 +0900 | [diff] [blame] | 160 | * instance for hostname resolution. |
| 161 | * |
| 162 | * @hide |
| 163 | */ |
Remi NGUYEN VAN | 31f1d0c | 2019-01-20 12:52:43 +0900 | [diff] [blame] | 164 | @TestApi |
| 165 | @SystemApi |
Erik Kline | f4fa982 | 2018-04-27 22:48:33 +0900 | [diff] [blame] | 166 | public Network getPrivateDnsBypassingCopy() { |
| 167 | return new Network(netId, true); |
Erik Kline | 7eccfeb | 2018-05-22 21:15:49 +0900 | [diff] [blame] | 168 | } |
| 169 | |
| 170 | /** |
| 171 | * Returns a netid marked with the Private DNS bypass flag. |
| 172 | * |
| 173 | * This flag must be kept in sync with the NETID_USE_LOCAL_NAMESERVERS flag |
| 174 | * in system/netd/include/NetdClient.h. |
| 175 | * |
| 176 | * @hide |
| 177 | */ |
| 178 | public int getNetIdForResolv() { |
| 179 | return mPrivateDnsBypass |
| 180 | ? (int) (0x80000000L | (long) netId) // Non-portable DNS resolution flag. |
| 181 | : netId; |
Paul Jensen | 3e32a4b | 2014-05-13 19:05:13 -0400 | [diff] [blame] | 182 | } |
| 183 | |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 184 | /** |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 185 | * A {@code SocketFactory} that produces {@code Socket}'s bound to this network. |
| 186 | */ |
| 187 | private class NetworkBoundSocketFactory extends SocketFactory { |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 188 | private Socket connectToHost(String host, int port, SocketAddress localAddress) |
| 189 | throws IOException { |
Paul Jensen | 8ef3401 | 2014-05-27 10:19:39 -0400 | [diff] [blame] | 190 | // Lookup addresses only on this Network. |
| 191 | InetAddress[] hostAddresses = getAllByName(host); |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 192 | // Try all addresses. |
| 193 | for (int i = 0; i < hostAddresses.length; i++) { |
Paul Jensen | 8ef3401 | 2014-05-27 10:19:39 -0400 | [diff] [blame] | 194 | try { |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 195 | Socket socket = createSocket(); |
Paul Jensen | 89bb993 | 2018-03-29 07:41:43 -0400 | [diff] [blame] | 196 | boolean failed = true; |
| 197 | try { |
| 198 | if (localAddress != null) socket.bind(localAddress); |
| 199 | socket.connect(new InetSocketAddress(hostAddresses[i], port)); |
| 200 | failed = false; |
| 201 | return socket; |
| 202 | } finally { |
| 203 | if (failed) IoUtils.closeQuietly(socket); |
| 204 | } |
Paul Jensen | 8ef3401 | 2014-05-27 10:19:39 -0400 | [diff] [blame] | 205 | } catch (IOException e) { |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 206 | if (i == (hostAddresses.length - 1)) throw e; |
Paul Jensen | 8ef3401 | 2014-05-27 10:19:39 -0400 | [diff] [blame] | 207 | } |
| 208 | } |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 209 | throw new UnknownHostException(host); |
Paul Jensen | 8ef3401 | 2014-05-27 10:19:39 -0400 | [diff] [blame] | 210 | } |
| 211 | |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 212 | @Override |
Chalard Jean | 6823744 | 2018-06-07 13:46:52 +0900 | [diff] [blame] | 213 | public Socket createSocket(String host, int port, InetAddress localHost, int localPort) |
| 214 | throws IOException { |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 215 | return connectToHost(host, port, new InetSocketAddress(localHost, localPort)); |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 216 | } |
| 217 | |
| 218 | @Override |
| 219 | public Socket createSocket(InetAddress address, int port, InetAddress localAddress, |
| 220 | int localPort) throws IOException { |
| 221 | Socket socket = createSocket(); |
Paul Jensen | 89bb993 | 2018-03-29 07:41:43 -0400 | [diff] [blame] | 222 | boolean failed = true; |
| 223 | try { |
| 224 | socket.bind(new InetSocketAddress(localAddress, localPort)); |
| 225 | socket.connect(new InetSocketAddress(address, port)); |
| 226 | failed = false; |
| 227 | } finally { |
| 228 | if (failed) IoUtils.closeQuietly(socket); |
| 229 | } |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 230 | return socket; |
| 231 | } |
| 232 | |
| 233 | @Override |
| 234 | public Socket createSocket(InetAddress host, int port) throws IOException { |
| 235 | Socket socket = createSocket(); |
Paul Jensen | 89bb993 | 2018-03-29 07:41:43 -0400 | [diff] [blame] | 236 | boolean failed = true; |
| 237 | try { |
| 238 | socket.connect(new InetSocketAddress(host, port)); |
| 239 | failed = false; |
| 240 | } finally { |
| 241 | if (failed) IoUtils.closeQuietly(socket); |
| 242 | } |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 243 | return socket; |
| 244 | } |
| 245 | |
| 246 | @Override |
| 247 | public Socket createSocket(String host, int port) throws IOException { |
Lorenzo Colitti | f038289 | 2014-07-30 17:17:13 +0900 | [diff] [blame] | 248 | return connectToHost(host, port, null); |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 249 | } |
| 250 | |
| 251 | @Override |
| 252 | public Socket createSocket() throws IOException { |
| 253 | Socket socket = new Socket(); |
Paul Jensen | 89bb993 | 2018-03-29 07:41:43 -0400 | [diff] [blame] | 254 | boolean failed = true; |
| 255 | try { |
| 256 | bindSocket(socket); |
| 257 | failed = false; |
| 258 | } finally { |
| 259 | if (failed) IoUtils.closeQuietly(socket); |
| 260 | } |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 261 | return socket; |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | /** |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 266 | * Returns a {@link SocketFactory} bound to this network. Any {@link Socket} created by |
| 267 | * this factory will have its traffic sent over this {@code Network}. Note that if this |
| 268 | * {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the |
| 269 | * past or future will cease to work. |
| 270 | * |
| 271 | * @return a {@link SocketFactory} which produces {@link Socket} instances bound to this |
| 272 | * {@code Network}. |
| 273 | */ |
Paul Jensen | 0a363a3 | 2014-05-29 10:12:39 -0400 | [diff] [blame] | 274 | public SocketFactory getSocketFactory() { |
Lorenzo Colitti | 5b37fa2 | 2014-07-29 22:51:27 +0900 | [diff] [blame] | 275 | if (mNetworkBoundSocketFactory == null) { |
| 276 | synchronized (mLock) { |
| 277 | if (mNetworkBoundSocketFactory == null) { |
Chalard Jean | 6823744 | 2018-06-07 13:46:52 +0900 | [diff] [blame] | 278 | mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(); |
Lorenzo Colitti | 5b37fa2 | 2014-07-29 22:51:27 +0900 | [diff] [blame] | 279 | } |
Lorenzo Colitti | c473dc4 | 2014-07-18 01:34:19 +0900 | [diff] [blame] | 280 | } |
Paul Jensen | 2d6f265 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 281 | } |
| 282 | return mNetworkBoundSocketFactory; |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 283 | } |
| 284 | |
Paul Jensen | 07ed074 | 2014-09-08 14:59:09 -0400 | [diff] [blame] | 285 | // TODO: This creates a connection pool and host resolver for |
Lorenzo Colitti | 0ed0a28 | 2014-08-28 17:15:40 -0700 | [diff] [blame] | 286 | // every Network object, instead of one for every NetId. This is |
| 287 | // suboptimal, because an app could potentially have more than one |
| 288 | // Network object for the same NetId, causing increased memory footprint |
| 289 | // and performance penalties due to lack of connection reuse (connection |
| 290 | // setup time, congestion window growth time, etc.). |
| 291 | // |
Paul Jensen | 07ed074 | 2014-09-08 14:59:09 -0400 | [diff] [blame] | 292 | // Instead, investigate only having one connection pool and host resolver |
| 293 | // for every NetId, perhaps by using a static HashMap of NetIds to |
| 294 | // connection pools and host resolvers. The tricky part is deciding when |
| 295 | // to remove a map entry; a WeakHashMap shouldn't be used because whether |
| 296 | // a Network is referenced doesn't correlate with whether a new Network |
| 297 | // will be instantiated in the near future with the same NetID. A good |
| 298 | // solution would involve purging empty (or when all connections are timed |
| 299 | // out) ConnectionPools. |
Tobias Thierer | 69b8b29 | 2017-04-11 22:16:53 +0100 | [diff] [blame] | 300 | private void maybeInitUrlConnectionFactory() { |
Paul Jensen | 07ed074 | 2014-09-08 14:59:09 -0400 | [diff] [blame] | 301 | synchronized (mLock) { |
Tobias Thierer | 69b8b29 | 2017-04-11 22:16:53 +0100 | [diff] [blame] | 302 | if (mUrlConnectionFactory == null) { |
| 303 | // Set configuration on the HttpURLConnectionFactory that will be good for all |
| 304 | // connections created by this Network. Configuration that might vary is left |
| 305 | // until openConnection() and passed as arguments. |
| 306 | Dns dnsLookup = hostname -> Arrays.asList(Network.this.getAllByName(hostname)); |
| 307 | HttpURLConnectionFactory urlConnectionFactory = new HttpURLConnectionFactory(); |
| 308 | urlConnectionFactory.setDns(dnsLookup); // Let traffic go via dnsLookup |
| 309 | // A private connection pool just for this Network. |
| 310 | urlConnectionFactory.setNewConnectionPool(httpMaxConnections, |
Tobias Thierer | 851d806 | 2016-06-01 20:51:45 +0100 | [diff] [blame] | 311 | httpKeepAliveDurationMs, TimeUnit.MILLISECONDS); |
Tobias Thierer | 69b8b29 | 2017-04-11 22:16:53 +0100 | [diff] [blame] | 312 | mUrlConnectionFactory = urlConnectionFactory; |
Lorenzo Colitti | 5b37fa2 | 2014-07-29 22:51:27 +0900 | [diff] [blame] | 313 | } |
Lorenzo Colitti | 5b37fa2 | 2014-07-29 22:51:27 +0900 | [diff] [blame] | 314 | } |
Lorenzo Colitti | 5b37fa2 | 2014-07-29 22:51:27 +0900 | [diff] [blame] | 315 | } |
| 316 | |
| 317 | /** |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 318 | * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent |
| 319 | * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}. |
| 320 | * |
| 321 | * @return a {@code URLConnection} to the resource referred to by this URL. |
| 322 | * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS. |
| 323 | * @throws IOException if an error occurs while opening the connection. |
| 324 | * @see java.net.URL#openConnection() |
Lorenzo Colitti | 5b37fa2 | 2014-07-29 22:51:27 +0900 | [diff] [blame] | 325 | */ |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 326 | public URLConnection openConnection(URL url) throws IOException { |
Paul Jensen | 72db88e | 2015-03-10 10:54:12 -0400 | [diff] [blame] | 327 | final ConnectivityManager cm = ConnectivityManager.getInstanceOrNull(); |
| 328 | if (cm == null) { |
| 329 | throw new IOException("No ConnectivityManager yet constructed, please construct one"); |
| 330 | } |
Paul Jensen | e0bef71 | 2014-12-10 15:12:18 -0500 | [diff] [blame] | 331 | // TODO: Should this be optimized to avoid fetching the global proxy for every request? |
Paul Jensen | cee9b51 | 2015-05-06 07:32:40 -0400 | [diff] [blame] | 332 | final ProxyInfo proxyInfo = cm.getProxyForNetwork(this); |
Tobias Thierer | 69b8b29 | 2017-04-11 22:16:53 +0100 | [diff] [blame] | 333 | final java.net.Proxy proxy; |
Paul Jensen | e0bef71 | 2014-12-10 15:12:18 -0500 | [diff] [blame] | 334 | if (proxyInfo != null) { |
| 335 | proxy = proxyInfo.makeProxy(); |
| 336 | } else { |
| 337 | proxy = java.net.Proxy.NO_PROXY; |
| 338 | } |
| 339 | return openConnection(url, proxy); |
| 340 | } |
| 341 | |
| 342 | /** |
| 343 | * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent |
| 344 | * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}. |
| 345 | * |
| 346 | * @param proxy the proxy through which the connection will be established. |
| 347 | * @return a {@code URLConnection} to the resource referred to by this URL. |
| 348 | * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS. |
| 349 | * @throws IllegalArgumentException if the argument proxy is null. |
| 350 | * @throws IOException if an error occurs while opening the connection. |
| 351 | * @see java.net.URL#openConnection() |
Paul Jensen | e0bef71 | 2014-12-10 15:12:18 -0500 | [diff] [blame] | 352 | */ |
| 353 | public URLConnection openConnection(URL url, java.net.Proxy proxy) throws IOException { |
| 354 | if (proxy == null) throw new IllegalArgumentException("proxy is null"); |
Tobias Thierer | 69b8b29 | 2017-04-11 22:16:53 +0100 | [diff] [blame] | 355 | maybeInitUrlConnectionFactory(); |
| 356 | SocketFactory socketFactory = getSocketFactory(); |
| 357 | return mUrlConnectionFactory.openConnection(url, socketFactory, proxy); |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 358 | } |
| 359 | |
| 360 | /** |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 361 | * Binds the specified {@link DatagramSocket} to this {@code Network}. All data traffic on the |
| 362 | * socket will be sent on this {@code Network}, irrespective of any process-wide network binding |
Paul Jensen | 72db88e | 2015-03-10 10:54:12 -0400 | [diff] [blame] | 363 | * set by {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 364 | * connected. |
| 365 | */ |
| 366 | public void bindSocket(DatagramSocket socket) throws IOException { |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 367 | // Query a property of the underlying socket to ensure that the socket's file descriptor |
| 368 | // exists, is available to bind to a network and is not closed. |
| 369 | socket.getReuseAddress(); |
Erik Kline | d895999 | 2015-06-05 17:37:45 +0900 | [diff] [blame] | 370 | bindSocket(socket.getFileDescriptor$()); |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 371 | } |
| 372 | |
| 373 | /** |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 374 | * Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket |
| 375 | * will be sent on this {@code Network}, irrespective of any process-wide network binding set by |
Paul Jensen | 72db88e | 2015-03-10 10:54:12 -0400 | [diff] [blame] | 376 | * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected. |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 377 | */ |
| 378 | public void bindSocket(Socket socket) throws IOException { |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 379 | // Query a property of the underlying socket to ensure that the socket's file descriptor |
| 380 | // exists, is available to bind to a network and is not closed. |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 381 | socket.getReuseAddress(); |
Erik Kline | d895999 | 2015-06-05 17:37:45 +0900 | [diff] [blame] | 382 | bindSocket(socket.getFileDescriptor$()); |
Sreeram Ramachandran | e15db7c | 2014-10-22 11:10:20 -0700 | [diff] [blame] | 383 | } |
| 384 | |
Erik Kline | d895999 | 2015-06-05 17:37:45 +0900 | [diff] [blame] | 385 | /** |
| 386 | * Binds the specified {@link FileDescriptor} to this {@code Network}. All data traffic on the |
| 387 | * socket represented by this file descriptor will be sent on this {@code Network}, |
| 388 | * irrespective of any process-wide network binding set by |
| 389 | * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected. |
| 390 | */ |
| 391 | public void bindSocket(FileDescriptor fd) throws IOException { |
| 392 | try { |
| 393 | final SocketAddress peer = Os.getpeername(fd); |
| 394 | final InetAddress inetPeer = ((InetSocketAddress) peer).getAddress(); |
| 395 | if (!inetPeer.isAnyLocalAddress()) { |
| 396 | // Apparently, the kernel doesn't update a connected UDP socket's |
| 397 | // routing upon mark changes. |
| 398 | throw new SocketException("Socket is connected"); |
| 399 | } |
| 400 | } catch (ErrnoException e) { |
| 401 | // getpeername() failed. |
| 402 | if (e.errno != OsConstants.ENOTCONN) { |
| 403 | throw e.rethrowAsSocketException(); |
| 404 | } |
| 405 | } catch (ClassCastException e) { |
| 406 | // Wasn't an InetSocketAddress. |
| 407 | throw new SocketException("Only AF_INET/AF_INET6 sockets supported"); |
| 408 | } |
| 409 | |
| 410 | final int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId); |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 411 | if (err != 0) { |
| 412 | // bindSocketToNetwork returns negative errno. |
| 413 | throw new ErrnoException("Binding socket to network " + netId, -err) |
| 414 | .rethrowAsSocketException(); |
| 415 | } |
Lorenzo Colitti | c473dc4 | 2014-07-18 01:34:19 +0900 | [diff] [blame] | 416 | } |
| 417 | |
Erik Kline | 25f3b7b | 2015-03-05 15:13:37 +0900 | [diff] [blame] | 418 | /** |
Paul Jensen | 4af1781 | 2018-03-28 09:19:58 -0400 | [diff] [blame] | 419 | * Returns a {@link Network} object given a handle returned from {@link #getNetworkHandle}. |
| 420 | * |
| 421 | * @param networkHandle a handle returned from {@link #getNetworkHandle}. |
| 422 | * @return A {@link Network} object derived from {@code networkHandle}. |
| 423 | */ |
| 424 | public static Network fromNetworkHandle(long networkHandle) { |
| 425 | if (networkHandle == 0) { |
| 426 | throw new IllegalArgumentException( |
| 427 | "Network.fromNetworkHandle refusing to instantiate NETID_UNSET Network."); |
| 428 | } |
| 429 | if ((networkHandle & ((1L << HANDLE_MAGIC_SIZE) - 1)) != HANDLE_MAGIC |
| 430 | || networkHandle < 0) { |
| 431 | throw new IllegalArgumentException( |
| 432 | "Value passed to fromNetworkHandle() is not a network handle."); |
| 433 | } |
| 434 | return new Network((int) (networkHandle >> HANDLE_MAGIC_SIZE)); |
| 435 | } |
| 436 | |
| 437 | /** |
Erik Kline | 25f3b7b | 2015-03-05 15:13:37 +0900 | [diff] [blame] | 438 | * Returns a handle representing this {@code Network}, for use with the NDK API. |
| 439 | */ |
| 440 | public long getNetworkHandle() { |
| 441 | // The network handle is explicitly not the same as the netId. |
| 442 | // |
| 443 | // The netId is an implementation detail which might be changed in the |
| 444 | // future, or which alone (i.e. in the absence of some additional |
| 445 | // context) might not be sufficient to fully identify a Network. |
| 446 | // |
| 447 | // As such, the intention is to prevent accidental misuse of the API |
| 448 | // that might result if a developer assumed that handles and netIds |
| 449 | // were identical and passing a netId to a call expecting a handle |
| 450 | // "just worked". Such accidental misuse, if widely deployed, might |
| 451 | // prevent future changes to the semantics of the netId field or |
| 452 | // inhibit the expansion of state required for Network objects. |
| 453 | // |
| 454 | // This extra layer of indirection might be seen as paranoia, and might |
| 455 | // never end up being necessary, but the added complexity is trivial. |
| 456 | // At some future date it may be desirable to realign the handle with |
| 457 | // Multiple Provisioning Domains API recommendations, as made by the |
| 458 | // IETF mif working group. |
Erik Kline | e1a6cf2 | 2015-05-14 15:40:07 +0900 | [diff] [blame] | 459 | if (netId == 0) { |
| 460 | return 0L; // make this zero condition obvious for debugging |
| 461 | } |
Paul Jensen | 4af1781 | 2018-03-28 09:19:58 -0400 | [diff] [blame] | 462 | return (((long) netId) << HANDLE_MAGIC_SIZE) | HANDLE_MAGIC; |
Erik Kline | 25f3b7b | 2015-03-05 15:13:37 +0900 | [diff] [blame] | 463 | } |
| 464 | |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 465 | // implement the Parcelable interface |
| 466 | public int describeContents() { |
| 467 | return 0; |
| 468 | } |
| 469 | public void writeToParcel(Parcel dest, int flags) { |
| 470 | dest.writeInt(netId); |
| 471 | } |
| 472 | |
Jeff Sharkey | 9e8f83d | 2019-02-28 12:06:45 -0700 | [diff] [blame] | 473 | public static final @android.annotation.NonNull Creator<Network> CREATOR = |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 474 | new Creator<Network>() { |
| 475 | public Network createFromParcel(Parcel in) { |
| 476 | int netId = in.readInt(); |
| 477 | |
| 478 | return new Network(netId); |
| 479 | } |
| 480 | |
| 481 | public Network[] newArray(int size) { |
| 482 | return new Network[size]; |
| 483 | } |
| 484 | }; |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 485 | |
Robert Greenwalt | 2c7bf2c | 2014-06-23 16:07:43 -0700 | [diff] [blame] | 486 | @Override |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 487 | public boolean equals(Object obj) { |
Chalard Jean | 6823744 | 2018-06-07 13:46:52 +0900 | [diff] [blame] | 488 | if (!(obj instanceof Network)) return false; |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 489 | Network other = (Network)obj; |
| 490 | return this.netId == other.netId; |
| 491 | } |
| 492 | |
Robert Greenwalt | 2c7bf2c | 2014-06-23 16:07:43 -0700 | [diff] [blame] | 493 | @Override |
Robert Greenwalt | 8595626 | 2014-05-18 20:29:39 -0700 | [diff] [blame] | 494 | public int hashCode() { |
| 495 | return netId * 11; |
| 496 | } |
Robert Greenwalt | 2c7bf2c | 2014-06-23 16:07:43 -0700 | [diff] [blame] | 497 | |
| 498 | @Override |
| 499 | public String toString() { |
| 500 | return Integer.toString(netId); |
| 501 | } |
Kweku Adams | 85f2fbc | 2017-12-18 12:04:12 -0800 | [diff] [blame] | 502 | |
| 503 | /** @hide */ |
| 504 | public void writeToProto(ProtoOutputStream proto, long fieldId) { |
| 505 | final long token = proto.start(fieldId); |
| 506 | proto.write(NetworkProto.NET_ID, netId); |
| 507 | proto.end(token); |
| 508 | } |
Robert Greenwalt | 9ba9c58 | 2014-03-19 17:56:12 -0700 | [diff] [blame] | 509 | } |