• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package android.net;
18 
19 import android.annotation.IntDef;
20 import android.annotation.IntRange;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.SuppressLint;
24 import android.annotation.SystemApi;
25 import android.annotation.TestApi;
26 import android.compat.annotation.UnsupportedAppUsage;
27 import android.content.Context;
28 import android.os.Build;
29 import android.os.Bundle;
30 import android.os.ConditionVariable;
31 import android.os.Handler;
32 import android.os.Looper;
33 import android.os.Message;
34 import android.os.RemoteException;
35 import android.telephony.data.EpsBearerQosSessionAttributes;
36 import android.telephony.data.NrQosSessionAttributes;
37 import android.util.Log;
38 
39 import com.android.internal.annotations.VisibleForTesting;
40 
41 import java.lang.annotation.Retention;
42 import java.lang.annotation.RetentionPolicy;
43 import java.time.Duration;
44 import java.util.ArrayList;
45 import java.util.List;
46 import java.util.Objects;
47 import java.util.concurrent.atomic.AtomicBoolean;
48 
49 /**
50  * A utility class for handling for communicating between bearer-specific
51  * code and ConnectivityService.
52  *
53  * An agent manages the life cycle of a network. A network starts its
54  * life cycle when {@link register} is called on NetworkAgent. The network
55  * is then connecting. When full L3 connectivity has been established,
56  * the agent should call {@link markConnected} to inform the system that
57  * this network is ready to use. When the network disconnects its life
58  * ends and the agent should call {@link unregister}, at which point the
59  * system will clean up and free resources.
60  * Any reconnection becomes a new logical network, so after a network
61  * is disconnected the agent cannot be used any more. Network providers
62  * should create a new NetworkAgent instance to handle new connections.
63  *
64  * A bearer may have more than one NetworkAgent if it can simultaneously
65  * support separate networks (IMS / Internet / MMS Apns on cellular, or
66  * perhaps connections with different SSID or P2P for Wi-Fi).
67  *
68  * This class supports methods to start and stop sending keepalive packets.
69  * Keepalive packets are typically sent at periodic intervals over a network
70  * with NAT when there is no other traffic to avoid the network forcefully
71  * closing the connection. NetworkAgents that manage technologies that
72  * have hardware support for keepalive should implement the related
73  * methods to save battery life. NetworkAgent that cannot get support
74  * without waking up the CPU should not, as this would be prohibitive in
75  * terms of battery - these agents should simply not override the related
76  * methods, which results in the implementation returning
77  * {@link SocketKeepalive.ERROR_UNSUPPORTED} as appropriate.
78  *
79  * Keepalive packets need to be sent at relatively frequent intervals
80  * (a few seconds to a few minutes). As the contents of keepalive packets
81  * depend on the current network status, hardware needs to be configured
82  * to send them and has a limited amount of memory to do so. The HAL
83  * formalizes this as slots that an implementation can configure to send
84  * the correct packets. Devices typically have a small number of slots
85  * per radio technology, and the specific number of slots for each
86  * technology is specified in configuration files.
87  * {@see SocketKeepalive} for details.
88  *
89  * @hide
90  */
91 @SystemApi
92 public abstract class NetworkAgent {
93     /**
94      * The {@link Network} corresponding to this object.
95      */
96     @Nullable
97     private volatile Network mNetwork;
98 
99     @Nullable
100     private volatile INetworkAgentRegistry mRegistry;
101 
102     private interface RegistryAction {
execute(@onNull INetworkAgentRegistry registry)103         void execute(@NonNull INetworkAgentRegistry registry) throws RemoteException;
104     }
105 
106     private final Handler mHandler;
107     private final String LOG_TAG;
108     private static final boolean DBG = true;
109     private static final boolean VDBG = false;
110     /** @hide */
111     @TestApi
112     public static final int MIN_LINGER_TIMER_MS = 2000;
113     private final ArrayList<RegistryAction> mPreConnectedQueue = new ArrayList<>();
114     private volatile long mLastBwRefreshTime = 0;
115     private static final long BW_REFRESH_MIN_WIN_MS = 500;
116     private boolean mBandwidthUpdateScheduled = false;
117     private AtomicBoolean mBandwidthUpdatePending = new AtomicBoolean(false);
118     @NonNull
119     private NetworkInfo mNetworkInfo;
120     @NonNull
121     private final Object mRegisterLock = new Object();
122 
123     /**
124      * The ID of the {@link NetworkProvider} that created this object, or
125      * {@link NetworkProvider#ID_NONE} if unknown.
126      * @hide
127      */
128     public final int providerId;
129 
130     // ConnectivityService parses message constants from itself and NetworkAgent with MessageUtils
131     // for debugging purposes, and crashes if some messages have the same values.
132     // TODO: have ConnectivityService store message names in different maps and remove this base
133     private static final int BASE = 200;
134 
135     /**
136      * Sent by ConnectivityService to the NetworkAgent to inform it of
137      * suspected connectivity problems on its network.  The NetworkAgent
138      * should take steps to verify and correct connectivity.
139      * @hide
140      */
141     public static final int CMD_SUSPECT_BAD = BASE;
142 
143     /**
144      * Sent by the NetworkAgent (note the EVENT vs CMD prefix) to
145      * ConnectivityService to pass the current NetworkInfo (connection state).
146      * Sent when the NetworkInfo changes, mainly due to change of state.
147      * obj = NetworkInfo
148      * @hide
149      */
150     public static final int EVENT_NETWORK_INFO_CHANGED = BASE + 1;
151 
152     /**
153      * Sent by the NetworkAgent to ConnectivityService to pass the current
154      * NetworkCapabilties.
155      * obj = NetworkCapabilities
156      * @hide
157      */
158     public static final int EVENT_NETWORK_CAPABILITIES_CHANGED = BASE + 2;
159 
160     /**
161      * Sent by the NetworkAgent to ConnectivityService to pass the current
162      * NetworkProperties.
163      * obj = NetworkProperties
164      * @hide
165      */
166     public static final int EVENT_NETWORK_PROPERTIES_CHANGED = BASE + 3;
167 
168     /**
169      * Centralize the place where base network score, and network score scaling, will be
170      * stored, so as we can consistently compare apple and oranges, or wifi, ethernet and LTE
171      * @hide
172      */
173     public static final int WIFI_BASE_SCORE = 60;
174 
175     /**
176      * Sent by the NetworkAgent to ConnectivityService to pass the current
177      * network score.
178      * arg1 = network score int
179      * @hide
180      */
181     public static final int EVENT_NETWORK_SCORE_CHANGED = BASE + 4;
182 
183     /**
184      * Sent by the NetworkAgent to ConnectivityService to pass the current
185      * list of underlying networks.
186      * obj = array of Network objects
187      * @hide
188      */
189     public static final int EVENT_UNDERLYING_NETWORKS_CHANGED = BASE + 5;
190 
191     /**
192      * Sent by the NetworkAgent to ConnectivityService to pass the current value of the teardown
193      * delay.
194      * arg1 = teardown delay in milliseconds
195      * @hide
196      */
197     public static final int EVENT_TEARDOWN_DELAY_CHANGED = BASE + 6;
198 
199     /**
200      * The maximum value for the teardown delay, in milliseconds.
201      * @hide
202      */
203     public static final int MAX_TEARDOWN_DELAY_MS = 5000;
204 
205     /**
206      * Sent by ConnectivityService to the NetworkAgent to inform the agent of the
207      * networks status - whether we could use the network or could not, due to
208      * either a bad network configuration (no internet link) or captive portal.
209      *
210      * arg1 = either {@code VALID_NETWORK} or {@code INVALID_NETWORK}
211      * obj = Bundle containing map from {@code REDIRECT_URL_KEY} to {@code String}
212      *       representing URL that Internet probe was redirect to, if it was redirected,
213      *       or mapping to {@code null} otherwise.
214      * @hide
215      */
216     public static final int CMD_REPORT_NETWORK_STATUS = BASE + 7;
217 
218     /**
219      * Network validation suceeded.
220      * Corresponds to {@link NetworkCapabilities.NET_CAPABILITY_VALIDATED}.
221      */
222     public static final int VALIDATION_STATUS_VALID = 1;
223 
224     /**
225      * Network validation was attempted and failed. This may be received more than once as
226      * subsequent validation attempts are made.
227      */
228     public static final int VALIDATION_STATUS_NOT_VALID = 2;
229 
230     /** @hide */
231     @Retention(RetentionPolicy.SOURCE)
232     @IntDef(prefix = { "VALIDATION_STATUS_" }, value = {
233             VALIDATION_STATUS_VALID,
234             VALIDATION_STATUS_NOT_VALID
235     })
236     public @interface ValidationStatus {}
237 
238     // TODO: remove.
239     /** @hide */
240     public static final int VALID_NETWORK = 1;
241     /** @hide */
242     public static final int INVALID_NETWORK = 2;
243 
244     /**
245      * The key for the redirect URL in the Bundle argument of {@code CMD_REPORT_NETWORK_STATUS}.
246      * @hide
247      */
248     public static final String REDIRECT_URL_KEY = "redirect URL";
249 
250     /**
251      * Sent by the NetworkAgent to ConnectivityService to indicate this network was
252      * explicitly selected.  This should be sent before the NetworkInfo is marked
253      * CONNECTED so it can be given special treatment at that time.
254      *
255      * obj = boolean indicating whether to use this network even if unvalidated
256      * @hide
257      */
258     public static final int EVENT_SET_EXPLICITLY_SELECTED = BASE + 8;
259 
260     /**
261      * Sent by ConnectivityService to the NetworkAgent to inform the agent of
262      * whether the network should in the future be used even if not validated.
263      * This decision is made by the user, but it is the network transport's
264      * responsibility to remember it.
265      *
266      * arg1 = 1 if true, 0 if false
267      * @hide
268      */
269     public static final int CMD_SAVE_ACCEPT_UNVALIDATED = BASE + 9;
270 
271     /**
272      * Sent by ConnectivityService to the NetworkAgent to inform the agent to pull
273      * the underlying network connection for updated bandwidth information.
274      * @hide
275      */
276     public static final int CMD_REQUEST_BANDWIDTH_UPDATE = BASE + 10;
277 
278     /**
279      * Sent by ConnectivityService to the NetworkAgent to request that the specified packet be sent
280      * periodically on the given interval.
281      *
282      *   arg1 = the hardware slot number of the keepalive to start
283      *   arg2 = interval in seconds
284      *   obj = KeepalivePacketData object describing the data to be sent
285      *
286      * Also used internally by ConnectivityService / KeepaliveTracker, with different semantics.
287      * @hide
288      */
289     public static final int CMD_START_SOCKET_KEEPALIVE = BASE + 11;
290 
291     /**
292      * Requests that the specified keepalive packet be stopped.
293      *
294      * arg1 = hardware slot number of the keepalive to stop.
295      *
296      * Also used internally by ConnectivityService / KeepaliveTracker, with different semantics.
297      * @hide
298      */
299     public static final int CMD_STOP_SOCKET_KEEPALIVE = BASE + 12;
300 
301     /**
302      * Sent by the NetworkAgent to ConnectivityService to provide status on a socket keepalive
303      * request. This may either be the reply to a CMD_START_SOCKET_KEEPALIVE, or an asynchronous
304      * error notification.
305      *
306      * This is also sent by KeepaliveTracker to the app's {@link SocketKeepalive},
307      * so that the app's {@link SocketKeepalive.Callback} methods can be called.
308      *
309      * arg1 = hardware slot number of the keepalive
310      * arg2 = error code
311      * @hide
312      */
313     public static final int EVENT_SOCKET_KEEPALIVE = BASE + 13;
314 
315     /**
316      * Sent by ConnectivityService to inform this network transport of signal strength thresholds
317      * that when crossed should trigger a system wakeup and a NetworkCapabilities update.
318      *
319      *   obj = int[] describing signal strength thresholds.
320      * @hide
321      */
322     public static final int CMD_SET_SIGNAL_STRENGTH_THRESHOLDS = BASE + 14;
323 
324     /**
325      * Sent by ConnectivityService to the NeworkAgent to inform the agent to avoid
326      * automatically reconnecting to this network (e.g. via autojoin).  Happens
327      * when user selects "No" option on the "Stay connected?" dialog box.
328      * @hide
329      */
330     public static final int CMD_PREVENT_AUTOMATIC_RECONNECT = BASE + 15;
331 
332     /**
333      * Sent by the KeepaliveTracker to NetworkAgent to add a packet filter.
334      *
335      * For TCP keepalive offloads, keepalive packets are sent by the firmware. However, because the
336      * remote site will send ACK packets in response to the keepalive packets, the firmware also
337      * needs to be configured to properly filter the ACKs to prevent the system from waking up.
338      * This does not happen with UDP, so this message is TCP-specific.
339      * arg1 = hardware slot number of the keepalive to filter for.
340      * obj = the keepalive packet to send repeatedly.
341      * @hide
342      */
343     public static final int CMD_ADD_KEEPALIVE_PACKET_FILTER = BASE + 16;
344 
345     /**
346      * Sent by the KeepaliveTracker to NetworkAgent to remove a packet filter. See
347      * {@link #CMD_ADD_KEEPALIVE_PACKET_FILTER}.
348      * arg1 = hardware slot number of the keepalive packet filter to remove.
349      * @hide
350      */
351     public static final int CMD_REMOVE_KEEPALIVE_PACKET_FILTER = BASE + 17;
352 
353     /**
354      * Sent by ConnectivityService to the NetworkAgent to complete the bidirectional connection.
355      * obj = INetworkAgentRegistry
356      */
357     private static final int EVENT_AGENT_CONNECTED = BASE + 18;
358 
359     /**
360      * Sent by ConnectivityService to the NetworkAgent to inform the agent that it was disconnected.
361      */
362     private static final int EVENT_AGENT_DISCONNECTED = BASE + 19;
363 
364     /**
365      * Sent by QosCallbackTracker to {@link NetworkAgent} to register a new filter with
366      * callback.
367      *
368      * arg1 = QoS agent callback ID
369      * obj = {@link QosFilter}
370      * @hide
371      */
372     public static final int CMD_REGISTER_QOS_CALLBACK = BASE + 20;
373 
374     /**
375      * Sent by QosCallbackTracker to {@link NetworkAgent} to unregister a callback.
376      *
377      * arg1 = QoS agent callback ID
378      * @hide
379      */
380     public static final int CMD_UNREGISTER_QOS_CALLBACK = BASE + 21;
381 
382     /**
383      * Sent by ConnectivityService to {@link NetworkAgent} to inform the agent that its native
384      * network was created and the Network object is now valid.
385      *
386      * @hide
387      */
388     public static final int CMD_NETWORK_CREATED = BASE + 22;
389 
390     /**
391      * Sent by ConnectivityService to {@link NetworkAgent} to inform the agent that its native
392      * network was destroyed.
393      *
394      * @hide
395      */
396     public static final int CMD_NETWORK_DESTROYED = BASE + 23;
397 
398     /**
399      * Sent by the NetworkAgent to ConnectivityService to set the linger duration for this network
400      * agent.
401      * arg1 = the linger duration, represents by {@link Duration}.
402      *
403      * @hide
404      */
405     public static final int EVENT_LINGER_DURATION_CHANGED = BASE + 24;
406 
407     /**
408      * Sent by the NetworkAgent to ConnectivityService to set add a DSCP policy.
409      *
410      * @hide
411      */
412     public static final int EVENT_ADD_DSCP_POLICY = BASE + 25;
413 
414     /**
415      * Sent by the NetworkAgent to ConnectivityService to set remove a DSCP policy.
416      *
417      * @hide
418      */
419     public static final int EVENT_REMOVE_DSCP_POLICY = BASE + 26;
420 
421     /**
422      * Sent by the NetworkAgent to ConnectivityService to remove all DSCP policies.
423      *
424      * @hide
425      */
426     public static final int EVENT_REMOVE_ALL_DSCP_POLICIES = BASE + 27;
427 
428     /**
429      * Sent by ConnectivityService to {@link NetworkAgent} to inform the agent of an updated
430      * status for a DSCP policy.
431      *
432      * @hide
433      */
434     public static final int CMD_DSCP_POLICY_STATUS = BASE + 28;
435 
436     /**
437      * DSCP policy was successfully added.
438      */
439     public static final int DSCP_POLICY_STATUS_SUCCESS = 0;
440 
441     /**
442      * DSCP policy was rejected for any reason besides invalid classifier or insufficient resources.
443      */
444     public static final int DSCP_POLICY_STATUS_REQUEST_DECLINED = 1;
445 
446     /**
447      * Requested DSCP policy contained a classifier which is not supported.
448      */
449     public static final int DSCP_POLICY_STATUS_REQUESTED_CLASSIFIER_NOT_SUPPORTED = 2;
450 
451     /**
452      * Requested DSCP policy was not added due to insufficient processing resources.
453      */
454     // TODO: should this error case be supported?
455     public static final int DSCP_POLICY_STATUS_INSUFFICIENT_PROCESSING_RESOURCES = 3;
456 
457     /**
458      * DSCP policy was deleted.
459      */
460     public static final int DSCP_POLICY_STATUS_DELETED = 4;
461 
462     /**
463      * DSCP policy was not found during deletion.
464      */
465     public static final int DSCP_POLICY_STATUS_POLICY_NOT_FOUND = 5;
466 
467     /** @hide */
468     @IntDef(prefix = "DSCP_POLICY_STATUS_", value = {
469         DSCP_POLICY_STATUS_SUCCESS,
470         DSCP_POLICY_STATUS_REQUEST_DECLINED,
471         DSCP_POLICY_STATUS_REQUESTED_CLASSIFIER_NOT_SUPPORTED,
472         DSCP_POLICY_STATUS_INSUFFICIENT_PROCESSING_RESOURCES,
473         DSCP_POLICY_STATUS_DELETED
474     })
475     @Retention(RetentionPolicy.SOURCE)
476     public @interface DscpPolicyStatus {}
477 
478     /**
479      * Sent by the NetworkAgent to ConnectivityService to notify that this network is expected to be
480      * replaced within the specified time by a similar network.
481      * arg1 = timeout in milliseconds
482      * @hide
483      */
484     public static final int EVENT_UNREGISTER_AFTER_REPLACEMENT = BASE + 29;
485 
getLegacyNetworkInfo(final NetworkAgentConfig config)486     private static NetworkInfo getLegacyNetworkInfo(final NetworkAgentConfig config) {
487         final NetworkInfo ni = new NetworkInfo(config.legacyType, config.legacySubType,
488                 config.legacyTypeName, config.legacySubTypeName);
489         ni.setIsAvailable(true);
490         ni.setDetailedState(NetworkInfo.DetailedState.CONNECTING, null /* reason */,
491                 config.getLegacyExtraInfo());
492         return ni;
493     }
494 
495     // Temporary backward compatibility constructor
NetworkAgent(@onNull Context context, @NonNull Looper looper, @NonNull String logTag, @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, int score, @NonNull NetworkAgentConfig config, @Nullable NetworkProvider provider)496     public NetworkAgent(@NonNull Context context, @NonNull Looper looper, @NonNull String logTag,
497             @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, int score,
498             @NonNull NetworkAgentConfig config, @Nullable NetworkProvider provider) {
499         this(context, looper, logTag, nc, lp,
500                 new NetworkScore.Builder().setLegacyInt(score).build(), config, provider);
501     }
502 
503     /**
504      * Create a new network agent.
505      * @param context a {@link Context} to get system services from.
506      * @param looper the {@link Looper} on which to invoke the callbacks.
507      * @param logTag the tag for logs
508      * @param nc the initial {@link NetworkCapabilities} of this network. Update with
509      *           sendNetworkCapabilities.
510      * @param lp the initial {@link LinkProperties} of this network. Update with sendLinkProperties.
511      * @param score the initial score of this network. Update with sendNetworkScore.
512      * @param config an immutable {@link NetworkAgentConfig} for this agent.
513      * @param provider the {@link NetworkProvider} managing this agent.
514      */
NetworkAgent(@onNull Context context, @NonNull Looper looper, @NonNull String logTag, @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, @Nullable NetworkProvider provider)515     public NetworkAgent(@NonNull Context context, @NonNull Looper looper, @NonNull String logTag,
516             @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp,
517             @NonNull NetworkScore score, @NonNull NetworkAgentConfig config,
518             @Nullable NetworkProvider provider) {
519         this(looper, context, logTag, nc, lp, score, config,
520                 provider == null ? NetworkProvider.ID_NONE : provider.getProviderId(),
521                 getLegacyNetworkInfo(config));
522     }
523 
524     private static class InitialConfiguration {
525         public final Context context;
526         public final NetworkCapabilities capabilities;
527         public final LinkProperties properties;
528         public final NetworkScore score;
529         public final NetworkAgentConfig config;
530         public final NetworkInfo info;
InitialConfiguration(@onNull Context context, @NonNull NetworkCapabilities capabilities, @NonNull LinkProperties properties, @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, @NonNull NetworkInfo info)531         InitialConfiguration(@NonNull Context context, @NonNull NetworkCapabilities capabilities,
532                 @NonNull LinkProperties properties, @NonNull NetworkScore score,
533                 @NonNull NetworkAgentConfig config, @NonNull NetworkInfo info) {
534             this.context = context;
535             this.capabilities = capabilities;
536             this.properties = properties;
537             this.score = score;
538             this.config = config;
539             this.info = info;
540         }
541     }
542     private volatile InitialConfiguration mInitialConfiguration;
543 
NetworkAgent(@onNull Looper looper, @NonNull Context context, @NonNull String logTag, @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp, @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId, @NonNull NetworkInfo ni)544     private NetworkAgent(@NonNull Looper looper, @NonNull Context context, @NonNull String logTag,
545             @NonNull NetworkCapabilities nc, @NonNull LinkProperties lp,
546             @NonNull NetworkScore score, @NonNull NetworkAgentConfig config, int providerId,
547             @NonNull NetworkInfo ni) {
548         mHandler = new NetworkAgentHandler(looper);
549         LOG_TAG = logTag;
550         mNetworkInfo = new NetworkInfo(ni);
551         this.providerId = providerId;
552         if (ni == null || nc == null || lp == null) {
553             throw new IllegalArgumentException();
554         }
555 
556         mInitialConfiguration = new InitialConfiguration(context,
557                 new NetworkCapabilities(nc, NetworkCapabilities.REDACT_NONE),
558                 new LinkProperties(lp), score, config, ni);
559     }
560 
561     private class NetworkAgentHandler extends Handler {
NetworkAgentHandler(Looper looper)562         NetworkAgentHandler(Looper looper) {
563             super(looper);
564         }
565 
566         @Override
handleMessage(Message msg)567         public void handleMessage(Message msg) {
568             switch (msg.what) {
569                 case EVENT_AGENT_CONNECTED: {
570                     if (mRegistry != null) {
571                         log("Received new connection while already connected!");
572                     } else {
573                         if (VDBG) log("NetworkAgent fully connected");
574                         synchronized (mPreConnectedQueue) {
575                             final INetworkAgentRegistry registry = (INetworkAgentRegistry) msg.obj;
576                             mRegistry = registry;
577                             for (RegistryAction a : mPreConnectedQueue) {
578                                 try {
579                                     a.execute(registry);
580                                 } catch (RemoteException e) {
581                                     Log.wtf(LOG_TAG, "Communication error with registry", e);
582                                     // Fall through
583                                 }
584                             }
585                             mPreConnectedQueue.clear();
586                         }
587                     }
588                     break;
589                 }
590                 case EVENT_AGENT_DISCONNECTED: {
591                     if (DBG) log("NetworkAgent channel lost");
592                     // let the client know CS is done with us.
593                     onNetworkUnwanted();
594                     synchronized (mPreConnectedQueue) {
595                         mRegistry = null;
596                     }
597                     break;
598                 }
599                 case CMD_SUSPECT_BAD: {
600                     log("Unhandled Message " + msg);
601                     break;
602                 }
603                 case CMD_REQUEST_BANDWIDTH_UPDATE: {
604                     long currentTimeMs = System.currentTimeMillis();
605                     if (VDBG) {
606                         log("CMD_REQUEST_BANDWIDTH_UPDATE request received.");
607                     }
608                     if (currentTimeMs >= (mLastBwRefreshTime + BW_REFRESH_MIN_WIN_MS)) {
609                         mBandwidthUpdateScheduled = false;
610                         if (!mBandwidthUpdatePending.getAndSet(true)) {
611                             onBandwidthUpdateRequested();
612                         }
613                     } else {
614                         // deliver the request at a later time rather than discard it completely.
615                         if (!mBandwidthUpdateScheduled) {
616                             long waitTime = mLastBwRefreshTime + BW_REFRESH_MIN_WIN_MS
617                                     - currentTimeMs + 1;
618                             mBandwidthUpdateScheduled = sendEmptyMessageDelayed(
619                                     CMD_REQUEST_BANDWIDTH_UPDATE, waitTime);
620                         }
621                     }
622                     break;
623                 }
624                 case CMD_REPORT_NETWORK_STATUS: {
625                     String redirectUrl = ((Bundle) msg.obj).getString(REDIRECT_URL_KEY);
626                     if (VDBG) {
627                         log("CMD_REPORT_NETWORK_STATUS("
628                                 + (msg.arg1 == VALID_NETWORK ? "VALID, " : "INVALID, ")
629                                 + redirectUrl);
630                     }
631                     Uri uri = null;
632                     try {
633                         if (null != redirectUrl) {
634                             uri = Uri.parse(redirectUrl);
635                         }
636                     } catch (Exception e) {
637                         Log.wtf(LOG_TAG, "Surprising URI : " + redirectUrl, e);
638                     }
639                     onValidationStatus(msg.arg1 /* status */, uri);
640                     break;
641                 }
642                 case CMD_SAVE_ACCEPT_UNVALIDATED: {
643                     onSaveAcceptUnvalidated(msg.arg1 != 0);
644                     break;
645                 }
646                 case CMD_START_SOCKET_KEEPALIVE: {
647                     onStartSocketKeepalive(msg.arg1 /* slot */,
648                             Duration.ofSeconds(msg.arg2) /* interval */,
649                             (KeepalivePacketData) msg.obj /* packet */);
650                     break;
651                 }
652                 case CMD_STOP_SOCKET_KEEPALIVE: {
653                     onStopSocketKeepalive(msg.arg1 /* slot */);
654                     break;
655                 }
656 
657                 case CMD_SET_SIGNAL_STRENGTH_THRESHOLDS: {
658                     onSignalStrengthThresholdsUpdated((int[]) msg.obj);
659                     break;
660                 }
661                 case CMD_PREVENT_AUTOMATIC_RECONNECT: {
662                     onAutomaticReconnectDisabled();
663                     break;
664                 }
665                 case CMD_ADD_KEEPALIVE_PACKET_FILTER: {
666                     onAddKeepalivePacketFilter(msg.arg1 /* slot */,
667                             (KeepalivePacketData) msg.obj /* packet */);
668                     break;
669                 }
670                 case CMD_REMOVE_KEEPALIVE_PACKET_FILTER: {
671                     onRemoveKeepalivePacketFilter(msg.arg1 /* slot */);
672                     break;
673                 }
674                 case CMD_REGISTER_QOS_CALLBACK: {
675                     onQosCallbackRegistered(
676                             msg.arg1 /* QoS callback id */,
677                             (QosFilter) msg.obj /* QoS filter */);
678                     break;
679                 }
680                 case CMD_UNREGISTER_QOS_CALLBACK: {
681                     onQosCallbackUnregistered(
682                             msg.arg1 /* QoS callback id */);
683                     break;
684                 }
685                 case CMD_NETWORK_CREATED: {
686                     onNetworkCreated();
687                     break;
688                 }
689                 case CMD_NETWORK_DESTROYED: {
690                     onNetworkDestroyed();
691                     break;
692                 }
693                 case CMD_DSCP_POLICY_STATUS: {
694                     onDscpPolicyStatusUpdated(
695                             msg.arg1 /* Policy ID */,
696                             msg.arg2 /* DSCP Policy Status */);
697                     break;
698                 }
699             }
700         }
701     }
702 
703     /**
704      * Register this network agent with ConnectivityService.
705      *
706      * This method can only be called once per network agent.
707      *
708      * @return the Network associated with this network agent (which can also be obtained later
709      *         by calling getNetwork() on this agent).
710      * @throws IllegalStateException thrown by the system server if this network agent is
711      *         already registered.
712      */
713     @NonNull
register()714     public Network register() {
715         if (VDBG) log("Registering NetworkAgent");
716         synchronized (mRegisterLock) {
717             if (mNetwork != null) {
718                 throw new IllegalStateException("Agent already registered");
719             }
720             final ConnectivityManager cm = (ConnectivityManager) mInitialConfiguration.context
721                     .getSystemService(Context.CONNECTIVITY_SERVICE);
722             mNetwork = cm.registerNetworkAgent(new NetworkAgentBinder(mHandler),
723                     new NetworkInfo(mInitialConfiguration.info),
724                     mInitialConfiguration.properties, mInitialConfiguration.capabilities,
725                     mInitialConfiguration.score, mInitialConfiguration.config, providerId);
726             mInitialConfiguration = null; // All this memory can now be GC'd
727         }
728         return mNetwork;
729     }
730 
731     private static class NetworkAgentBinder extends INetworkAgent.Stub {
732         private static final String LOG_TAG = NetworkAgentBinder.class.getSimpleName();
733 
734         private final Handler mHandler;
735 
NetworkAgentBinder(Handler handler)736         private NetworkAgentBinder(Handler handler) {
737             mHandler = handler;
738         }
739 
740         @Override
onRegistered(@onNull INetworkAgentRegistry registry)741         public void onRegistered(@NonNull INetworkAgentRegistry registry) {
742             mHandler.sendMessage(mHandler.obtainMessage(EVENT_AGENT_CONNECTED, registry));
743         }
744 
745         @Override
onDisconnected()746         public void onDisconnected() {
747             mHandler.sendMessage(mHandler.obtainMessage(EVENT_AGENT_DISCONNECTED));
748         }
749 
750         @Override
onBandwidthUpdateRequested()751         public void onBandwidthUpdateRequested() {
752             mHandler.sendMessage(mHandler.obtainMessage(CMD_REQUEST_BANDWIDTH_UPDATE));
753         }
754 
755         @Override
onValidationStatusChanged( int validationStatus, @Nullable String captivePortalUrl)756         public void onValidationStatusChanged(
757                 int validationStatus, @Nullable String captivePortalUrl) {
758             // TODO: consider using a parcelable as argument when the interface is structured
759             Bundle redirectUrlBundle = new Bundle();
760             redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, captivePortalUrl);
761             mHandler.sendMessage(mHandler.obtainMessage(CMD_REPORT_NETWORK_STATUS,
762                     validationStatus, 0, redirectUrlBundle));
763         }
764 
765         @Override
onSaveAcceptUnvalidated(boolean acceptUnvalidated)766         public void onSaveAcceptUnvalidated(boolean acceptUnvalidated) {
767             mHandler.sendMessage(mHandler.obtainMessage(CMD_SAVE_ACCEPT_UNVALIDATED,
768                     acceptUnvalidated ? 1 : 0, 0));
769         }
770 
771         @Override
onStartNattSocketKeepalive(int slot, int intervalDurationMs, @NonNull NattKeepalivePacketData packetData)772         public void onStartNattSocketKeepalive(int slot, int intervalDurationMs,
773                 @NonNull NattKeepalivePacketData packetData) {
774             mHandler.sendMessage(mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE,
775                     slot, intervalDurationMs, packetData));
776         }
777 
778         @Override
onStartTcpSocketKeepalive(int slot, int intervalDurationMs, @NonNull TcpKeepalivePacketData packetData)779         public void onStartTcpSocketKeepalive(int slot, int intervalDurationMs,
780                 @NonNull TcpKeepalivePacketData packetData) {
781             mHandler.sendMessage(mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE,
782                     slot, intervalDurationMs, packetData));
783         }
784 
785         @Override
onStopSocketKeepalive(int slot)786         public void onStopSocketKeepalive(int slot) {
787             mHandler.sendMessage(mHandler.obtainMessage(CMD_STOP_SOCKET_KEEPALIVE, slot, 0));
788         }
789 
790         @Override
onSignalStrengthThresholdsUpdated(@onNull int[] thresholds)791         public void onSignalStrengthThresholdsUpdated(@NonNull int[] thresholds) {
792             mHandler.sendMessage(mHandler.obtainMessage(
793                     CMD_SET_SIGNAL_STRENGTH_THRESHOLDS, thresholds));
794         }
795 
796         @Override
onPreventAutomaticReconnect()797         public void onPreventAutomaticReconnect() {
798             mHandler.sendMessage(mHandler.obtainMessage(CMD_PREVENT_AUTOMATIC_RECONNECT));
799         }
800 
801         @Override
onAddNattKeepalivePacketFilter(int slot, @NonNull NattKeepalivePacketData packetData)802         public void onAddNattKeepalivePacketFilter(int slot,
803                 @NonNull NattKeepalivePacketData packetData) {
804             mHandler.sendMessage(mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER,
805                     slot, 0, packetData));
806         }
807 
808         @Override
onAddTcpKeepalivePacketFilter(int slot, @NonNull TcpKeepalivePacketData packetData)809         public void onAddTcpKeepalivePacketFilter(int slot,
810                 @NonNull TcpKeepalivePacketData packetData) {
811             mHandler.sendMessage(mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER,
812                     slot, 0, packetData));
813         }
814 
815         @Override
onRemoveKeepalivePacketFilter(int slot)816         public void onRemoveKeepalivePacketFilter(int slot) {
817             mHandler.sendMessage(mHandler.obtainMessage(CMD_REMOVE_KEEPALIVE_PACKET_FILTER,
818                     slot, 0));
819         }
820 
821         @Override
onQosFilterCallbackRegistered(final int qosCallbackId, final QosFilterParcelable qosFilterParcelable)822         public void onQosFilterCallbackRegistered(final int qosCallbackId,
823                 final QosFilterParcelable qosFilterParcelable) {
824             if (qosFilterParcelable.getQosFilter() != null) {
825                 mHandler.sendMessage(
826                         mHandler.obtainMessage(CMD_REGISTER_QOS_CALLBACK, qosCallbackId, 0,
827                                 qosFilterParcelable.getQosFilter()));
828                 return;
829             }
830 
831             Log.wtf(LOG_TAG, "onQosFilterCallbackRegistered: qos filter is null.");
832         }
833 
834         @Override
onQosCallbackUnregistered(final int qosCallbackId)835         public void onQosCallbackUnregistered(final int qosCallbackId) {
836             mHandler.sendMessage(mHandler.obtainMessage(
837                     CMD_UNREGISTER_QOS_CALLBACK, qosCallbackId, 0, null));
838         }
839 
840         @Override
onNetworkCreated()841         public void onNetworkCreated() {
842             mHandler.sendMessage(mHandler.obtainMessage(CMD_NETWORK_CREATED));
843         }
844 
845         @Override
onNetworkDestroyed()846         public void onNetworkDestroyed() {
847             mHandler.sendMessage(mHandler.obtainMessage(CMD_NETWORK_DESTROYED));
848         }
849 
850         @Override
onDscpPolicyStatusUpdated(final int policyId, @DscpPolicyStatus final int status)851         public void onDscpPolicyStatusUpdated(final int policyId,
852                 @DscpPolicyStatus final int status) {
853             mHandler.sendMessage(mHandler.obtainMessage(
854                     CMD_DSCP_POLICY_STATUS, policyId, status));
855         }
856     }
857 
858     /**
859      * Register this network agent with a testing harness.
860      *
861      * The returned Messenger sends messages to the Handler. This allows a test to send
862      * this object {@code CMD_*} messages as if they came from ConnectivityService, which
863      * is useful for testing the behavior.
864      *
865      * @hide
866      */
registerForTest(final Network network)867     public INetworkAgent registerForTest(final Network network) {
868         log("Registering NetworkAgent for test");
869         synchronized (mRegisterLock) {
870             mNetwork = network;
871             mInitialConfiguration = null;
872         }
873         return new NetworkAgentBinder(mHandler);
874     }
875 
876     /**
877      * Waits for the handler to be idle.
878      * This is useful for testing, and has smaller scope than an accessor to mHandler.
879      * TODO : move the implementation in common library with the tests
880      * @hide
881      */
882     @VisibleForTesting
waitForIdle(final long timeoutMs)883     public boolean waitForIdle(final long timeoutMs) {
884         final ConditionVariable cv = new ConditionVariable(false);
885         mHandler.post(cv::open);
886         return cv.block(timeoutMs);
887     }
888 
889     /**
890      * @return The Network associated with this agent, or null if it's not registered yet.
891      */
892     @Nullable
getNetwork()893     public Network getNetwork() {
894         return mNetwork;
895     }
896 
queueOrSendMessage(@onNull RegistryAction action)897     private void queueOrSendMessage(@NonNull RegistryAction action) {
898         synchronized (mPreConnectedQueue) {
899             if (mRegistry != null) {
900                 try {
901                     action.execute(mRegistry);
902                 } catch (RemoteException e) {
903                     Log.wtf(LOG_TAG, "Error executing registry action", e);
904                     // Fall through: the channel is asynchronous and does not report errors back
905                 }
906             } else {
907                 mPreConnectedQueue.add(action);
908             }
909         }
910     }
911 
912     /**
913      * Must be called by the agent when the network's {@link LinkProperties} change.
914      * @param linkProperties the new LinkProperties.
915      */
sendLinkProperties(@onNull LinkProperties linkProperties)916     public final void sendLinkProperties(@NonNull LinkProperties linkProperties) {
917         Objects.requireNonNull(linkProperties);
918         final LinkProperties lp = new LinkProperties(linkProperties);
919         queueOrSendMessage(reg -> reg.sendLinkProperties(lp));
920     }
921 
922     /**
923      * Must be called by the agent when the network's underlying networks change.
924      *
925      * <p>{@code networks} is one of the following:
926      * <ul>
927      * <li><strong>a non-empty array</strong>: an array of one or more {@link Network}s, in
928      * decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular)
929      * networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear
930      * first in the array.</li>
931      * <li><strong>an empty array</strong>: a zero-element array, meaning that the VPN has no
932      * underlying network connection, and thus, app traffic will not be sent or received.</li>
933      * <li><strong>null</strong>: (default) signifies that the VPN uses whatever is the system's
934      * default network. I.e., it doesn't use the {@code bindSocket} or {@code bindDatagramSocket}
935      * APIs mentioned above to send traffic over specific channels.</li>
936      * </ul>
937      *
938      * @param underlyingNetworks the new list of underlying networks.
939      * @see {@link VpnService.Builder#setUnderlyingNetworks(Network[])}
940      */
setUnderlyingNetworks( @uppressLint"NullableCollection") @ullable List<Network> underlyingNetworks)941     public final void setUnderlyingNetworks(
942             @SuppressLint("NullableCollection") @Nullable List<Network> underlyingNetworks) {
943         final ArrayList<Network> underlyingArray = (underlyingNetworks != null)
944                 ? new ArrayList<>(underlyingNetworks) : null;
945         queueOrSendMessage(reg -> reg.sendUnderlyingNetworks(underlyingArray));
946     }
947 
948     /**
949      * Inform ConnectivityService that this agent has now connected.
950      * Call {@link #unregister} to disconnect.
951      */
markConnected()952     public void markConnected() {
953         mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null /* reason */,
954                 mNetworkInfo.getExtraInfo());
955         queueOrSendNetworkInfo(mNetworkInfo);
956     }
957 
958     /**
959      * Unregister this network agent.
960      *
961      * This signals the network has disconnected and ends its lifecycle. After this is called,
962      * the network is torn down and this agent can no longer be used.
963      */
unregister()964     public void unregister() {
965         // When unregistering an agent nobody should use the extrainfo (or reason) any more.
966         mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null /* reason */,
967                 null /* extraInfo */);
968         queueOrSendNetworkInfo(mNetworkInfo);
969     }
970 
971     /**
972      * Sets the value of the teardown delay.
973      *
974      * The teardown delay is the time between when the network disconnects and when the native
975      * network corresponding to this {@code NetworkAgent} is destroyed. By default, the native
976      * network is destroyed immediately. If {@code teardownDelayMs} is non-zero, then when this
977      * network disconnects, the system will instead immediately mark the network as restricted
978      * and unavailable to unprivileged apps, but will defer destroying the native network until the
979      * teardown delay timer expires.
980      *
981      * The interfaces in use by this network will remain in use until the native network is
982      * destroyed and cannot be reused until {@link #onNetworkDestroyed()} is called.
983      *
984      * This method may be called at any time while the network is connected. It has no effect if
985      * the network is already disconnected and the teardown delay timer is running.
986      *
987      * @param teardownDelayMillis the teardown delay to set, or 0 to disable teardown delay.
988      */
setTeardownDelayMillis( @ntRangefrom = 0, to = MAX_TEARDOWN_DELAY_MS) int teardownDelayMillis)989     public void setTeardownDelayMillis(
990             @IntRange(from = 0, to = MAX_TEARDOWN_DELAY_MS) int teardownDelayMillis) {
991         queueOrSendMessage(reg -> reg.sendTeardownDelayMs(teardownDelayMillis));
992     }
993 
994     /**
995      * Indicates that this agent will likely soon be replaced by another agent for a very similar
996      * network (e.g., same Wi-Fi SSID).
997      *
998      * If the network is not currently satisfying any {@link NetworkRequest}s, it will be torn down.
999      * If it is satisfying requests, then the native network corresponding to the agent will be
1000      * destroyed immediately, but the agent will remain registered and will continue to satisfy
1001      * requests until {@link #unregister} is called, the network is replaced by an equivalent or
1002      * better network, or the specified timeout expires. During this time:
1003      *
1004      * <ul>
1005      * <li>The agent may not send any further updates, for example by calling methods
1006      *    such as {@link #sendNetworkCapabilities}, {@link #sendLinkProperties},
1007      *    {@link #sendNetworkScore(NetworkScore)} and so on. Any such updates will be ignored.
1008      * <li>The network will remain connected and continue to satisfy any requests that it would
1009      *    otherwise satisfy (including, possibly, the default request).
1010      * <li>The validation state of the network will not change, and calls to
1011      *    {@link ConnectivityManager#reportNetworkConnectivity(Network, boolean)} will be ignored.
1012      * </ul>
1013      *
1014      * Once this method is called, it is not possible to restore the agent to a functioning state.
1015      * If a replacement network becomes available, then a new agent must be registered. When that
1016      * replacement network is fully capable of replacing this network (including, possibly, being
1017      * validated), this agent will no longer be needed and will be torn down. Otherwise, this agent
1018      * can be disconnected by calling {@link #unregister}. If {@link #unregister} is not called,
1019      * this agent will automatically be unregistered when the specified timeout expires. Any
1020      * teardown delay previously set using{@link #setTeardownDelayMillis} is ignored.
1021      *
1022      * <p>This method has no effect if {@link #markConnected} has not yet been called.
1023      * <p>This method may only be called once.
1024      *
1025      * @param timeoutMillis the timeout after which this network will be unregistered even if
1026      *                      {@link #unregister} was not called.
1027      */
unregisterAfterReplacement( @ntRangefrom = 0, to = MAX_TEARDOWN_DELAY_MS) int timeoutMillis)1028     public void unregisterAfterReplacement(
1029             @IntRange(from = 0, to = MAX_TEARDOWN_DELAY_MS) int timeoutMillis) {
1030         queueOrSendMessage(reg -> reg.sendUnregisterAfterReplacement(timeoutMillis));
1031     }
1032 
1033     /**
1034      * Change the legacy subtype of this network agent.
1035      *
1036      * This is only for backward compatibility and should not be used by non-legacy network agents,
1037      * or agents that did not use to set a subtype. As such, only TYPE_MOBILE type agents can use
1038      * this and others will be thrown an exception if they try.
1039      *
1040      * @deprecated this is for backward compatibility only.
1041      * @param legacySubtype the legacy subtype.
1042      * @hide
1043      */
1044     @Deprecated
1045     @SystemApi
setLegacySubtype(final int legacySubtype, @NonNull final String legacySubtypeName)1046     public void setLegacySubtype(final int legacySubtype, @NonNull final String legacySubtypeName) {
1047         mNetworkInfo.setSubtype(legacySubtype, legacySubtypeName);
1048         queueOrSendNetworkInfo(mNetworkInfo);
1049     }
1050 
1051     /**
1052      * Set the ExtraInfo of this network agent.
1053      *
1054      * This sets the ExtraInfo field inside the NetworkInfo returned by legacy public API and the
1055      * broadcasts about the corresponding Network.
1056      * This is only for backward compatibility and should not be used by non-legacy network agents,
1057      * who will be thrown an exception if they try. The extra info should only be :
1058      * <ul>
1059      *   <li>For cellular agents, the APN name.</li>
1060      *   <li>For ethernet agents, the interface name.</li>
1061      * </ul>
1062      *
1063      * @deprecated this is for backward compatibility only.
1064      * @param extraInfo the ExtraInfo.
1065      * @hide
1066      */
1067     @Deprecated
setLegacyExtraInfo(@ullable final String extraInfo)1068     public void setLegacyExtraInfo(@Nullable final String extraInfo) {
1069         mNetworkInfo.setExtraInfo(extraInfo);
1070         queueOrSendNetworkInfo(mNetworkInfo);
1071     }
1072 
1073     /**
1074      * Must be called by the agent when it has a new NetworkInfo object.
1075      * @hide TODO: expose something better.
1076      */
1077     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
sendNetworkInfo(NetworkInfo networkInfo)1078     public final void sendNetworkInfo(NetworkInfo networkInfo) {
1079         queueOrSendNetworkInfo(networkInfo);
1080     }
1081 
queueOrSendNetworkInfo(NetworkInfo networkInfo)1082     private void queueOrSendNetworkInfo(NetworkInfo networkInfo) {
1083         final NetworkInfo ni = new NetworkInfo(networkInfo);
1084         queueOrSendMessage(reg -> reg.sendNetworkInfo(ni));
1085     }
1086 
1087     /**
1088      * Must be called by the agent when the network's {@link NetworkCapabilities} change.
1089      * @param networkCapabilities the new NetworkCapabilities.
1090      */
sendNetworkCapabilities(@onNull NetworkCapabilities networkCapabilities)1091     public final void sendNetworkCapabilities(@NonNull NetworkCapabilities networkCapabilities) {
1092         Objects.requireNonNull(networkCapabilities);
1093         mBandwidthUpdatePending.set(false);
1094         mLastBwRefreshTime = System.currentTimeMillis();
1095         final NetworkCapabilities nc =
1096                 new NetworkCapabilities(networkCapabilities, NetworkCapabilities.REDACT_NONE);
1097         queueOrSendMessage(reg -> reg.sendNetworkCapabilities(nc));
1098     }
1099 
1100     /**
1101      * Must be called by the agent to update the score of this network.
1102      *
1103      * @param score the new score.
1104      */
sendNetworkScore(@onNull NetworkScore score)1105     public final void sendNetworkScore(@NonNull NetworkScore score) {
1106         Objects.requireNonNull(score);
1107         queueOrSendMessage(reg -> reg.sendScore(score));
1108     }
1109 
1110     /**
1111      * Must be called by the agent to update the score of this network.
1112      *
1113      * @param score the new score, between 0 and 99.
1114      * deprecated use sendNetworkScore(NetworkScore) TODO : remove in S.
1115      */
sendNetworkScore(@ntRangefrom = 0, to = 99) int score)1116     public final void sendNetworkScore(@IntRange(from = 0, to = 99) int score) {
1117         sendNetworkScore(new NetworkScore.Builder().setLegacyInt(score).build());
1118     }
1119 
1120     /**
1121      * Must be called by the agent to indicate this network was manually selected by the user.
1122      * This should be called before the NetworkInfo is marked CONNECTED so that this
1123      * Network can be given special treatment at that time. If {@code acceptUnvalidated} is
1124      * {@code true}, then the system will switch to this network. If it is {@code false} and the
1125      * network cannot be validated, the system will ask the user whether to switch to this network.
1126      * If the user confirms and selects "don't ask again", then the system will call
1127      * {@link #saveAcceptUnvalidated} to persist the user's choice. Thus, if the transport ever
1128      * calls this method with {@code acceptUnvalidated} set to {@code false}, it must also implement
1129      * {@link #saveAcceptUnvalidated} to respect the user's choice.
1130      * @hide should move to NetworkAgentConfig.
1131      */
explicitlySelected(boolean acceptUnvalidated)1132     public void explicitlySelected(boolean acceptUnvalidated) {
1133         explicitlySelected(true /* explicitlySelected */, acceptUnvalidated);
1134     }
1135 
1136     /**
1137      * Must be called by the agent to indicate whether the network was manually selected by the
1138      * user. This should be called before the network becomes connected, so it can be given
1139      * special treatment when it does.
1140      *
1141      * If {@code explicitlySelected} is {@code true}, and {@code acceptUnvalidated} is {@code true},
1142      * then the system will switch to this network. If {@code explicitlySelected} is {@code true}
1143      * and {@code acceptUnvalidated} is {@code false}, and the  network cannot be validated, the
1144      * system will ask the user whether to switch to this network.  If the user confirms and selects
1145      * "don't ask again", then the system will call {@link #saveAcceptUnvalidated} to persist the
1146      * user's choice. Thus, if the transport ever calls this method with {@code explicitlySelected}
1147      * set to {@code true} and {@code acceptUnvalidated} set to {@code false}, it must also
1148      * implement {@link #saveAcceptUnvalidated} to respect the user's choice.
1149      *
1150      * If  {@code explicitlySelected} is {@code false} and {@code acceptUnvalidated} is
1151      * {@code true}, the system will interpret this as the user having accepted partial connectivity
1152      * on this network. Thus, the system will switch to the network and consider it validated even
1153      * if it only provides partial connectivity, but the network is not otherwise treated specially.
1154      * @hide should move to NetworkAgentConfig.
1155      */
explicitlySelected(boolean explicitlySelected, boolean acceptUnvalidated)1156     public void explicitlySelected(boolean explicitlySelected, boolean acceptUnvalidated) {
1157         queueOrSendMessage(reg -> reg.sendExplicitlySelected(
1158                 explicitlySelected, acceptUnvalidated));
1159     }
1160 
1161     /**
1162      * Called when ConnectivityService has indicated they no longer want this network.
1163      * The parent factory should (previously) have received indication of the change
1164      * as well, either canceling NetworkRequests or altering their score such that this
1165      * network won't be immediately requested again.
1166      */
onNetworkUnwanted()1167     public void onNetworkUnwanted() {
1168         unwanted();
1169     }
1170     /** @hide TODO delete once subclasses have moved to onNetworkUnwanted. */
unwanted()1171     protected void unwanted() {
1172     }
1173 
1174     /**
1175      * Called when ConnectivityService request a bandwidth update. The parent factory
1176      * shall try to overwrite this method and produce a bandwidth update if capable.
1177      * @hide
1178      */
1179     @SystemApi
onBandwidthUpdateRequested()1180     public void onBandwidthUpdateRequested() {
1181         pollLceData();
1182     }
1183     /** @hide TODO delete once subclasses have moved to onBandwidthUpdateRequested. */
pollLceData()1184     protected void pollLceData() {
1185     }
1186 
1187     /**
1188      * Called when the system determines the usefulness of this network.
1189      *
1190      * The system attempts to validate Internet connectivity on networks that provide the
1191      * {@link NetworkCapabilities#NET_CAPABILITY_INTERNET} capability.
1192      *
1193      * Currently there are two possible values:
1194      * {@code VALIDATION_STATUS_VALID} if Internet connectivity was validated,
1195      * {@code VALIDATION_STATUS_NOT_VALID} if Internet connectivity was not validated.
1196      *
1197      * This is guaranteed to be called again when the network status changes, but the system
1198      * may also call this multiple times even if the status does not change.
1199      *
1200      * @param status one of {@code VALIDATION_STATUS_VALID} or {@code VALIDATION_STATUS_NOT_VALID}.
1201      * @param redirectUri If Internet connectivity is being redirected (e.g., on a captive portal),
1202      *        this is the destination the probes are being redirected to, otherwise {@code null}.
1203      */
onValidationStatus(@alidationStatus int status, @Nullable Uri redirectUri)1204     public void onValidationStatus(@ValidationStatus int status, @Nullable Uri redirectUri) {
1205         networkStatus(status, null == redirectUri ? "" : redirectUri.toString());
1206     }
1207     /** @hide TODO delete once subclasses have moved to onValidationStatus */
networkStatus(int status, String redirectUrl)1208     protected void networkStatus(int status, String redirectUrl) {
1209     }
1210 
1211 
1212     /**
1213      * Called when the user asks to remember the choice to use this network even if unvalidated.
1214      * The transport is responsible for remembering the choice, and the next time the user connects
1215      * to the network, should explicitlySelected with {@code acceptUnvalidated} set to {@code true}.
1216      * This method will only be called if {@link #explicitlySelected} was called with
1217      * {@code acceptUnvalidated} set to {@code false}.
1218      * @param accept whether the user wants to use the network even if unvalidated.
1219      */
onSaveAcceptUnvalidated(boolean accept)1220     public void onSaveAcceptUnvalidated(boolean accept) {
1221         saveAcceptUnvalidated(accept);
1222     }
1223     /** @hide TODO delete once subclasses have moved to onSaveAcceptUnvalidated */
saveAcceptUnvalidated(boolean accept)1224     protected void saveAcceptUnvalidated(boolean accept) {
1225     }
1226 
1227     /**
1228      * Called when ConnectivityService has successfully created this NetworkAgent's native network.
1229      */
onNetworkCreated()1230     public void onNetworkCreated() {}
1231 
1232 
1233     /**
1234      * Called when ConnectivityService has successfully destroy this NetworkAgent's native network.
1235      */
onNetworkDestroyed()1236     public void onNetworkDestroyed() {}
1237 
1238     /**
1239      * Called when when the DSCP Policy status has changed.
1240      */
onDscpPolicyStatusUpdated(int policyId, @DscpPolicyStatus int status)1241     public void onDscpPolicyStatusUpdated(int policyId, @DscpPolicyStatus int status) {}
1242 
1243     /**
1244      * Requests that the network hardware send the specified packet at the specified interval.
1245      *
1246      * @param slot the hardware slot on which to start the keepalive.
1247      * @param interval the interval between packets, between 10 and 3600. Note that this API
1248      *                 does not support sub-second precision and will round off the request.
1249      * @param packet the packet to send.
1250      */
1251     // seconds is from SocketKeepalive.MIN_INTERVAL_SEC to MAX_INTERVAL_SEC, but these should
1252     // not be exposed as constants because they may change in the future (API guideline 4.8)
1253     // and should have getters if exposed at all. Getters can't be used in the annotation,
1254     // so the values unfortunately need to be copied.
onStartSocketKeepalive(int slot, @NonNull Duration interval, @NonNull KeepalivePacketData packet)1255     public void onStartSocketKeepalive(int slot, @NonNull Duration interval,
1256             @NonNull KeepalivePacketData packet) {
1257         final long intervalSeconds = interval.getSeconds();
1258         if (intervalSeconds < SocketKeepalive.MIN_INTERVAL_SEC
1259                 || intervalSeconds > SocketKeepalive.MAX_INTERVAL_SEC) {
1260             throw new IllegalArgumentException("Interval needs to be comprised between "
1261                     + SocketKeepalive.MIN_INTERVAL_SEC + " and " + SocketKeepalive.MAX_INTERVAL_SEC
1262                     + " but was " + intervalSeconds);
1263         }
1264         final Message msg = mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE, slot,
1265                 (int) intervalSeconds, packet);
1266         startSocketKeepalive(msg);
1267         msg.recycle();
1268     }
1269     /** @hide TODO delete once subclasses have moved to onStartSocketKeepalive */
startSocketKeepalive(Message msg)1270     protected void startSocketKeepalive(Message msg) {
1271         onSocketKeepaliveEvent(msg.arg1, SocketKeepalive.ERROR_UNSUPPORTED);
1272     }
1273 
1274     /**
1275      * Requests that the network hardware stop a previously-started keepalive.
1276      *
1277      * @param slot the hardware slot on which to stop the keepalive.
1278      */
onStopSocketKeepalive(int slot)1279     public void onStopSocketKeepalive(int slot) {
1280         Message msg = mHandler.obtainMessage(CMD_STOP_SOCKET_KEEPALIVE, slot, 0, null);
1281         stopSocketKeepalive(msg);
1282         msg.recycle();
1283     }
1284     /** @hide TODO delete once subclasses have moved to onStopSocketKeepalive */
stopSocketKeepalive(Message msg)1285     protected void stopSocketKeepalive(Message msg) {
1286         onSocketKeepaliveEvent(msg.arg1, SocketKeepalive.ERROR_UNSUPPORTED);
1287     }
1288 
1289     /**
1290      * Must be called by the agent when a socket keepalive event occurs.
1291      *
1292      * @param slot the hardware slot on which the event occurred.
1293      * @param event the event that occurred, as one of the SocketKeepalive.ERROR_*
1294      *              or SocketKeepalive.SUCCESS constants.
1295      */
sendSocketKeepaliveEvent(int slot, @SocketKeepalive.KeepaliveEvent int event)1296     public final void sendSocketKeepaliveEvent(int slot,
1297             @SocketKeepalive.KeepaliveEvent int event) {
1298         queueOrSendMessage(reg -> reg.sendSocketKeepaliveEvent(slot, event));
1299     }
1300     /** @hide TODO delete once callers have moved to sendSocketKeepaliveEvent */
onSocketKeepaliveEvent(int slot, int reason)1301     public void onSocketKeepaliveEvent(int slot, int reason) {
1302         sendSocketKeepaliveEvent(slot, reason);
1303     }
1304 
1305     /**
1306      * Called by ConnectivityService to add specific packet filter to network hardware to block
1307      * replies (e.g., TCP ACKs) matching the sent keepalive packets. Implementations that support
1308      * this feature must override this method.
1309      *
1310      * @param slot the hardware slot on which the keepalive should be sent.
1311      * @param packet the packet that is being sent.
1312      */
onAddKeepalivePacketFilter(int slot, @NonNull KeepalivePacketData packet)1313     public void onAddKeepalivePacketFilter(int slot, @NonNull KeepalivePacketData packet) {
1314         Message msg = mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0, packet);
1315         addKeepalivePacketFilter(msg);
1316         msg.recycle();
1317     }
1318     /** @hide TODO delete once subclasses have moved to onAddKeepalivePacketFilter */
addKeepalivePacketFilter(Message msg)1319     protected void addKeepalivePacketFilter(Message msg) {
1320     }
1321 
1322     /**
1323      * Called by ConnectivityService to remove a packet filter installed with
1324      * {@link #addKeepalivePacketFilter(Message)}. Implementations that support this feature
1325      * must override this method.
1326      *
1327      * @param slot the hardware slot on which the keepalive is being sent.
1328      */
onRemoveKeepalivePacketFilter(int slot)1329     public void onRemoveKeepalivePacketFilter(int slot) {
1330         Message msg = mHandler.obtainMessage(CMD_REMOVE_KEEPALIVE_PACKET_FILTER, slot, 0, null);
1331         removeKeepalivePacketFilter(msg);
1332         msg.recycle();
1333     }
1334     /** @hide TODO delete once subclasses have moved to onRemoveKeepalivePacketFilter */
removeKeepalivePacketFilter(Message msg)1335     protected void removeKeepalivePacketFilter(Message msg) {
1336     }
1337 
1338     /**
1339      * Called by ConnectivityService to inform this network agent of signal strength thresholds
1340      * that when crossed should trigger a system wakeup and a NetworkCapabilities update.
1341      *
1342      * When the system updates the list of thresholds that should wake up the CPU for a
1343      * given agent it will call this method on the agent. The agent that implement this
1344      * should implement it in hardware so as to ensure the CPU will be woken up on breach.
1345      * Agents are expected to react to a breach by sending an updated NetworkCapabilities
1346      * object with the appropriate signal strength to sendNetworkCapabilities.
1347      *
1348      * The specific units are bearer-dependent. See details on the units and requests in
1349      * {@link NetworkCapabilities.Builder#setSignalStrength}.
1350      *
1351      * @param thresholds the array of thresholds that should trigger wakeups.
1352      */
onSignalStrengthThresholdsUpdated(@onNull int[] thresholds)1353     public void onSignalStrengthThresholdsUpdated(@NonNull int[] thresholds) {
1354         setSignalStrengthThresholds(thresholds);
1355     }
1356     /** @hide TODO delete once subclasses have moved to onSetSignalStrengthThresholds */
setSignalStrengthThresholds(int[] thresholds)1357     protected void setSignalStrengthThresholds(int[] thresholds) {
1358     }
1359 
1360     /**
1361      * Called when the user asks to not stay connected to this network because it was found to not
1362      * provide Internet access.  Usually followed by call to {@code unwanted}.  The transport is
1363      * responsible for making sure the device does not automatically reconnect to the same network
1364      * after the {@code unwanted} call.
1365      */
onAutomaticReconnectDisabled()1366     public void onAutomaticReconnectDisabled() {
1367         preventAutomaticReconnect();
1368     }
1369     /** @hide TODO delete once subclasses have moved to onAutomaticReconnectDisabled */
preventAutomaticReconnect()1370     protected void preventAutomaticReconnect() {
1371     }
1372 
1373     /**
1374      * Called when a qos callback is registered with a filter.
1375      * @param qosCallbackId the id for the callback registered
1376      * @param filter the filter being registered
1377      */
onQosCallbackRegistered(final int qosCallbackId, final @NonNull QosFilter filter)1378     public void onQosCallbackRegistered(final int qosCallbackId, final @NonNull QosFilter filter) {
1379     }
1380 
1381     /**
1382      * Called when a qos callback is registered with a filter.
1383      * <p/>
1384      * Any QoS events that are sent with the same callback id after this method is called
1385      * are a no-op.
1386      *
1387      * @param qosCallbackId the id for the callback being unregistered
1388      */
onQosCallbackUnregistered(final int qosCallbackId)1389     public void onQosCallbackUnregistered(final int qosCallbackId) {
1390     }
1391 
1392 
1393     /**
1394      * Sends the attributes of Qos Session back to the Application
1395      *
1396      * @param qosCallbackId the callback id that the session belongs to
1397      * @param sessionId the unique session id across all Qos Sessions
1398      * @param attributes the attributes of the Qos Session
1399      */
sendQosSessionAvailable(final int qosCallbackId, final int sessionId, @NonNull final QosSessionAttributes attributes)1400     public final void sendQosSessionAvailable(final int qosCallbackId, final int sessionId,
1401             @NonNull final QosSessionAttributes attributes) {
1402         Objects.requireNonNull(attributes, "The attributes must be non-null");
1403         if (attributes instanceof EpsBearerQosSessionAttributes) {
1404             queueOrSendMessage(ra -> ra.sendEpsQosSessionAvailable(qosCallbackId,
1405                     new QosSession(sessionId, QosSession.TYPE_EPS_BEARER),
1406                     (EpsBearerQosSessionAttributes)attributes));
1407         } else if (attributes instanceof NrQosSessionAttributes) {
1408             queueOrSendMessage(ra -> ra.sendNrQosSessionAvailable(qosCallbackId,
1409                     new QosSession(sessionId, QosSession.TYPE_NR_BEARER),
1410                     (NrQosSessionAttributes)attributes));
1411         }
1412     }
1413 
1414     /**
1415      * Sends event that the Qos Session was lost.
1416      *
1417      * @param qosCallbackId the callback id that the session belongs to
1418      * @param sessionId the unique session id across all Qos Sessions
1419      * @param qosSessionType the session type {@code QosSesson#QosSessionType}
1420      */
sendQosSessionLost(final int qosCallbackId, final int sessionId, final int qosSessionType)1421     public final void sendQosSessionLost(final int qosCallbackId,
1422             final int sessionId, final int qosSessionType) {
1423         queueOrSendMessage(ra -> ra.sendQosSessionLost(qosCallbackId,
1424                 new QosSession(sessionId, qosSessionType)));
1425     }
1426 
1427     /**
1428      * Sends the exception type back to the application.
1429      *
1430      * The NetworkAgent should not send anymore messages with this id.
1431      *
1432      * @param qosCallbackId the callback id this exception belongs to
1433      * @param exceptionType the type of exception
1434      */
sendQosCallbackError(final int qosCallbackId, @QosCallbackException.ExceptionType final int exceptionType)1435     public final void sendQosCallbackError(final int qosCallbackId,
1436             @QosCallbackException.ExceptionType final int exceptionType) {
1437         queueOrSendMessage(ra -> ra.sendQosCallbackError(qosCallbackId, exceptionType));
1438     }
1439 
1440     /**
1441      * Set the linger duration for this network agent.
1442      * @param duration the delay between the moment the network becomes unneeded and the
1443      *                 moment the network is disconnected or moved into the background.
1444      *                 Note that If this duration has greater than millisecond precision, then
1445      *                 the internal implementation will drop any excess precision.
1446      */
setLingerDuration(@onNull final Duration duration)1447     public void setLingerDuration(@NonNull final Duration duration) {
1448         Objects.requireNonNull(duration);
1449         final long durationMs = duration.toMillis();
1450         if (durationMs < MIN_LINGER_TIMER_MS || durationMs > Integer.MAX_VALUE) {
1451             throw new IllegalArgumentException("Duration must be within ["
1452                     + MIN_LINGER_TIMER_MS + "," + Integer.MAX_VALUE + "]ms");
1453         }
1454         queueOrSendMessage(ra -> ra.sendLingerDuration((int) durationMs));
1455     }
1456 
1457     /**
1458      * Add a DSCP Policy.
1459      * @param policy the DSCP policy to be added.
1460      */
sendAddDscpPolicy(@onNull final DscpPolicy policy)1461     public void sendAddDscpPolicy(@NonNull final DscpPolicy policy) {
1462         Objects.requireNonNull(policy);
1463         queueOrSendMessage(ra -> ra.sendAddDscpPolicy(policy));
1464     }
1465 
1466     /**
1467      * Remove the specified DSCP policy.
1468      * @param policyId the ID corresponding to a specific DSCP Policy.
1469      */
sendRemoveDscpPolicy(final int policyId)1470     public void sendRemoveDscpPolicy(final int policyId) {
1471         queueOrSendMessage(ra -> ra.sendRemoveDscpPolicy(policyId));
1472     }
1473 
1474     /**
1475      * Remove all the DSCP policies on this network.
1476      */
sendRemoveAllDscpPolicies()1477     public void sendRemoveAllDscpPolicies() {
1478         queueOrSendMessage(ra -> ra.sendRemoveAllDscpPolicies());
1479     }
1480 
1481     /** @hide */
log(final String s)1482     protected void log(final String s) {
1483         Log.d(LOG_TAG, "NetworkAgent: " + s);
1484     }
1485 }
1486