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