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 17package android.net; 18 19import android.os.Parcel; 20import android.os.Parcelable; 21import android.system.ErrnoException; 22import android.system.Os; 23import android.system.OsConstants; 24import android.util.proto.ProtoOutputStream; 25 26import com.android.okhttp.internalandroidapi.Dns; 27import com.android.okhttp.internalandroidapi.HttpURLConnectionFactory; 28 29import libcore.io.IoUtils; 30 31import java.io.FileDescriptor; 32import java.io.IOException; 33import java.net.DatagramSocket; 34import java.net.InetAddress; 35import java.net.InetSocketAddress; 36import java.net.MalformedURLException; 37import java.net.Socket; 38import java.net.SocketAddress; 39import java.net.SocketException; 40import java.net.URL; 41import java.net.URLConnection; 42import java.net.UnknownHostException; 43import java.util.Arrays; 44import java.util.concurrent.TimeUnit; 45 46import javax.net.SocketFactory; 47 48/** 49 * Identifies a {@code Network}. This is supplied to applications via 50 * {@link ConnectivityManager.NetworkCallback} in response to the active 51 * {@link ConnectivityManager#requestNetwork} or passive 52 * {@link ConnectivityManager#registerNetworkCallback} calls. 53 * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis 54 * through a targeted {@link SocketFactory} or process-wide via 55 * {@link ConnectivityManager#bindProcessToNetwork}. 56 */ 57public class Network implements Parcelable { 58 59 /** 60 * @hide 61 */ 62 public final int netId; 63 64 // Objects used to perform per-network operations such as getSocketFactory 65 // and openConnection, and a lock to protect access to them. 66 private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null; 67 // 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; 70 private final Object mLock = new Object(); 71 72 // 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. 82 // 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; 87 88 // 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 103 /** 104 * @hide 105 */ 106 public Network(int netId) { 107 this.netId = netId; 108 } 109 110 /** 111 * @hide 112 */ 113 public Network(Network that) { 114 this.netId = that.netId; 115 } 116 117 /** 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 { 126 return InetAddress.getAllByNameOnNet(host, getNetIdForResolv()); 127 } 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 { 140 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; 166 } 167 168 /** 169 * 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 179 private Socket connectToHost(String host, int port, SocketAddress localAddress) 180 throws IOException { 181 // Lookup addresses only on this Network. 182 InetAddress[] hostAddresses = getAllByName(host); 183 // Try all addresses. 184 for (int i = 0; i < hostAddresses.length; i++) { 185 try { 186 Socket socket = createSocket(); 187 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 } 196 } catch (IOException e) { 197 if (i == (hostAddresses.length - 1)) throw e; 198 } 199 } 200 throw new UnknownHostException(host); 201 } 202 203 @Override 204 public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { 205 return connectToHost(host, port, new InetSocketAddress(localHost, localPort)); 206 } 207 208 @Override 209 public Socket createSocket(InetAddress address, int port, InetAddress localAddress, 210 int localPort) throws IOException { 211 Socket socket = createSocket(); 212 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 } 220 return socket; 221 } 222 223 @Override 224 public Socket createSocket(InetAddress host, int port) throws IOException { 225 Socket socket = createSocket(); 226 boolean failed = true; 227 try { 228 socket.connect(new InetSocketAddress(host, port)); 229 failed = false; 230 } finally { 231 if (failed) IoUtils.closeQuietly(socket); 232 } 233 return socket; 234 } 235 236 @Override 237 public Socket createSocket(String host, int port) throws IOException { 238 return connectToHost(host, port, null); 239 } 240 241 @Override 242 public Socket createSocket() throws IOException { 243 Socket socket = new Socket(); 244 boolean failed = true; 245 try { 246 bindSocket(socket); 247 failed = false; 248 } finally { 249 if (failed) IoUtils.closeQuietly(socket); 250 } 251 return socket; 252 } 253 } 254 255 /** 256 * 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 */ 264 public SocketFactory getSocketFactory() { 265 if (mNetworkBoundSocketFactory == null) { 266 synchronized (mLock) { 267 if (mNetworkBoundSocketFactory == null) { 268 mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId); 269 } 270 } 271 } 272 return mNetworkBoundSocketFactory; 273 } 274 275 // TODO: This creates a connection pool and host resolver for 276 // 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 // 282 // 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. 290 private void maybeInitUrlConnectionFactory() { 291 synchronized (mLock) { 292 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, 301 httpKeepAliveDurationMs, TimeUnit.MILLISECONDS); 302 mUrlConnectionFactory = urlConnectionFactory; 303 } 304 } 305 } 306 307 /** 308 * 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() 315 */ 316 public URLConnection openConnection(URL url) throws IOException { 317 final ConnectivityManager cm = ConnectivityManager.getInstanceOrNull(); 318 if (cm == null) { 319 throw new IOException("No ConnectivityManager yet constructed, please construct one"); 320 } 321 // TODO: Should this be optimized to avoid fetching the global proxy for every request? 322 final ProxyInfo proxyInfo = cm.getProxyForNetwork(this); 323 final java.net.Proxy proxy; 324 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() 342 */ 343 public URLConnection openConnection(URL url, java.net.Proxy proxy) throws IOException { 344 if (proxy == null) throw new IllegalArgumentException("proxy is null"); 345 maybeInitUrlConnectionFactory(); 346 SocketFactory socketFactory = getSocketFactory(); 347 return mUrlConnectionFactory.openConnection(url, socketFactory, proxy); 348 } 349 350 /** 351 * 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 353 * set by {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be 354 * connected. 355 */ 356 public void bindSocket(DatagramSocket socket) throws IOException { 357 // 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(); 360 bindSocket(socket.getFileDescriptor$()); 361 } 362 363 /** 364 * 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 366 * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected. 367 */ 368 public void bindSocket(Socket socket) throws IOException { 369 // 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. 371 socket.getReuseAddress(); 372 bindSocket(socket.getFileDescriptor$()); 373 } 374 375 /** 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); 401 if (err != 0) { 402 // bindSocketToNetwork returns negative errno. 403 throw new ErrnoException("Binding socket to network " + netId, -err) 404 .rethrowAsSocketException(); 405 } 406 } 407 408 /** 409 * 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 /** 428 * 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. 449 if (netId == 0) { 450 return 0L; // make this zero condition obvious for debugging 451 } 452 return (((long) netId) << HANDLE_MAGIC_SIZE) | HANDLE_MAGIC; 453 } 454 455 // 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 }; 475 476 @Override 477 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 483 @Override 484 public int hashCode() { 485 return netId * 11; 486 } 487 488 @Override 489 public String toString() { 490 return Integer.toString(netId); 491 } 492 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 } 499} 500