Network.java revision 4af1781776f304c848e1a0ece34a0f5f3b5780ff
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 java.io.FileDescriptor;
30import java.io.IOException;
31import java.net.DatagramSocket;
32import java.net.InetAddress;
33import java.net.InetSocketAddress;
34import java.net.MalformedURLException;
35import java.net.Socket;
36import java.net.SocketAddress;
37import java.net.SocketException;
38import java.net.URL;
39import java.net.URLConnection;
40import java.net.UnknownHostException;
41import java.util.Arrays;
42import java.util.concurrent.TimeUnit;
43
44import javax.net.SocketFactory;
45
46/**
47 * Identifies a {@code Network}.  This is supplied to applications via
48 * {@link ConnectivityManager.NetworkCallback} in response to the active
49 * {@link ConnectivityManager#requestNetwork} or passive
50 * {@link ConnectivityManager#registerNetworkCallback} calls.
51 * It is used to direct traffic to the given {@code Network}, either on a {@link Socket} basis
52 * through a targeted {@link SocketFactory} or process-wide via
53 * {@link ConnectivityManager#bindProcessToNetwork}.
54 */
55public class Network implements Parcelable {
56
57    /**
58     * @hide
59     */
60    public final int netId;
61
62    // Objects used to perform per-network operations such as getSocketFactory
63    // and openConnection, and a lock to protect access to them.
64    private volatile NetworkBoundSocketFactory mNetworkBoundSocketFactory = null;
65    // mLock should be used to control write access to mUrlConnectionFactory.
66    // maybeInitUrlConnectionFactory() must be called prior to reading this field.
67    private volatile HttpURLConnectionFactory mUrlConnectionFactory;
68    private final Object mLock = new Object();
69
70    // Default connection pool values. These are evaluated at startup, just
71    // like the OkHttp code. Also like the OkHttp code, we will throw parse
72    // exceptions at class loading time if the properties are set but are not
73    // valid integers.
74    private static final boolean httpKeepAlive =
75            Boolean.parseBoolean(System.getProperty("http.keepAlive", "true"));
76    private static final int httpMaxConnections =
77            httpKeepAlive ? Integer.parseInt(System.getProperty("http.maxConnections", "5")) : 0;
78    private static final long httpKeepAliveDurationMs =
79            Long.parseLong(System.getProperty("http.keepAliveDuration", "300000"));  // 5 minutes.
80    // Value used to obfuscate network handle longs.
81    // The HANDLE_MAGIC value MUST be kept in sync with the corresponding
82    // value in the native/android/net.c NDK implementation.
83    private static final long HANDLE_MAGIC = 0xcafed00dL;
84    private static final int HANDLE_MAGIC_SIZE = 32;
85
86    /**
87     * @hide
88     */
89    public Network(int netId) {
90        this.netId = netId;
91    }
92
93    /**
94     * @hide
95     */
96    public Network(Network that) {
97        this.netId = that.netId;
98    }
99
100    /**
101     * Operates the same as {@code InetAddress.getAllByName} except that host
102     * resolution is done on this network.
103     *
104     * @param host the hostname or literal IP string to be resolved.
105     * @return the array of addresses associated with the specified host.
106     * @throws UnknownHostException if the address lookup fails.
107     */
108    public InetAddress[] getAllByName(String host) throws UnknownHostException {
109        return InetAddress.getAllByNameOnNet(host, netId);
110    }
111
112    /**
113     * Operates the same as {@code InetAddress.getByName} except that host
114     * resolution is done on this network.
115     *
116     * @param host
117     *            the hostName to be resolved to an address or {@code null}.
118     * @return the {@code InetAddress} instance representing the host.
119     * @throws UnknownHostException
120     *             if the address lookup fails.
121     */
122    public InetAddress getByName(String host) throws UnknownHostException {
123        return InetAddress.getByNameOnNet(host, netId);
124    }
125
126    /**
127     * A {@code SocketFactory} that produces {@code Socket}'s bound to this network.
128     */
129    private class NetworkBoundSocketFactory extends SocketFactory {
130        private final int mNetId;
131
132        public NetworkBoundSocketFactory(int netId) {
133            super();
134            mNetId = netId;
135        }
136
137        private Socket connectToHost(String host, int port, SocketAddress localAddress)
138                throws IOException {
139            // Lookup addresses only on this Network.
140            InetAddress[] hostAddresses = getAllByName(host);
141            // Try all addresses.
142            for (int i = 0; i < hostAddresses.length; i++) {
143                try {
144                    Socket socket = createSocket();
145                    if (localAddress != null) socket.bind(localAddress);
146                    socket.connect(new InetSocketAddress(hostAddresses[i], port));
147                    return socket;
148                } catch (IOException e) {
149                    if (i == (hostAddresses.length - 1)) throw e;
150                }
151            }
152            throw new UnknownHostException(host);
153        }
154
155        @Override
156        public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
157            return connectToHost(host, port, new InetSocketAddress(localHost, localPort));
158        }
159
160        @Override
161        public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
162                int localPort) throws IOException {
163            Socket socket = createSocket();
164            socket.bind(new InetSocketAddress(localAddress, localPort));
165            socket.connect(new InetSocketAddress(address, port));
166            return socket;
167        }
168
169        @Override
170        public Socket createSocket(InetAddress host, int port) throws IOException {
171            Socket socket = createSocket();
172            socket.connect(new InetSocketAddress(host, port));
173            return socket;
174        }
175
176        @Override
177        public Socket createSocket(String host, int port) throws IOException {
178            return connectToHost(host, port, null);
179        }
180
181        @Override
182        public Socket createSocket() throws IOException {
183            Socket socket = new Socket();
184            bindSocket(socket);
185            return socket;
186        }
187    }
188
189    /**
190     * Returns a {@link SocketFactory} bound to this network.  Any {@link Socket} created by
191     * this factory will have its traffic sent over this {@code Network}.  Note that if this
192     * {@code Network} ever disconnects, this factory and any {@link Socket} it produced in the
193     * past or future will cease to work.
194     *
195     * @return a {@link SocketFactory} which produces {@link Socket} instances bound to this
196     *         {@code Network}.
197     */
198    public SocketFactory getSocketFactory() {
199        if (mNetworkBoundSocketFactory == null) {
200            synchronized (mLock) {
201                if (mNetworkBoundSocketFactory == null) {
202                    mNetworkBoundSocketFactory = new NetworkBoundSocketFactory(netId);
203                }
204            }
205        }
206        return mNetworkBoundSocketFactory;
207    }
208
209    // TODO: This creates a connection pool and host resolver for
210    // every Network object, instead of one for every NetId. This is
211    // suboptimal, because an app could potentially have more than one
212    // Network object for the same NetId, causing increased memory footprint
213    // and performance penalties due to lack of connection reuse (connection
214    // setup time, congestion window growth time, etc.).
215    //
216    // Instead, investigate only having one connection pool and host resolver
217    // for every NetId, perhaps by using a static HashMap of NetIds to
218    // connection pools and host resolvers. The tricky part is deciding when
219    // to remove a map entry; a WeakHashMap shouldn't be used because whether
220    // a Network is referenced doesn't correlate with whether a new Network
221    // will be instantiated in the near future with the same NetID. A good
222    // solution would involve purging empty (or when all connections are timed
223    // out) ConnectionPools.
224    private void maybeInitUrlConnectionFactory() {
225        synchronized (mLock) {
226            if (mUrlConnectionFactory == null) {
227                // Set configuration on the HttpURLConnectionFactory that will be good for all
228                // connections created by this Network. Configuration that might vary is left
229                // until openConnection() and passed as arguments.
230                Dns dnsLookup = hostname -> Arrays.asList(Network.this.getAllByName(hostname));
231                HttpURLConnectionFactory urlConnectionFactory = new HttpURLConnectionFactory();
232                urlConnectionFactory.setDns(dnsLookup); // Let traffic go via dnsLookup
233                // A private connection pool just for this Network.
234                urlConnectionFactory.setNewConnectionPool(httpMaxConnections,
235                        httpKeepAliveDurationMs, TimeUnit.MILLISECONDS);
236                mUrlConnectionFactory = urlConnectionFactory;
237            }
238        }
239    }
240
241    /**
242     * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
243     * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
244     *
245     * @return a {@code URLConnection} to the resource referred to by this URL.
246     * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
247     * @throws IOException if an error occurs while opening the connection.
248     * @see java.net.URL#openConnection()
249     */
250    public URLConnection openConnection(URL url) throws IOException {
251        final ConnectivityManager cm = ConnectivityManager.getInstanceOrNull();
252        if (cm == null) {
253            throw new IOException("No ConnectivityManager yet constructed, please construct one");
254        }
255        // TODO: Should this be optimized to avoid fetching the global proxy for every request?
256        final ProxyInfo proxyInfo = cm.getProxyForNetwork(this);
257        final java.net.Proxy proxy;
258        if (proxyInfo != null) {
259            proxy = proxyInfo.makeProxy();
260        } else {
261            proxy = java.net.Proxy.NO_PROXY;
262        }
263        return openConnection(url, proxy);
264    }
265
266    /**
267     * Opens the specified {@link URL} on this {@code Network}, such that all traffic will be sent
268     * on this Network. The URL protocol must be {@code HTTP} or {@code HTTPS}.
269     *
270     * @param proxy the proxy through which the connection will be established.
271     * @return a {@code URLConnection} to the resource referred to by this URL.
272     * @throws MalformedURLException if the URL protocol is not HTTP or HTTPS.
273     * @throws IllegalArgumentException if the argument proxy is null.
274     * @throws IOException if an error occurs while opening the connection.
275     * @see java.net.URL#openConnection()
276     */
277    public URLConnection openConnection(URL url, java.net.Proxy proxy) throws IOException {
278        if (proxy == null) throw new IllegalArgumentException("proxy is null");
279        maybeInitUrlConnectionFactory();
280        SocketFactory socketFactory = getSocketFactory();
281        return mUrlConnectionFactory.openConnection(url, socketFactory, proxy);
282    }
283
284    /**
285     * Binds the specified {@link DatagramSocket} to this {@code Network}. All data traffic on the
286     * socket will be sent on this {@code Network}, irrespective of any process-wide network binding
287     * set by {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be
288     * connected.
289     */
290    public void bindSocket(DatagramSocket socket) throws IOException {
291        // Query a property of the underlying socket to ensure that the socket's file descriptor
292        // exists, is available to bind to a network and is not closed.
293        socket.getReuseAddress();
294        bindSocket(socket.getFileDescriptor$());
295    }
296
297    /**
298     * Binds the specified {@link Socket} to this {@code Network}. All data traffic on the socket
299     * will be sent on this {@code Network}, irrespective of any process-wide network binding set by
300     * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
301     */
302    public void bindSocket(Socket socket) throws IOException {
303        // Query a property of the underlying socket to ensure that the socket's file descriptor
304        // exists, is available to bind to a network and is not closed.
305        socket.getReuseAddress();
306        bindSocket(socket.getFileDescriptor$());
307    }
308
309    /**
310     * Binds the specified {@link FileDescriptor} to this {@code Network}. All data traffic on the
311     * socket represented by this file descriptor will be sent on this {@code Network},
312     * irrespective of any process-wide network binding set by
313     * {@link ConnectivityManager#bindProcessToNetwork}. The socket must not be connected.
314     */
315    public void bindSocket(FileDescriptor fd) throws IOException {
316        try {
317            final SocketAddress peer = Os.getpeername(fd);
318            final InetAddress inetPeer = ((InetSocketAddress) peer).getAddress();
319            if (!inetPeer.isAnyLocalAddress()) {
320                // Apparently, the kernel doesn't update a connected UDP socket's
321                // routing upon mark changes.
322                throw new SocketException("Socket is connected");
323            }
324        } catch (ErrnoException e) {
325            // getpeername() failed.
326            if (e.errno != OsConstants.ENOTCONN) {
327                throw e.rethrowAsSocketException();
328            }
329        } catch (ClassCastException e) {
330            // Wasn't an InetSocketAddress.
331            throw new SocketException("Only AF_INET/AF_INET6 sockets supported");
332        }
333
334        final int err = NetworkUtils.bindSocketToNetwork(fd.getInt$(), netId);
335        if (err != 0) {
336            // bindSocketToNetwork returns negative errno.
337            throw new ErrnoException("Binding socket to network " + netId, -err)
338                    .rethrowAsSocketException();
339        }
340    }
341
342    /**
343     * Returns a {@link Network} object given a handle returned from {@link #getNetworkHandle}.
344     *
345     * @param networkHandle a handle returned from {@link #getNetworkHandle}.
346     * @return A {@link Network} object derived from {@code networkHandle}.
347     */
348    public static Network fromNetworkHandle(long networkHandle) {
349        if (networkHandle == 0) {
350            throw new IllegalArgumentException(
351                    "Network.fromNetworkHandle refusing to instantiate NETID_UNSET Network.");
352        }
353        if ((networkHandle & ((1L << HANDLE_MAGIC_SIZE) - 1)) != HANDLE_MAGIC
354                || networkHandle < 0) {
355            throw new IllegalArgumentException(
356                    "Value passed to fromNetworkHandle() is not a network handle.");
357        }
358        return new Network((int) (networkHandle >> HANDLE_MAGIC_SIZE));
359    }
360
361    /**
362     * Returns a handle representing this {@code Network}, for use with the NDK API.
363     */
364    public long getNetworkHandle() {
365        // The network handle is explicitly not the same as the netId.
366        //
367        // The netId is an implementation detail which might be changed in the
368        // future, or which alone (i.e. in the absence of some additional
369        // context) might not be sufficient to fully identify a Network.
370        //
371        // As such, the intention is to prevent accidental misuse of the API
372        // that might result if a developer assumed that handles and netIds
373        // were identical and passing a netId to a call expecting a handle
374        // "just worked".  Such accidental misuse, if widely deployed, might
375        // prevent future changes to the semantics of the netId field or
376        // inhibit the expansion of state required for Network objects.
377        //
378        // This extra layer of indirection might be seen as paranoia, and might
379        // never end up being necessary, but the added complexity is trivial.
380        // At some future date it may be desirable to realign the handle with
381        // Multiple Provisioning Domains API recommendations, as made by the
382        // IETF mif working group.
383        if (netId == 0) {
384            return 0L;  // make this zero condition obvious for debugging
385        }
386        return (((long) netId) << HANDLE_MAGIC_SIZE) | HANDLE_MAGIC;
387    }
388
389    // implement the Parcelable interface
390    public int describeContents() {
391        return 0;
392    }
393    public void writeToParcel(Parcel dest, int flags) {
394        dest.writeInt(netId);
395    }
396
397    public static final Creator<Network> CREATOR =
398        new Creator<Network>() {
399            public Network createFromParcel(Parcel in) {
400                int netId = in.readInt();
401
402                return new Network(netId);
403            }
404
405            public Network[] newArray(int size) {
406                return new Network[size];
407            }
408    };
409
410    @Override
411    public boolean equals(Object obj) {
412        if (obj instanceof Network == false) return false;
413        Network other = (Network)obj;
414        return this.netId == other.netId;
415    }
416
417    @Override
418    public int hashCode() {
419        return netId * 11;
420    }
421
422    @Override
423    public String toString() {
424        return Integer.toString(netId);
425    }
426
427    /** @hide */
428    public void writeToProto(ProtoOutputStream proto, long fieldId) {
429        final long token = proto.start(fieldId);
430        proto.write(NetworkProto.NET_ID, netId);
431        proto.end(token);
432    }
433}
434