NetworkRequest.java revision d778da33d91956f3eb44bb3a6e8bd7570d088315
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.annotation.NonNull;
20import android.net.NetworkCapabilities.NetCapability;
21import android.net.NetworkCapabilities.Transport;
22import android.os.Parcel;
23import android.os.Parcelable;
24import android.os.Process;
25import android.text.TextUtils;
26import android.util.proto.ProtoOutputStream;
27
28import java.util.Objects;
29import java.util.Set;
30
31/**
32 * Defines a request for a network, made through {@link NetworkRequest.Builder} and used
33 * to request a network via {@link ConnectivityManager#requestNetwork} or listen for changes
34 * via {@link ConnectivityManager#registerNetworkCallback}.
35 */
36public class NetworkRequest implements Parcelable {
37    /**
38     * The {@link NetworkCapabilities} that define this request.
39     * @hide
40     */
41    public final @NonNull NetworkCapabilities networkCapabilities;
42
43    /**
44     * Identifies the request.  NetworkRequests should only be constructed by
45     * the Framework and given out to applications as tokens to be used to identify
46     * the request.
47     * @hide
48     */
49    public final int requestId;
50
51    /**
52     * Set for legacy requests and the default.  Set to TYPE_NONE for none.
53     * Causes CONNECTIVITY_ACTION broadcasts to be sent.
54     * @hide
55     */
56    public final int legacyType;
57
58    /**
59     * A NetworkRequest as used by the system can be one of the following types:
60     *
61     *     - LISTEN, for which the framework will issue callbacks about any
62     *       and all networks that match the specified NetworkCapabilities,
63     *
64     *     - REQUEST, capable of causing a specific network to be created
65     *       first (e.g. a telephony DUN request), the framework will issue
66     *       callbacks about the single, highest scoring current network
67     *       (if any) that matches the specified NetworkCapabilities, or
68     *
69     *     - TRACK_DEFAULT, a hybrid of the two designed such that the
70     *       framework will issue callbacks for the single, highest scoring
71     *       current network (if any) that matches the capabilities of the
72     *       default Internet request (mDefaultRequest), but which cannot cause
73     *       the framework to either create or retain the existence of any
74     *       specific network. Note that from the point of view of the request
75     *       matching code, TRACK_DEFAULT is identical to REQUEST: its special
76     *       behaviour is not due to different semantics, but to the fact that
77     *       the system will only ever create a TRACK_DEFAULT with capabilities
78     *       that are identical to the default request's capabilities, thus
79     *       causing it to share fate in every way with the default request.
80     *
81     *     - BACKGROUND_REQUEST, like REQUEST but does not cause any networks
82     *       to retain the NET_CAPABILITY_FOREGROUND capability. A network with
83     *       no foreground requests is in the background. A network that has
84     *       one or more background requests and loses its last foreground
85     *       request to a higher-scoring network will not go into the
86     *       background immediately, but will linger and go into the background
87     *       after the linger timeout.
88     *
89     *     - The value NONE is used only by applications. When an application
90     *       creates a NetworkRequest, it does not have a type; the type is set
91     *       by the system depending on the method used to file the request
92     *       (requestNetwork, registerNetworkCallback, etc.).
93     *
94     * @hide
95     */
96    public static enum Type {
97        NONE,
98        LISTEN,
99        TRACK_DEFAULT,
100        REQUEST,
101        BACKGROUND_REQUEST,
102    };
103
104    /**
105     * The type of the request. This is only used by the system and is always NONE elsewhere.
106     *
107     * @hide
108     */
109    public final Type type;
110
111    /**
112     * @hide
113     */
114    public NetworkRequest(NetworkCapabilities nc, int legacyType, int rId, Type type) {
115        if (nc == null) {
116            throw new NullPointerException();
117        }
118        requestId = rId;
119        networkCapabilities = nc;
120        this.legacyType = legacyType;
121        this.type = type;
122    }
123
124    /**
125     * @hide
126     */
127    public NetworkRequest(NetworkRequest that) {
128        networkCapabilities = new NetworkCapabilities(that.networkCapabilities);
129        requestId = that.requestId;
130        this.legacyType = that.legacyType;
131        this.type = that.type;
132    }
133
134    /**
135     * Builder used to create {@link NetworkRequest} objects.  Specify the Network features
136     * needed in terms of {@link NetworkCapabilities} features
137     */
138    public static class Builder {
139        private final NetworkCapabilities mNetworkCapabilities;
140
141        /**
142         * Default constructor for Builder.
143         */
144        public Builder() {
145            // By default, restrict this request to networks available to this app.
146            // Apps can rescind this restriction, but ConnectivityService will enforce
147            // it for apps that do not have the NETWORK_SETTINGS permission.
148            mNetworkCapabilities = new NetworkCapabilities();
149            mNetworkCapabilities.setSingleUid(Process.myUid());
150        }
151
152        /**
153         * Build {@link NetworkRequest} give the current set of capabilities.
154         */
155        public NetworkRequest build() {
156            // Make a copy of mNetworkCapabilities so we don't inadvertently remove NOT_RESTRICTED
157            // when later an unrestricted capability could be added to mNetworkCapabilities, in
158            // which case NOT_RESTRICTED should be returned to mNetworkCapabilities, which
159            // maybeMarkCapabilitiesRestricted() doesn't add back.
160            final NetworkCapabilities nc = new NetworkCapabilities(mNetworkCapabilities);
161            nc.maybeMarkCapabilitiesRestricted();
162            return new NetworkRequest(nc, ConnectivityManager.TYPE_NONE,
163                    ConnectivityManager.REQUEST_ID_UNSET, Type.NONE);
164        }
165
166        /**
167         * Add the given capability requirement to this builder.  These represent
168         * the requested network's required capabilities.  Note that when searching
169         * for a network to satisfy a request, all capabilities requested must be
170         * satisfied.
171         * <p>
172         * If the given capability was previously added to the list of unwanted capabilities
173         * then the capability will also be removed from the list of unwanted capabilities.
174         *
175         * @param capability The capability to add.
176         * @return The builder to facilitate chaining
177         *         {@code builder.addCapability(...).addCapability();}.
178         */
179        public Builder addCapability(@NetworkCapabilities.NetCapability int capability) {
180            mNetworkCapabilities.addCapability(capability);
181            return this;
182        }
183
184        /**
185         * Removes (if found) the given capability from this builder instance from both required
186         * and unwanted capabilities lists.
187         *
188         * @param capability The capability to remove.
189         * @return The builder to facilitate chaining.
190         */
191        public Builder removeCapability(@NetworkCapabilities.NetCapability int capability) {
192            mNetworkCapabilities.removeCapability(capability);
193            return this;
194        }
195
196        /**
197         * Set the {@code NetworkCapabilities} for this builder instance,
198         * overriding any capabilities that had been previously set.
199         *
200         * @param nc The superseding {@code NetworkCapabilities} instance.
201         * @return The builder to facilitate chaining.
202         * @hide
203         */
204        public Builder setCapabilities(NetworkCapabilities nc) {
205            mNetworkCapabilities.clearAll();
206            mNetworkCapabilities.combineCapabilities(nc);
207            return this;
208        }
209
210        /**
211         * Set the watched UIDs for this request. This will be reset and wiped out unless
212         * the calling app holds the CHANGE_NETWORK_STATE permission.
213         *
214         * @param uids The watched UIDs as a set of UidRanges, or null for everything.
215         * @return The builder to facilitate chaining.
216         * @hide
217         */
218        public Builder setUids(Set<UidRange> uids) {
219            mNetworkCapabilities.setUids(uids);
220            return this;
221        }
222
223        /**
224         * Add a capability that must not exist in the requested network.
225         * <p>
226         * If the capability was previously added to the list of required capabilities (for
227         * example, it was there by default or added using {@link #addCapability(int)} method), then
228         * it will be removed from the list of required capabilities as well.
229         *
230         * @see #addCapability(int)
231         *
232         * @param capability The capability to add to unwanted capability list.
233         * @return The builder to facilitate chaining.
234         * @hide
235         */
236        public Builder addUnwantedCapability(@NetworkCapabilities.NetCapability int capability) {
237            mNetworkCapabilities.addUnwantedCapability(capability);
238            return this;
239        }
240
241        /**
242         * Completely clears all the {@code NetworkCapabilities} from this builder instance,
243         * removing even the capabilities that are set by default when the object is constructed.
244         *
245         * @return The builder to facilitate chaining.
246         * @hide
247         */
248        public Builder clearCapabilities() {
249            mNetworkCapabilities.clearAll();
250            return this;
251        }
252
253        /**
254         * Adds the given transport requirement to this builder.  These represent
255         * the set of allowed transports for the request.  Only networks using one
256         * of these transports will satisfy the request.  If no particular transports
257         * are required, none should be specified here.
258         *
259         * @param transportType The transport type to add.
260         * @return The builder to facilitate chaining.
261         */
262        public Builder addTransportType(@NetworkCapabilities.Transport int transportType) {
263            mNetworkCapabilities.addTransportType(transportType);
264            return this;
265        }
266
267        /**
268         * Removes (if found) the given transport from this builder instance.
269         *
270         * @param transportType The transport type to remove.
271         * @return The builder to facilitate chaining.
272         */
273        public Builder removeTransportType(@NetworkCapabilities.Transport int transportType) {
274            mNetworkCapabilities.removeTransportType(transportType);
275            return this;
276        }
277
278        /**
279         * @hide
280         */
281        public Builder setLinkUpstreamBandwidthKbps(int upKbps) {
282            mNetworkCapabilities.setLinkUpstreamBandwidthKbps(upKbps);
283            return this;
284        }
285        /**
286         * @hide
287         */
288        public Builder setLinkDownstreamBandwidthKbps(int downKbps) {
289            mNetworkCapabilities.setLinkDownstreamBandwidthKbps(downKbps);
290            return this;
291        }
292
293        /**
294         * Sets the optional bearer specific network specifier.
295         * This has no meaning if a single transport is also not specified, so calling
296         * this without a single transport set will generate an exception, as will
297         * subsequently adding or removing transports after this is set.
298         * </p>
299         * The interpretation of this {@code String} is bearer specific and bearers that use
300         * it should document their particulars.  For example, Bluetooth may use some sort of
301         * device id while WiFi could used ssid and/or bssid.  Cellular may use carrier spn.
302         *
303         * @param networkSpecifier An {@code String} of opaque format used to specify the bearer
304         *                         specific network specifier where the bearer has a choice of
305         *                         networks.
306         */
307        public Builder setNetworkSpecifier(String networkSpecifier) {
308            /*
309             * A StringNetworkSpecifier does not accept null or empty ("") strings. When network
310             * specifiers were strings a null string and an empty string were considered equivalent.
311             * Hence no meaning is attached to a null or empty ("") string.
312             */
313            return setNetworkSpecifier(TextUtils.isEmpty(networkSpecifier) ? null
314                    : new StringNetworkSpecifier(networkSpecifier));
315        }
316
317        /**
318         * Sets the optional bearer specific network specifier.
319         * This has no meaning if a single transport is also not specified, so calling
320         * this without a single transport set will generate an exception, as will
321         * subsequently adding or removing transports after this is set.
322         * </p>
323         *
324         * @param networkSpecifier A concrete, parcelable framework class that extends
325         *                         NetworkSpecifier.
326         */
327        public Builder setNetworkSpecifier(NetworkSpecifier networkSpecifier) {
328            MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(networkSpecifier);
329            mNetworkCapabilities.setNetworkSpecifier(networkSpecifier);
330            return this;
331        }
332
333        /**
334         * Sets the signal strength. This is a signed integer, with higher values indicating a
335         * stronger signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same
336         * RSSI units reported by WifiManager.
337         * <p>
338         * Note that when used to register a network callback, this specifies the minimum acceptable
339         * signal strength. When received as the state of an existing network it specifies the
340         * current value. A value of {@code SIGNAL_STRENGTH_UNSPECIFIED} means no value when
341         * received and has no effect when requesting a callback.
342         *
343         * @param signalStrength the bearer-specific signal strength.
344         * @hide
345         */
346        public Builder setSignalStrength(int signalStrength) {
347            mNetworkCapabilities.setSignalStrength(signalStrength);
348            return this;
349        }
350    }
351
352    // implement the Parcelable interface
353    public int describeContents() {
354        return 0;
355    }
356    public void writeToParcel(Parcel dest, int flags) {
357        networkCapabilities.writeToParcel(dest, flags);
358        dest.writeInt(legacyType);
359        dest.writeInt(requestId);
360        dest.writeString(type.name());
361    }
362    public static final Creator<NetworkRequest> CREATOR =
363        new Creator<NetworkRequest>() {
364            public NetworkRequest createFromParcel(Parcel in) {
365                NetworkCapabilities nc = NetworkCapabilities.CREATOR.createFromParcel(in);
366                int legacyType = in.readInt();
367                int requestId = in.readInt();
368                Type type = Type.valueOf(in.readString());  // IllegalArgumentException if invalid.
369                NetworkRequest result = new NetworkRequest(nc, legacyType, requestId, type);
370                return result;
371            }
372            public NetworkRequest[] newArray(int size) {
373                return new NetworkRequest[size];
374            }
375        };
376
377    /**
378     * Returns true iff. this NetworkRequest is of type LISTEN.
379     *
380     * @hide
381     */
382    public boolean isListen() {
383        return type == Type.LISTEN;
384    }
385
386    /**
387     * Returns true iff. the contained NetworkRequest is one that:
388     *
389     *     - should be associated with at most one satisfying network
390     *       at a time;
391     *
392     *     - should cause a network to be kept up, but not necessarily in
393     *       the foreground, if it is the best network which can satisfy the
394     *       NetworkRequest.
395     *
396     * For full detail of how isRequest() is used for pairing Networks with
397     * NetworkRequests read rematchNetworkAndRequests().
398     *
399     * @hide
400     */
401    public boolean isRequest() {
402        return isForegroundRequest() || isBackgroundRequest();
403    }
404
405    /**
406     * Returns true iff. the contained NetworkRequest is one that:
407     *
408     *     - should be associated with at most one satisfying network
409     *       at a time;
410     *
411     *     - should cause a network to be kept up and in the foreground if
412     *       it is the best network which can satisfy the NetworkRequest.
413     *
414     * For full detail of how isRequest() is used for pairing Networks with
415     * NetworkRequests read rematchNetworkAndRequests().
416     *
417     * @hide
418     */
419    public boolean isForegroundRequest() {
420        return type == Type.TRACK_DEFAULT || type == Type.REQUEST;
421    }
422
423    /**
424     * Returns true iff. this NetworkRequest is of type BACKGROUND_REQUEST.
425     *
426     * @hide
427     */
428    public boolean isBackgroundRequest() {
429        return type == Type.BACKGROUND_REQUEST;
430    }
431
432    /**
433     * @see Builder#addCapability(int)
434     */
435    public boolean hasCapability(@NetCapability int capability) {
436        return networkCapabilities.hasCapability(capability);
437    }
438
439    /**
440     * @see Builder#addTransportType(int)
441     */
442    public boolean hasTransport(@Transport int transportType) {
443        return networkCapabilities.hasTransport(transportType);
444    }
445
446    public String toString() {
447        return "NetworkRequest [ " + type + " id=" + requestId +
448                (legacyType != ConnectivityManager.TYPE_NONE ? ", legacyType=" + legacyType : "") +
449                ", " + networkCapabilities.toString() + " ]";
450    }
451
452    private int typeToProtoEnum(Type t) {
453        switch (t) {
454            case NONE:
455                return NetworkRequestProto.TYPE_NONE;
456            case LISTEN:
457                return NetworkRequestProto.TYPE_LISTEN;
458            case TRACK_DEFAULT:
459                return NetworkRequestProto.TYPE_TRACK_DEFAULT;
460            case REQUEST:
461                return NetworkRequestProto.TYPE_REQUEST;
462            case BACKGROUND_REQUEST:
463                return NetworkRequestProto.TYPE_BACKGROUND_REQUEST;
464            default:
465                return NetworkRequestProto.TYPE_UNKNOWN;
466        }
467    }
468
469    /** @hide */
470    public void writeToProto(ProtoOutputStream proto, long fieldId) {
471        final long token = proto.start(fieldId);
472
473        proto.write(NetworkRequestProto.TYPE, typeToProtoEnum(type));
474        proto.write(NetworkRequestProto.REQUEST_ID, requestId);
475        proto.write(NetworkRequestProto.LEGACY_TYPE, legacyType);
476        networkCapabilities.writeToProto(proto, NetworkRequestProto.NETWORK_CAPABILITIES);
477
478        proto.end(token);
479    }
480
481    public boolean equals(Object obj) {
482        if (obj instanceof NetworkRequest == false) return false;
483        NetworkRequest that = (NetworkRequest)obj;
484        return (that.legacyType == this.legacyType &&
485                that.requestId == this.requestId &&
486                that.type == this.type &&
487                Objects.equals(that.networkCapabilities, this.networkCapabilities));
488    }
489
490    public int hashCode() {
491        return Objects.hash(requestId, legacyType, networkCapabilities, type);
492    }
493}
494