Network.java revision 50a01d89606b40dd151ad407d05c3b2867bbdbad
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.Parcelable; 20import android.os.Parcel; 21import android.system.ErrnoException; 22 23import java.io.IOException; 24import java.net.InetAddress; 25import java.net.InetSocketAddress; 26import java.net.MalformedURLException; 27import java.net.Socket; 28import java.net.SocketAddress; 29import java.net.SocketException; 30import java.net.UnknownHostException; 31import java.net.URL; 32import java.net.URLConnection; 33import javax.net.SocketFactory; 34 35import com.android.okhttp.ConnectionPool; 36import com.android.okhttp.HttpHandler; 37import com.android.okhttp.HttpsHandler; 38import com.android.okhttp.OkHttpClient; 39import com.android.okhttp.OkUrlFactory; 40import com.android.okhttp.internal.Internal; 41 42/** 43 * Identifies a {@code Network}. This is supplied to applications via 44 * {@link ConnectivityManager.NetworkCallback} in response to the active 45 * {@link ConnectivityManager#requestNetwork} or passive 46 * {@link ConnectivityManager#registerNetworkCallback} calls. 47 * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis 48 * through a targeted {@link SocketFactory} or process-wide via 49 * {@link ConnectivityManager#setProcessDefaultNetwork}. 50 */ 51public class Network implements Parcelable { 52 53 /** 54 * @hide 55 */ 56 public final int netId; 57 58 // Objects used to perform per-network operations such as getSocketFactory 59 // and openConnection, and a lock to protect access to them. 60 private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null; 61 // mLock should be used to control write access to mConnectionPool and mNetwork. 62 // maybeInitHttpClient() must be called prior to reading either variable. 63 private volatile ConnectionPool mConnectionPool = null; 64 private volatile com.android.okhttp.internal.Network mNetwork = null; 65 private Object mLock = new Object(); 66 67 // Default connection pool values. These are evaluated at startup, just 68 // like the OkHttp code. Also like the OkHttp code, we will throw parse 69 // exceptions at class loading time if the properties are set but are not 70 // valid integers. 71 private static final boolean httpKeepAlive = 72 Boolean.parseBoolean(System.getProperty("http.keepAlive", "true")); 73 private static final int httpMaxConnections = 74 httpKeepAlive ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0; 75 private static final long httpKeepAliveDurationMs = 76 Long.parseLong(System.getProperty("http.keepAliveDuration", "300000")); // 5 minutes. 77 78 /** 79 * @hide 80 */ 81 public Network(int netId) { 82 this.netId = netId; 83 } 84 85 /** 86 * @hide 87 */ 88 public Network(Network that) { 89 this.netId = that.netId; 90 } 91 92 /** 93 * Operates the same as {@code InetAddress.getAllByName} except that host 94 * resolution is done on this network. 95 * 96 * @param host the hostname or literal IP string to be resolved. 97 * @return the array of addresses associated with the specified host. 98 * @throws UnknownHostException if the address lookup fails. 99 */ 100 public InetAddress[] getAllByName(String host) throws UnknownHostException { 101 return InetAddress.getAllByNameOnNet(host, netId); 102 } 103 104 /** 105 * Operates the same as {@code InetAddress.getByName} except that host 106 * resolution is done on this network. 107 * 108 * @param host 109 * the hostName to be resolved to an address or {@code null}. 110 * @return the {@code InetAddress} instance representing the host. 111 * @throws UnknownHostException 112 * if the address lookup fails. 113 */ 114 public InetAddress getByName(String host) throws UnknownHostException { 115 return InetAddress.getByNameOnNet(host, netId); 116 } 117 118 /** 119 * A {@code SocketFactory} that produces {@code Socket}'s bound to this network. 120 */ 121 private class NetworkBoundSocketFactory extends SocketFactory { 122 private final int mNetId; 123 124 public NetworkBoundSocketFactory(int netId) { 125 super(); 126 mNetId = netId; 127 } 128 129 private Socket connectToHost(String host, int port, SocketAddress localAddress) 130 throws IOException { 131 // Lookup addresses only on this Network. 132 InetAddress[] hostAddresses = getAllByName(host); 133 // Try all addresses. 134 for (int i = 0; i < hostAddresses.length; i++) { 135 try { 136 Socket socket = createSocket(); 137 if (localAddress != null) socket.bind(localAddress); 138 socket.connect(new InetSocketAddress(hostAddresses[i], port)); 139 return socket; 140 } catch (IOException e) { 141 if (i == (hostAddresses.length - 1)) throw e; 142 } 143 } 144 throw new UnknownHostException(host); 145 } 146 147 @Override 148 public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { 149 return connectToHost(host, port, new InetSocketAddress(localHost, localPort)); 150 } 151 152 @Override 153 public Socket createSocket(InetAddress address, int port, InetAddress localAddress, 154 int localPort) throws IOException { 155 Socket socket = createSocket(); 156 socket.bind(new InetSocketAddress(localAddress, localPort)); 157 socket.connect(new InetSocketAddress(address, port)); 158 return socket; 159 } 160 161 @Override 162 public Socket createSocket(InetAddress host, int port) throws IOException { 163 Socket socket = createSocket(); 164 socket.connect(new InetSocketAddress(host, port)); 165 return socket; 166 } 167 168 @Override 169 public Socket createSocket(String host, int port) throws IOException { 170 return connectToHost(host, port, null); 171 } 172 173 @Override 174 public Socket createSocket() throws IOException { 175 Socket socket = new Socket(); 176 bindSocket(socket); 177 return socket; 178 } 179 } 180 181 /** 182 * Returns a {@link SocketFactory} bound to this network. Any {@link Socket} created by 183 * this factory will have its traffic sent over this {@code Network}. Note that if this 184 * {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the 185 * past or future will cease to work. 186 * 187 * @return a {@link SocketFactory} which produces {@link Socket} instances bound to this 188 * {@code Network}. 189 */ 190 public SocketFactory getSocketFactory() { 191 if (mNetworkBoundSocketFactory == null) { 192 synchronized (mLock) { 193 if (mNetworkBoundSocketFactory == null) { 194 mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId); 195 } 196 } 197 } 198 return mNetworkBoundSocketFactory; 199 } 200 201 // TODO: This creates a connection pool and host resolver for 202 // every Network object, instead of one for every NetId. This is 203 // suboptimal, because an app could potentially have more than one 204 // Network object for the same NetId, causing increased memory footprint 205 // and performance penalties due to lack of connection reuse (connection 206 // setup time, congestion window growth time, etc.). 207 // 208 // Instead, investigate only having one connection pool and host resolver 209 // for every NetId, perhaps by using a static HashMap of NetIds to 210 // connection pools and host resolvers. The tricky part is deciding when 211 // to remove a map entry; a WeakHashMap shouldn't be used because whether 212 // a Network is referenced doesn't correlate with whether a new Network 213 // will be instantiated in the near future with the same NetID. A good 214 // solution would involve purging empty (or when all connections are timed 215 // out) ConnectionPools. 216 private void maybeInitHttpClient() { 217 synchronized (mLock) { 218 if (mNetwork == null) { 219 mNetwork = new com.android.okhttp.internal.Network() { 220 @Override 221 public InetAddress[] resolveInetAddresses(String host) throws UnknownHostException { 222 return Network.this.getAllByName(host); 223 } 224 }; 225 } 226 if (mConnectionPool == null) { 227 mConnectionPool = new ConnectionPool(httpMaxConnections, 228 httpKeepAliveDurationMs); 229 } 230 } 231 } 232 233 /** 234 * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent 235 * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}. 236 * 237 * @return a {@code URLConnection} to the resource referred to by this URL. 238 * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS. 239 * @throws IOException if an error occurs while opening the connection. 240 * @see java.net.URL#openConnection() 241 */ 242 public URLConnection openConnection(URL url) throws IOException { 243 maybeInitHttpClient(); 244 String protocol = url.getProtocol(); 245 OkUrlFactory okUrlFactory; 246 // TODO: HttpHandler creates OkUrlFactory instances that share the default ResponseCache. 247 // Could this cause unexpected behavior? 248 // TODO: Should the network's proxy be specified? 249 if (protocol.equals("http")) { 250 okUrlFactory = HttpHandler.createHttpOkUrlFactory(null /* proxy */); 251 } else if (protocol.equals("https")) { 252 okUrlFactory = HttpsHandler.createHttpsOkUrlFactory(null /* proxy */); 253 } else { 254 // OkHttp only supports HTTP and HTTPS and returns a null URLStreamHandler if 255 // passed another protocol. 256 throw new MalformedURLException("Invalid URL or unrecognized protocol " + protocol); 257 } 258 OkHttpClient client = okUrlFactory.client(); 259 client.setSocketFactory(getSocketFactory()).setConnectionPool(mConnectionPool); 260 261 // Use internal APIs to change the Network. 262 Internal.instance.setNetwork(client, mNetwork); 263 264 return okUrlFactory.open(url); 265 } 266 267 /** 268 * Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket 269 * will be sent on this {@code Network}, irrespective of any process-wide network binding set by 270 * {@link ConnectivityManager#setProcessDefaultNetwork}. The socket must not be connected. 271 */ 272 public void bindSocket(Socket socket) throws IOException { 273 if (socket.isConnected()) { 274 throw new SocketException("Socket is connected"); 275 } 276 // Query a property of the underlying socket to ensure the underlying 277 // socket exists so a file descriptor is available to bind to a network. 278 socket.getReuseAddress(); 279 int err = NetworkUtils.bindSocketToNetwork(socket.getFileDescriptor$().getInt$(), netId); 280 if (err != 0) { 281 // bindSocketToNetwork returns negative errno. 282 throw new ErrnoException("Binding socket to network " + netId, -err) 283 .rethrowAsSocketException(); 284 } 285 } 286 287 // implement the Parcelable interface 288 public int describeContents() { 289 return 0; 290 } 291 public void writeToParcel(Parcel dest, int flags) { 292 dest.writeInt(netId); 293 } 294 295 public static final Creator<Network> CREATOR = 296 new Creator<Network>() { 297 public Network createFromParcel(Parcel in) { 298 int netId = in.readInt(); 299 300 return new Network(netId); 301 } 302 303 public Network[] newArray(int size) { 304 return new Network[size]; 305 } 306 }; 307 308 @Override 309 public boolean equals(Object obj) { 310 if (obj instanceof Network == false) return false; 311 Network other = (Network)obj; 312 return this.netId == other.netId; 313 } 314 315 @Override 316 public int hashCode() { 317 return netId * 11; 318 } 319 320 @Override 321 public String toString() { 322 return Integer.toString(netId); 323 } 324} 325