blob: cc28e8d221a6566a15413e6d795670fb40373d2d [file] [log] [blame]
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001/*
2 * Copyright (C) 2008 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 com.android.server;
18
19import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
20import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
24import static android.content.pm.PackageManager.PERMISSION_GRANTED;
25import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
33import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
35import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
36import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
37import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
38import static android.net.ConnectivityManager.TYPE_ETHERNET;
39import static android.net.ConnectivityManager.TYPE_MOBILE;
40import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
41import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
42import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
43import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
44import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
45import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
46import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
47import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
49import static android.net.ConnectivityManager.TYPE_NONE;
50import static android.net.ConnectivityManager.TYPE_PROXY;
51import static android.net.ConnectivityManager.TYPE_VPN;
52import static android.net.ConnectivityManager.TYPE_WIFI;
53import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
54import static android.net.ConnectivityManager.getNetworkTypeName;
55import static android.net.ConnectivityManager.isNetworkTypeValid;
56import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
57import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
58import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
59import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
60import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
61import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
62import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
63import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
64import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
65import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
66import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
67import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
68import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
69import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
71import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
72import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
73import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
74import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
75import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
76import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
77import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
78import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
79import static android.net.NetworkCapabilities.TRANSPORT_TEST;
80import static android.net.NetworkCapabilities.TRANSPORT_VPN;
81import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
82import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
83import static android.os.Process.INVALID_UID;
84import static android.os.Process.VPN_UID;
85import static android.system.OsConstants.IPPROTO_TCP;
86import static android.system.OsConstants.IPPROTO_UDP;
87
88import static java.util.Map.Entry;
89
90import android.Manifest;
91import android.annotation.NonNull;
92import android.annotation.Nullable;
93import android.app.AppOpsManager;
94import android.app.BroadcastOptions;
95import android.app.PendingIntent;
96import android.app.usage.NetworkStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.ContentResolver;
100import android.content.Context;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.pm.PackageManager;
104import android.database.ContentObserver;
105import android.net.CaptivePortal;
106import android.net.CaptivePortalData;
107import android.net.ConnectionInfo;
Aaron Huang6a7e6ad2021-04-14 01:25:55 +0800108import android.net.ConnectivityAnnotations.RestrictBackgroundStatus;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000109import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
110import android.net.ConnectivityDiagnosticsManager.DataStallReport;
111import android.net.ConnectivityManager;
112import android.net.ConnectivityManager.BlockedReason;
113import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +0000114import android.net.ConnectivityResources;
115import android.net.ConnectivitySettingsManager;
116import android.net.DataStallReportParcelable;
117import android.net.DnsResolverServiceManager;
118import android.net.ICaptivePortal;
119import android.net.IConnectivityDiagnosticsCallback;
120import android.net.IConnectivityManager;
121import android.net.IDnsResolver;
122import android.net.INetd;
123import android.net.INetworkActivityListener;
124import android.net.INetworkAgent;
125import android.net.INetworkMonitor;
126import android.net.INetworkMonitorCallbacks;
127import android.net.INetworkOfferCallback;
128import android.net.IOnCompleteListener;
129import android.net.IQosCallback;
130import android.net.ISocketKeepaliveCallback;
131import android.net.InetAddresses;
132import android.net.IpMemoryStore;
133import android.net.IpPrefix;
134import android.net.LinkProperties;
135import android.net.MatchAllNetworkSpecifier;
136import android.net.NativeNetworkConfig;
137import android.net.NativeNetworkType;
138import android.net.NattSocketKeepalive;
139import android.net.Network;
140import android.net.NetworkAgent;
141import android.net.NetworkAgentConfig;
142import android.net.NetworkCapabilities;
143import android.net.NetworkInfo;
144import android.net.NetworkInfo.DetailedState;
145import android.net.NetworkMonitorManager;
146import android.net.NetworkPolicyManager;
147import android.net.NetworkPolicyManager.NetworkPolicyCallback;
148import android.net.NetworkProvider;
149import android.net.NetworkRequest;
150import android.net.NetworkScore;
151import android.net.NetworkSpecifier;
152import android.net.NetworkStack;
153import android.net.NetworkState;
154import android.net.NetworkStateSnapshot;
155import android.net.NetworkTestResultParcelable;
156import android.net.NetworkUtils;
157import android.net.NetworkWatchlistManager;
158import android.net.OemNetworkPreferences;
159import android.net.PrivateDnsConfigParcel;
160import android.net.ProxyInfo;
161import android.net.QosCallbackException;
162import android.net.QosFilter;
163import android.net.QosSocketFilter;
164import android.net.QosSocketInfo;
165import android.net.RouteInfo;
166import android.net.RouteInfoParcel;
167import android.net.SocketKeepalive;
168import android.net.TetheringManager;
169import android.net.TransportInfo;
170import android.net.UidRange;
171import android.net.UidRangeParcel;
172import android.net.UnderlyingNetworkInfo;
173import android.net.Uri;
174import android.net.VpnManager;
175import android.net.VpnTransportInfo;
176import android.net.metrics.IpConnectivityLog;
177import android.net.metrics.NetworkEvent;
178import android.net.netlink.InetDiagMessage;
179import android.net.networkstack.ModuleNetworkStackClient;
180import android.net.networkstack.NetworkStackClientBase;
181import android.net.resolv.aidl.DnsHealthEventParcel;
182import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
183import android.net.resolv.aidl.Nat64PrefixEventParcel;
184import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
185import android.net.shared.PrivateDnsConfig;
186import android.net.util.MultinetworkPolicyTracker;
187import android.os.BatteryStatsManager;
188import android.os.Binder;
189import android.os.Build;
190import android.os.Bundle;
191import android.os.Handler;
192import android.os.HandlerThread;
193import android.os.IBinder;
194import android.os.Looper;
195import android.os.Message;
196import android.os.Messenger;
197import android.os.ParcelFileDescriptor;
198import android.os.Parcelable;
199import android.os.PersistableBundle;
200import android.os.PowerManager;
201import android.os.Process;
202import android.os.RemoteCallbackList;
203import android.os.RemoteException;
204import android.os.ServiceSpecificException;
205import android.os.SystemClock;
206import android.os.SystemProperties;
207import android.os.UserHandle;
208import android.os.UserManager;
209import android.provider.Settings;
210import android.sysprop.NetworkProperties;
211import android.telephony.TelephonyManager;
212import android.text.TextUtils;
213import android.util.ArrayMap;
214import android.util.ArraySet;
215import android.util.LocalLog;
216import android.util.Log;
217import android.util.Pair;
218import android.util.SparseArray;
219import android.util.SparseIntArray;
220
221import com.android.connectivity.resources.R;
222import com.android.internal.annotations.GuardedBy;
223import com.android.internal.annotations.VisibleForTesting;
224import com.android.internal.util.IndentingPrintWriter;
225import com.android.internal.util.MessageUtils;
226import com.android.modules.utils.BasicShellCommandHandler;
227import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
228import com.android.net.module.util.CollectionUtils;
229import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
230import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
231import com.android.net.module.util.LocationPermissionChecker;
232import com.android.net.module.util.NetworkCapabilitiesUtils;
233import com.android.net.module.util.PermissionUtils;
234import com.android.server.connectivity.AutodestructReference;
235import com.android.server.connectivity.DnsManager;
236import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
237import com.android.server.connectivity.FullScore;
238import com.android.server.connectivity.KeepaliveTracker;
239import com.android.server.connectivity.LingerMonitor;
240import com.android.server.connectivity.MockableSystemProperties;
241import com.android.server.connectivity.NetworkAgentInfo;
242import com.android.server.connectivity.NetworkDiagnostics;
243import com.android.server.connectivity.NetworkNotificationManager;
244import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
245import com.android.server.connectivity.NetworkOffer;
246import com.android.server.connectivity.NetworkRanker;
247import com.android.server.connectivity.PermissionMonitor;
248import com.android.server.connectivity.ProfileNetworkPreferences;
249import com.android.server.connectivity.ProxyTracker;
250import com.android.server.connectivity.QosCallbackTracker;
251
252import libcore.io.IoUtils;
253
254import java.io.FileDescriptor;
255import java.io.PrintWriter;
256import java.net.Inet4Address;
257import java.net.InetAddress;
258import java.net.InetSocketAddress;
259import java.net.UnknownHostException;
260import java.util.ArrayList;
261import java.util.Arrays;
262import java.util.Collection;
263import java.util.Collections;
264import java.util.Comparator;
265import java.util.ConcurrentModificationException;
266import java.util.HashMap;
267import java.util.HashSet;
268import java.util.List;
269import java.util.Map;
270import java.util.Objects;
271import java.util.Set;
272import java.util.SortedSet;
273import java.util.StringJoiner;
274import java.util.TreeSet;
275import java.util.concurrent.atomic.AtomicInteger;
276
277/**
278 * @hide
279 */
280public class ConnectivityService extends IConnectivityManager.Stub
281 implements PendingIntent.OnFinished {
282 private static final String TAG = ConnectivityService.class.getSimpleName();
283
284 private static final String DIAG_ARG = "--diag";
285 public static final String SHORT_ARG = "--short";
286 private static final String NETWORK_ARG = "networks";
287 private static final String REQUEST_ARG = "requests";
288
289 private static final boolean DBG = true;
290 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
291 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
292
293 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
294
295 /**
296 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
297 * by OEMs for configuration purposes, as this value is overridden by
298 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
299 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
300 * (preferably via runtime resource overlays).
301 */
302 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
303 "http://connectivitycheck.gstatic.com/generate_204";
304
305 // TODO: create better separation between radio types and network types
306
307 // how long to wait before switching back to a radio's default network
308 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
309 // system property that can override the above value
310 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
311 "android.telephony.apn-restore";
312
313 // How long to wait before putting up a "This network doesn't have an Internet connection,
314 // connect anyway?" dialog after the user selects a network that doesn't validate.
315 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
316
317 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
318 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
319 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
320 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
321
322 // The maximum number of network request allowed per uid before an exception is thrown.
323 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
324
325 // The maximum number of network request allowed for system UIDs before an exception is thrown.
326 @VisibleForTesting
327 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
328
329 @VisibleForTesting
330 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
331 @VisibleForTesting
332 protected int mNascentDelayMs;
333
334 // How long to delay to removal of a pending intent based request.
335 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
336 private final int mReleasePendingIntentDelayMs;
337
338 private MockableSystemProperties mSystemProperties;
339
340 @VisibleForTesting
341 protected final PermissionMonitor mPermissionMonitor;
342
343 private final PerUidCounter mNetworkRequestCounter;
344 @VisibleForTesting
345 final PerUidCounter mSystemNetworkRequestCounter;
346
347 private volatile boolean mLockdownEnabled;
348
349 /**
350 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
351 * internal handler thread, they don't need a lock.
352 */
353 private SparseIntArray mUidBlockedReasons = new SparseIntArray();
354
355 private final Context mContext;
356 private final ConnectivityResources mResources;
357 // The Context is created for UserHandle.ALL.
358 private final Context mUserAllContext;
359 private final Dependencies mDeps;
360 // 0 is full bad, 100 is full good
361 private int mDefaultInetConditionPublished = 0;
362
363 @VisibleForTesting
364 protected IDnsResolver mDnsResolver;
365 @VisibleForTesting
366 protected INetd mNetd;
367 private NetworkStatsManager mStatsManager;
368 private NetworkPolicyManager mPolicyManager;
369 private final NetdCallback mNetdCallback;
370
371 /**
372 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
373 * instances.
374 */
375 @GuardedBy("mTNSLock")
376 private TestNetworkService mTNS;
377
378 private final Object mTNSLock = new Object();
379
380 private String mCurrentTcpBufferSizes;
381
382 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
383 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
384
385 private enum ReapUnvalidatedNetworks {
386 // Tear down networks that have no chance (e.g. even if validated) of becoming
387 // the highest scoring network satisfying a NetworkRequest. This should be passed when
388 // all networks have been rematched against all NetworkRequests.
389 REAP,
390 // Don't reap networks. This should be passed when some networks have not yet been
391 // rematched against all NetworkRequests.
392 DONT_REAP
393 }
394
395 private enum UnneededFor {
396 LINGER, // Determine whether this network is unneeded and should be lingered.
397 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
398 }
399
400 /**
401 * used internally to clear a wakelock when transitioning
402 * from one net to another. Clear happens when we get a new
403 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
404 * after a timeout if no network is found (typically 1 min).
405 */
406 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
407
408 /**
409 * used internally to reload global proxy settings
410 */
411 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
412
413 /**
414 * PAC manager has received new port.
415 */
416 private static final int EVENT_PROXY_HAS_CHANGED = 16;
417
418 /**
419 * used internally when registering NetworkProviders
420 * obj = NetworkProviderInfo
421 */
422 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
423
424 /**
425 * used internally when registering NetworkAgents
426 * obj = Messenger
427 */
428 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
429
430 /**
431 * used to add a network request
432 * includes a NetworkRequestInfo
433 */
434 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
435
436 /**
437 * indicates a timeout period is over - check if we had a network yet or not
438 * and if not, call the timeout callback (but leave the request live until they
439 * cancel it.
440 * includes a NetworkRequestInfo
441 */
442 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
443
444 /**
445 * used to add a network listener - no request
446 * includes a NetworkRequestInfo
447 */
448 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
449
450 /**
451 * used to remove a network request, either a listener or a real request
452 * arg1 = UID of caller
453 * obj = NetworkRequest
454 */
455 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
456
457 /**
458 * used internally when registering NetworkProviders
459 * obj = Messenger
460 */
461 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
462
463 /**
464 * used internally to expire a wakelock when transitioning
465 * from one net to another. Expire happens when we fail to find
466 * a new network (typically after 1 minute) -
467 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
468 * a replacement network.
469 */
470 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
471
472 /**
473 * used to add a network request with a pending intent
474 * obj = NetworkRequestInfo
475 */
476 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
477
478 /**
479 * used to remove a pending intent and its associated network request.
480 * arg1 = UID of caller
481 * obj = PendingIntent
482 */
483 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
484
485 /**
486 * used to specify whether a network should be used even if unvalidated.
487 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
488 * arg2 = whether to remember this choice in the future (1 or 0)
489 * obj = network
490 */
491 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
492
493 /**
494 * used to ask the user to confirm a connection to an unvalidated network.
495 * obj = network
496 */
497 private static final int EVENT_PROMPT_UNVALIDATED = 29;
498
499 /**
500 * used internally to (re)configure always-on networks.
501 */
502 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
503
504 /**
505 * used to add a network listener with a pending intent
506 * obj = NetworkRequestInfo
507 */
508 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
509
510 /**
511 * used to specify whether a network should not be penalized when it becomes unvalidated.
512 */
513 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
514
515 /**
516 * used to trigger revalidation of a network.
517 */
518 private static final int EVENT_REVALIDATE_NETWORK = 36;
519
520 // Handle changes in Private DNS settings.
521 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
522
523 // Handle private DNS validation status updates.
524 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
525
526 /**
527 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
528 * been tested.
529 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
530 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
531 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
532 */
533 private static final int EVENT_NETWORK_TESTED = 41;
534
535 /**
536 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
537 * config was resolved.
538 * obj = PrivateDnsConfig
539 * arg2 = netid
540 */
541 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
542
543 /**
544 * Request ConnectivityService display provisioning notification.
545 * arg1 = Whether to make the notification visible.
546 * arg2 = NetID.
547 * obj = Intent to be launched when notification selected by user, null if !arg1.
548 */
549 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
550
551 /**
552 * Used to specify whether a network should be used even if connectivity is partial.
553 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
554 * false)
555 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
556 * obj = network
557 */
558 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
559
560 /**
561 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
562 * Both of the arguments are bitmasks, and the value of bits come from
563 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
564 * arg1 = A bitmask to describe which probes are completed.
565 * arg2 = A bitmask to describe which probes are successful.
566 */
567 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
568
569 /**
570 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
571 * arg1 = unused
572 * arg2 = netId
573 * obj = captive portal data
574 */
575 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
576
577 /**
578 * Used by setRequireVpnForUids.
579 * arg1 = whether the specified UID ranges are required to use a VPN.
580 * obj = Array of UidRange objects.
581 */
582 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
583
584 /**
585 * Used internally when setting the default networks for OemNetworkPreferences.
586 * obj = Pair<OemNetworkPreferences, listener>
587 */
588 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
589
590 /**
591 * Used to indicate the system default network becomes active.
592 */
593 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
594
595 /**
596 * Used internally when setting a network preference for a user profile.
597 * obj = Pair<ProfileNetworkPreference, Listener>
598 */
599 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
600
601 /**
602 * Event to specify that reasons for why an uid is blocked changed.
603 * arg1 = uid
604 * arg2 = blockedReasons
605 */
606 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
607
608 /**
609 * Event to register a new network offer
610 * obj = NetworkOffer
611 */
612 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
613
614 /**
615 * Event to unregister an existing network offer
616 * obj = INetworkOfferCallback
617 */
618 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
619
620 /**
621 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
622 * should be shown.
623 */
624 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
625
626 /**
627 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
628 * should be hidden.
629 */
630 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
631
632 private static String eventName(int what) {
633 return sMagicDecoderRing.get(what, Integer.toString(what));
634 }
635
636 private static IDnsResolver getDnsResolver(Context context) {
637 final DnsResolverServiceManager dsm = context.getSystemService(
638 DnsResolverServiceManager.class);
639 return IDnsResolver.Stub.asInterface(dsm.getService());
640 }
641
642 /** Handler thread used for all of the handlers below. */
643 @VisibleForTesting
644 protected final HandlerThread mHandlerThread;
645 /** Handler used for internal events. */
646 final private InternalHandler mHandler;
647 /** Handler used for incoming {@link NetworkStateTracker} events. */
648 final private NetworkStateTrackerHandler mTrackerHandler;
649 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
650 @VisibleForTesting
651 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
652
653 private final DnsManager mDnsManager;
654 private final NetworkRanker mNetworkRanker;
655
656 private boolean mSystemReady;
657 private Intent mInitialBroadcast;
658
659 private PowerManager.WakeLock mNetTransitionWakeLock;
660 private final PowerManager.WakeLock mPendingIntentWakeLock;
661
662 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
663 // the world when it changes.
664 @VisibleForTesting
665 protected final ProxyTracker mProxyTracker;
666
667 final private SettingsObserver mSettingsObserver;
668
669 private UserManager mUserManager;
670
671 // the set of network types that can only be enabled by system/sig apps
672 private List<Integer> mProtectedNetworks;
673
674 private Set<String> mWolSupportedInterfaces;
675
676 private final TelephonyManager mTelephonyManager;
677 private final AppOpsManager mAppOpsManager;
678
679 private final LocationPermissionChecker mLocationPermissionChecker;
680
681 private KeepaliveTracker mKeepaliveTracker;
682 private QosCallbackTracker mQosCallbackTracker;
683 private NetworkNotificationManager mNotifier;
684 private LingerMonitor mLingerMonitor;
685
686 // sequence number of NetworkRequests
687 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
688
689 // Sequence number for NetworkProvider IDs.
690 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
691 NetworkProvider.FIRST_PROVIDER_ID);
692
693 // NetworkRequest activity String log entries.
694 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
695 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
696
697 // NetworkInfo blocked and unblocked String log entries
698 private static final int MAX_NETWORK_INFO_LOGS = 40;
699 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
700
701 private static final int MAX_WAKELOCK_LOGS = 20;
702 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
703 private int mTotalWakelockAcquisitions = 0;
704 private int mTotalWakelockReleases = 0;
705 private long mTotalWakelockDurationMs = 0;
706 private long mMaxWakelockDurationMs = 0;
707 private long mLastWakeLockAcquireTimestamp = 0;
708
709 private final IpConnectivityLog mMetricsLog;
710
711 @GuardedBy("mBandwidthRequests")
712 private final SparseArray<Integer> mBandwidthRequests = new SparseArray(10);
713
714 @VisibleForTesting
715 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
716
717 @VisibleForTesting
718 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
719 new HashMap<>();
720
721 /**
722 * Implements support for the legacy "one network per network type" model.
723 *
724 * We used to have a static array of NetworkStateTrackers, one for each
725 * network type, but that doesn't work any more now that we can have,
726 * for example, more that one wifi network. This class stores all the
727 * NetworkAgentInfo objects that support a given type, but the legacy
728 * API will only see the first one.
729 *
730 * It serves two main purposes:
731 *
732 * 1. Provide information about "the network for a given type" (since this
733 * API only supports one).
734 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
735 * the first network for a given type changes, or if the default network
736 * changes.
737 */
738 @VisibleForTesting
739 static class LegacyTypeTracker {
740
741 private static final boolean DBG = true;
742 private static final boolean VDBG = false;
743
744 /**
745 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
746 * Each list holds references to all NetworkAgentInfos that are used to
747 * satisfy requests for that network type.
748 *
749 * This array is built out at startup such that an unsupported network
750 * doesn't get an ArrayList instance, making this a tristate:
751 * unsupported, supported but not active and active.
752 *
753 * The actual lists are populated when we scan the network types that
754 * are supported on this device.
755 *
756 * Threading model:
757 * - addSupportedType() is only called in the constructor
758 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
759 * They are therefore not thread-safe with respect to each other.
760 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
761 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
762 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
763 * - dump is thread-safe with respect to concurrent add and remove calls.
764 */
765 private final ArrayList<NetworkAgentInfo> mTypeLists[];
766 @NonNull
767 private final ConnectivityService mService;
768
769 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
770 // an entry have no timer (equivalent to -1). Lazily loaded.
771 @NonNull
772 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
773
774 LegacyTypeTracker(@NonNull ConnectivityService service) {
775 mService = service;
776 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
777 }
778
779 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
780 final PackageManager pm = ctx.getPackageManager();
781 if (pm.hasSystemFeature(FEATURE_WIFI)) {
782 addSupportedType(TYPE_WIFI);
783 }
784 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
785 addSupportedType(TYPE_WIFI_P2P);
786 }
787 if (tm.isDataCapable()) {
788 // Telephony does not have granular support for these types: they are either all
789 // supported, or none is supported
790 addSupportedType(TYPE_MOBILE);
791 addSupportedType(TYPE_MOBILE_MMS);
792 addSupportedType(TYPE_MOBILE_SUPL);
793 addSupportedType(TYPE_MOBILE_DUN);
794 addSupportedType(TYPE_MOBILE_HIPRI);
795 addSupportedType(TYPE_MOBILE_FOTA);
796 addSupportedType(TYPE_MOBILE_IMS);
797 addSupportedType(TYPE_MOBILE_CBS);
798 addSupportedType(TYPE_MOBILE_IA);
799 addSupportedType(TYPE_MOBILE_EMERGENCY);
800 }
801 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
802 addSupportedType(TYPE_BLUETOOTH);
803 }
804 if (pm.hasSystemFeature(FEATURE_WATCH)) {
805 // TYPE_PROXY is only used on Wear
806 addSupportedType(TYPE_PROXY);
807 }
808 // Ethernet is often not specified in the configs, although many devices can use it via
809 // USB host adapters. Add it as long as the ethernet service is here.
810 if (ctx.getSystemService(Context.ETHERNET_SERVICE) != null) {
811 addSupportedType(TYPE_ETHERNET);
812 }
813
814 // Always add TYPE_VPN as a supported type
815 addSupportedType(TYPE_VPN);
816 }
817
818 private void addSupportedType(int type) {
819 if (mTypeLists[type] != null) {
820 throw new IllegalStateException(
821 "legacy list for type " + type + "already initialized");
822 }
823 mTypeLists[type] = new ArrayList<>();
824 }
825
826 public boolean isTypeSupported(int type) {
827 return isNetworkTypeValid(type) && mTypeLists[type] != null;
828 }
829
830 public NetworkAgentInfo getNetworkForType(int type) {
831 synchronized (mTypeLists) {
832 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
833 return mTypeLists[type].get(0);
834 }
835 }
836 return null;
837 }
838
839 public int getRestoreTimerForType(int type) {
840 synchronized (mTypeLists) {
841 if (mRestoreTimers == null) {
842 mRestoreTimers = loadRestoreTimers();
843 }
844 return mRestoreTimers.getOrDefault(type, -1);
845 }
846 }
847
848 private ArrayMap<Integer, Integer> loadRestoreTimers() {
849 final String[] configs = mService.mResources.get().getStringArray(
850 R.array.config_legacy_networktype_restore_timers);
851 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
852 for (final String config : configs) {
853 final String[] splits = TextUtils.split(config, ",");
854 if (splits.length != 2) {
855 logwtf("Invalid restore timer token count: " + config);
856 continue;
857 }
858 try {
859 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
860 } catch (NumberFormatException e) {
861 logwtf("Invalid restore timer number format: " + config, e);
862 }
863 }
864 return ret;
865 }
866
867 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
868 boolean isDefaultNetwork) {
869 if (DBG) {
870 log("Sending " + state
871 + " broadcast for type " + type + " " + nai.toShortString()
872 + " isDefaultNetwork=" + isDefaultNetwork);
873 }
874 }
875
876 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
877 // network type, to preserve previous behaviour.
878 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
879 if (vpnNai != mService.getLegacyLockdownNai()) return;
880
881 if (vpnNai.declaredUnderlyingNetworks == null
882 || vpnNai.declaredUnderlyingNetworks.length != 1) {
883 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
884 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
885 return;
886 }
887 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
888 vpnNai.declaredUnderlyingNetworks[0]);
889 if (underlyingNai == null) return;
890
891 final int type = underlyingNai.networkInfo.getType();
892 final DetailedState state = DetailedState.CONNECTED;
893 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
894 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
895 }
896
897 /** Adds the given network to the specified legacy type list. */
898 public void add(int type, NetworkAgentInfo nai) {
899 if (!isTypeSupported(type)) {
900 return; // Invalid network type.
901 }
902 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
903
904 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
905 if (list.contains(nai)) {
906 return;
907 }
908 synchronized (mTypeLists) {
909 list.add(nai);
910 }
911
912 // Send a broadcast if this is the first network of its type or if it's the default.
913 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
914
915 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
916 // to preserve previous behaviour.
917 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
918 if ((list.size() == 1) || isDefaultNetwork) {
919 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
920 mService.sendLegacyNetworkBroadcast(nai, state, type);
921 }
922
923 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
924 maybeSendLegacyLockdownBroadcast(nai);
925 }
926 }
927
928 /** Removes the given network from the specified legacy type list. */
929 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
930 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
931 if (list == null || list.isEmpty()) {
932 return;
933 }
934 final boolean wasFirstNetwork = list.get(0).equals(nai);
935
936 synchronized (mTypeLists) {
937 if (!list.remove(nai)) {
938 return;
939 }
940 }
941
942 if (wasFirstNetwork || wasDefault) {
943 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
944 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
945 }
946
947 if (!list.isEmpty() && wasFirstNetwork) {
948 if (DBG) log("Other network available for type " + type +
949 ", sending connected broadcast");
950 final NetworkAgentInfo replacement = list.get(0);
951 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
952 mService.isDefaultNetwork(replacement));
953 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
954 }
955 }
956
957 /** Removes the given network from all legacy type lists. */
958 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
959 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
960 for (int type = 0; type < mTypeLists.length; type++) {
961 remove(type, nai, wasDefault);
962 }
963 }
964
965 // send out another legacy broadcast - currently only used for suspend/unsuspend
966 // toggle
967 public void update(NetworkAgentInfo nai) {
968 final boolean isDefault = mService.isDefaultNetwork(nai);
969 final DetailedState state = nai.networkInfo.getDetailedState();
970 for (int type = 0; type < mTypeLists.length; type++) {
971 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
972 final boolean contains = (list != null && list.contains(nai));
973 final boolean isFirst = contains && (nai == list.get(0));
974 if (isFirst || contains && isDefault) {
975 maybeLogBroadcast(nai, state, type, isDefault);
976 mService.sendLegacyNetworkBroadcast(nai, state, type);
977 }
978 }
979 }
980
981 public void dump(IndentingPrintWriter pw) {
982 pw.println("mLegacyTypeTracker:");
983 pw.increaseIndent();
984 pw.print("Supported types:");
985 for (int type = 0; type < mTypeLists.length; type++) {
986 if (mTypeLists[type] != null) pw.print(" " + type);
987 }
988 pw.println();
989 pw.println("Current state:");
990 pw.increaseIndent();
991 synchronized (mTypeLists) {
992 for (int type = 0; type < mTypeLists.length; type++) {
993 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
994 for (NetworkAgentInfo nai : mTypeLists[type]) {
995 pw.println(type + " " + nai.toShortString());
996 }
997 }
998 }
999 pw.decreaseIndent();
1000 pw.decreaseIndent();
1001 pw.println();
1002 }
1003 }
1004 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
1005
1006 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
1007 /**
1008 * Helper class which parses out priority arguments and dumps sections according to their
1009 * priority. If priority arguments are omitted, function calls the legacy dump command.
1010 */
1011 private class LocalPriorityDump {
1012 private static final String PRIORITY_ARG = "--dump-priority";
1013 private static final String PRIORITY_ARG_HIGH = "HIGH";
1014 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1015
1016 LocalPriorityDump() {}
1017
1018 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1019 doDump(fd, pw, new String[] {DIAG_ARG});
1020 doDump(fd, pw, new String[] {SHORT_ARG});
1021 }
1022
1023 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1024 doDump(fd, pw, args);
1025 }
1026
1027 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1028 if (args == null) {
1029 dumpNormal(fd, pw, args);
1030 return;
1031 }
1032
1033 String priority = null;
1034 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1035 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1036 argIndex++;
1037 priority = args[argIndex];
1038 }
1039 }
1040
1041 if (PRIORITY_ARG_HIGH.equals(priority)) {
1042 dumpHigh(fd, pw);
1043 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1044 dumpNormal(fd, pw, args);
1045 } else {
1046 // ConnectivityService publishes binder service using publishBinderService() with
1047 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang12d32a62021-05-17 16:57:15 +08001048 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1049 // legacy output for dumpsys connectivity.
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001050 // TODO: Integrate into signal dump.
1051 dumpNormal(fd, pw, args);
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001052 }
1053 }
1054 }
1055
1056 /**
1057 * Keeps track of the number of requests made under different uids.
1058 */
1059 public static class PerUidCounter {
1060 private final int mMaxCountPerUid;
1061
1062 // Map from UID to number of NetworkRequests that UID has filed.
1063 @VisibleForTesting
1064 @GuardedBy("mUidToNetworkRequestCount")
1065 final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
1066
1067 /**
1068 * Constructor
1069 *
1070 * @param maxCountPerUid the maximum count per uid allowed
1071 */
1072 public PerUidCounter(final int maxCountPerUid) {
1073 mMaxCountPerUid = maxCountPerUid;
1074 }
1075
1076 /**
1077 * Increments the request count of the given uid. Throws an exception if the number
1078 * of open requests for the uid exceeds the value of maxCounterPerUid which is the value
1079 * passed into the constructor. see: {@link #PerUidCounter(int)}.
1080 *
1081 * @throws ServiceSpecificException with
1082 * {@link ConnectivityManager.Errors.TOO_MANY_REQUESTS} if the number of requests for
1083 * the uid exceed the allowed number.
1084 *
1085 * @param uid the uid that the request was made under
1086 */
1087 public void incrementCountOrThrow(final int uid) {
1088 synchronized (mUidToNetworkRequestCount) {
1089 incrementCountOrThrow(uid, 1 /* numToIncrement */);
1090 }
1091 }
1092
1093 private void incrementCountOrThrow(final int uid, final int numToIncrement) {
1094 final int newRequestCount =
1095 mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
1096 if (newRequestCount >= mMaxCountPerUid) {
1097 throw new ServiceSpecificException(
1098 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
1099 }
1100 mUidToNetworkRequestCount.put(uid, newRequestCount);
1101 }
1102
1103 /**
1104 * Decrements the request count of the given uid.
1105 *
1106 * @param uid the uid that the request was made under
1107 */
1108 public void decrementCount(final int uid) {
1109 synchronized (mUidToNetworkRequestCount) {
1110 decrementCount(uid, 1 /* numToDecrement */);
1111 }
1112 }
1113
1114 private void decrementCount(final int uid, final int numToDecrement) {
1115 final int newRequestCount =
1116 mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
1117 if (newRequestCount < 0) {
1118 logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
1119 } else if (newRequestCount == 0) {
1120 mUidToNetworkRequestCount.delete(uid);
1121 } else {
1122 mUidToNetworkRequestCount.put(uid, newRequestCount);
1123 }
1124 }
1125
1126 /**
1127 * Used to adjust the request counter for the per-app API flows. Directly adjusting the
1128 * counter is not ideal however in the per-app flows, the nris can't be removed until they
1129 * are used to create the new nris upon set. Therefore the request count limit can be
1130 * artificially hit. This method is used as a workaround for this particular case so that
1131 * the request counts are accounted for correctly.
1132 * @param uid the uid to adjust counts for
1133 * @param numOfNewRequests the new request count to account for
1134 * @param r the runnable to execute
1135 */
1136 public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
1137 // This should only be used on the handler thread as per all current and foreseen
1138 // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
1139 // no ref to the outer ConnectivityService.
1140 synchronized (mUidToNetworkRequestCount) {
1141 final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
1142 decrementCount(uid, reqCountOverage);
1143 r.run();
1144 incrementCountOrThrow(uid, reqCountOverage);
1145 }
1146 }
1147
1148 private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
1149 final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
1150 + numOfNewRequests;
1151 return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
1152 ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
1153 }
1154 }
1155
1156 /**
1157 * Dependencies of ConnectivityService, for injection in tests.
1158 */
1159 @VisibleForTesting
1160 public static class Dependencies {
1161 public int getCallingUid() {
1162 return Binder.getCallingUid();
1163 }
1164
1165 /**
1166 * Get system properties to use in ConnectivityService.
1167 */
1168 public MockableSystemProperties getSystemProperties() {
1169 return new MockableSystemProperties();
1170 }
1171
1172 /**
1173 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1174 */
1175 public ConnectivityResources getResources(@NonNull Context ctx) {
1176 return new ConnectivityResources(ctx);
1177 }
1178
1179 /**
1180 * Create a HandlerThread to use in ConnectivityService.
1181 */
1182 public HandlerThread makeHandlerThread() {
1183 return new HandlerThread("ConnectivityServiceThread");
1184 }
1185
1186 /**
1187 * Get a reference to the ModuleNetworkStackClient.
1188 */
1189 public NetworkStackClientBase getNetworkStack() {
1190 return ModuleNetworkStackClient.getInstance(null);
1191 }
1192
1193 /**
1194 * @see ProxyTracker
1195 */
1196 public ProxyTracker makeProxyTracker(@NonNull Context context,
1197 @NonNull Handler connServiceHandler) {
1198 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1199 }
1200
1201 /**
1202 * @see NetIdManager
1203 */
1204 public NetIdManager makeNetIdManager() {
1205 return new NetIdManager();
1206 }
1207
1208 /**
1209 * @see NetworkUtils#queryUserAccess(int, int)
1210 */
1211 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1212 return cs.queryUserAccess(uid, network);
1213 }
1214
1215 /**
1216 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1217 * requires CAP_NET_ADMIN, which the unit tests do not have.
1218 */
1219 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1220 InetSocketAddress remote) {
1221 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1222 }
1223
1224 /**
1225 * @see MultinetworkPolicyTracker
1226 */
1227 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1228 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1229 return new MultinetworkPolicyTracker(c, h, r);
1230 }
1231
1232 /**
1233 * @see BatteryStatsManager
1234 */
1235 public void reportNetworkInterfaceForTransports(Context context, String iface,
1236 int[] transportTypes) {
1237 final BatteryStatsManager batteryStats =
1238 context.getSystemService(BatteryStatsManager.class);
1239 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1240 }
1241
1242 public boolean getCellular464XlatEnabled() {
1243 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1244 }
1245 }
1246
1247 public ConnectivityService(Context context) {
1248 this(context, getDnsResolver(context), new IpConnectivityLog(),
1249 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1250 new Dependencies());
1251 }
1252
1253 @VisibleForTesting
1254 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1255 IpConnectivityLog logger, INetd netd, Dependencies deps) {
1256 if (DBG) log("ConnectivityService starting up");
1257
1258 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
1259 mSystemProperties = mDeps.getSystemProperties();
1260 mNetIdManager = mDeps.makeNetIdManager();
1261 mContext = Objects.requireNonNull(context, "missing Context");
1262 mResources = deps.getResources(mContext);
1263 mNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_UID);
1264 mSystemNetworkRequestCounter = new PerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID);
1265
1266 mMetricsLog = logger;
1267 mNetworkRanker = new NetworkRanker();
1268 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1269 mDefaultRequest = new NetworkRequestInfo(
1270 Process.myUid(), defaultInternetRequest, null,
1271 new Binder(), NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1272 null /* attributionTags */);
1273 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1274 mDefaultNetworkRequests.add(mDefaultRequest);
1275 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
1276
1277 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
1278 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
1279
1280 // The default WiFi request is a background request so that apps using WiFi are
1281 // migrated to a better network (typically ethernet) when one comes up, instead
1282 // of staying on WiFi forever.
1283 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1284 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1285
1286 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1287 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1288 NetworkRequest.Type.BACKGROUND_REQUEST);
1289
1290 mHandlerThread = mDeps.makeHandlerThread();
1291 mHandlerThread.start();
1292 mHandler = new InternalHandler(mHandlerThread.getLooper());
1293 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
1294 mConnectivityDiagnosticsHandler =
1295 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
1296
1297 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
1298 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
1299
1300 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1301 // TODO: Consider making the timer customizable.
1302 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1303
1304 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
1305 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
1306 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
1307 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
1308
1309 mNetd = netd;
1310 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
1311 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
1312 mLocationPermissionChecker = new LocationPermissionChecker(mContext);
1313
1314 // To ensure uid state is synchronized with Network Policy, register for
1315 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1316 // reading existing policy from disk.
1317 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
1318
1319 final PowerManager powerManager = (PowerManager) context.getSystemService(
1320 Context.POWER_SERVICE);
1321 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1322 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
1323
1324 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1325 mProtectedNetworks = new ArrayList<>();
1326 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
1327 for (int p : protectedNetworks) {
1328 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
1329 mProtectedNetworks.add(p);
1330 } else {
1331 if (DBG) loge("Ignoring protectedNetwork " + p);
1332 }
1333 }
1334
1335 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1336
1337 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
1338
1339 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
1340 // Listen for user add/removes to inform PermissionMonitor.
1341 // Should run on mHandler to avoid any races.
1342 final IntentFilter userIntentFilter = new IntentFilter();
1343 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1344 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1345 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1346 null /* broadcastPermission */, mHandler);
1347
1348 // Listen to package add/removes for netd
1349 final IntentFilter packageIntentFilter = new IntentFilter();
1350 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1351 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1352 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1353 packageIntentFilter.addDataScheme("package");
1354 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
1355 null /* broadcastPermission */, mHandler);
1356
1357 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
1358
1359 mNetdCallback = new NetdCallback();
1360 try {
1361 mNetd.registerUnsolicitedEventListener(mNetdCallback);
1362 } catch (RemoteException | ServiceSpecificException e) {
1363 loge("Error registering event listener :" + e);
1364 }
1365
1366 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1367 registerSettingsCallbacks();
1368
1369 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
1370 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
1371 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
1372
1373 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
1374 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
1375 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1376 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
1377 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
1378 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1379 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
1380
1381 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
1382 mContext, mHandler, () -> updateAvoidBadWifi());
1383 mMultinetworkPolicyTracker.start();
1384
1385 mDnsManager = new DnsManager(mContext, mDnsResolver);
1386 registerPrivateDnsSettingsCallbacks();
1387
1388 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1389 // request that doesn't allow fallback to the default network. It should never be visible
1390 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1391 // arguments like the handler or the DnsResolver.
1392 // TODO : remove this ; it is probably better handled with a sentinel request.
1393 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen4f612fa2021-05-14 14:30:43 +08001394 new Network(INetd.UNREACHABLE_NET_ID),
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00001395 new NetworkInfo(TYPE_NONE, 0, "", ""),
1396 new LinkProperties(), new NetworkCapabilities(),
1397 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
1398 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1399 mLingerDelayMs, mQosCallbackTracker, mDeps);
1400 }
1401
1402 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
1403 return createDefaultNetworkCapabilitiesForUidRange(new UidRange(uid, uid));
1404 }
1405
1406 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRange(
1407 @NonNull final UidRange uids) {
1408 final NetworkCapabilities netCap = new NetworkCapabilities();
1409 netCap.addCapability(NET_CAPABILITY_INTERNET);
1410 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1411 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
1412 netCap.setUids(UidRange.toIntRanges(Collections.singleton(uids)));
1413 return netCap;
1414 }
1415
1416 private NetworkRequest createDefaultRequest() {
1417 return createDefaultInternetRequestForTransport(
1418 TYPE_NONE, NetworkRequest.Type.REQUEST);
1419 }
1420
1421 private NetworkRequest createDefaultInternetRequestForTransport(
1422 int transportType, NetworkRequest.Type type) {
1423 final NetworkCapabilities netCap = new NetworkCapabilities();
1424 netCap.addCapability(NET_CAPABILITY_INTERNET);
1425 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
1426 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1427 if (transportType > TYPE_NONE) {
1428 netCap.addTransportType(transportType);
1429 }
1430 return createNetworkRequest(type, netCap);
1431 }
1432
1433 private NetworkRequest createNetworkRequest(
1434 NetworkRequest.Type type, NetworkCapabilities netCap) {
1435 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1436 }
1437
1438 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1439 NetworkRequest.Type type) {
1440 final NetworkCapabilities netCap = new NetworkCapabilities();
1441 netCap.clearAll();
1442 netCap.addCapability(capability);
1443 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1444 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1445 }
1446
1447 // Used only for testing.
1448 // TODO: Delete this and either:
1449 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
1450 // changing ContentResolver to make registerContentObserver non-final).
1451 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1452 // by subclassing SettingsObserver.
1453 @VisibleForTesting
1454 void updateAlwaysOnNetworks() {
1455 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1456 }
1457
1458 // See FakeSettingsProvider comment above.
1459 @VisibleForTesting
1460 void updatePrivateDnsSettings() {
1461 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1462 }
1463
1464 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, int id) {
1465 final boolean enable = mContext.getResources().getBoolean(id);
1466 handleAlwaysOnNetworkRequest(networkRequest, enable);
1467 }
1468
1469 private void handleAlwaysOnNetworkRequest(
1470 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
1471 final boolean enable = toBool(Settings.Global.getInt(
1472 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
1473 handleAlwaysOnNetworkRequest(networkRequest, enable);
1474 }
1475
1476 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
1477 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
1478 if (enable == isEnabled) {
1479 return; // Nothing to do.
1480 }
1481
1482 if (enable) {
1483 handleRegisterNetworkRequest(new NetworkRequestInfo(
1484 Process.myUid(), networkRequest, null, new Binder(),
1485 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
1486 null /* attributionTags */));
1487 } else {
1488 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1489 /* callOnUnavailable */ false);
1490 }
1491 }
1492
1493 private void handleConfigureAlwaysOnNetworks() {
1494 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1495 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1496 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1497 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
1498 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1499 R.bool.config_vehicleInternalNetworkAlwaysRequested);
1500 // TODO (b/183076074): remove legacy fallback after migrating overlays
1501 final boolean legacyAlwaysRequested = mContext.getResources().getBoolean(
1502 mContext.getResources().getIdentifier(
1503 "config_vehicleInternalNetworkAlwaysRequested", "bool", "android"));
1504 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
1505 vehicleAlwaysRequested || legacyAlwaysRequested);
1506 }
1507
1508 private void registerSettingsCallbacks() {
1509 // Watch for global HTTP proxy changes.
1510 mSettingsObserver.observe(
1511 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1512 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1513
1514 // Watch for whether or not to keep mobile data always on.
1515 mSettingsObserver.observe(
1516 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
1517 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1518
1519 // Watch for whether or not to keep wifi always on.
1520 mSettingsObserver.observe(
1521 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
1522 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1523 }
1524
1525 private void registerPrivateDnsSettingsCallbacks() {
1526 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1527 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1528 }
1529 }
1530
1531 private synchronized int nextNetworkRequestId() {
1532 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1533 // doing that.
1534 return mNextNetworkRequestId++;
1535 }
1536
1537 @VisibleForTesting
1538 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1539 if (network == null) {
1540 return null;
1541 }
1542 return getNetworkAgentInfoForNetId(network.getNetId());
1543 }
1544
1545 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
1546 synchronized (mNetworkForNetId) {
1547 return mNetworkForNetId.get(netId);
1548 }
1549 }
1550
1551 // TODO: determine what to do when more than one VPN applies to |uid|.
1552 private NetworkAgentInfo getVpnForUid(int uid) {
1553 synchronized (mNetworkForNetId) {
1554 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1555 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
1556 if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
1557 return nai;
1558 }
1559 }
1560 }
1561 return null;
1562 }
1563
1564 private Network[] getVpnUnderlyingNetworks(int uid) {
1565 if (mLockdownEnabled) return null;
1566 final NetworkAgentInfo nai = getVpnForUid(uid);
1567 if (nai != null) return nai.declaredUnderlyingNetworks;
1568 return null;
1569 }
1570
1571 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
1572 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1573
1574 final Network[] networks = getVpnUnderlyingNetworks(uid);
1575 if (networks != null) {
1576 // getUnderlyingNetworks() returns:
1577 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1578 // empty array => the VPN explicitly said "no default network".
1579 // non-empty array => the VPN specified one or more default networks; we use the
1580 // first one.
1581 if (networks.length > 0) {
1582 nai = getNetworkAgentInfoForNetwork(networks[0]);
1583 } else {
1584 nai = null;
1585 }
1586 }
1587 return nai;
1588 }
1589
1590 /**
1591 * Check if UID should be blocked from using the specified network.
1592 */
1593 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1594 final int uid, final boolean ignoreBlocked) {
1595 // Networks aren't blocked when ignoring blocked status
1596 if (ignoreBlocked) {
1597 return false;
1598 }
1599 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
1600 final long ident = Binder.clearCallingIdentity();
1601 try {
1602 final boolean metered = nc == null ? true : nc.isMetered();
1603 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1604 } finally {
1605 Binder.restoreCallingIdentity(ident);
1606 }
1607 }
1608
1609 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
1610 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1611 return;
1612 }
1613 final boolean blocked;
1614 synchronized (mBlockedAppUids) {
1615 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1616 blocked = true;
1617 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1618 blocked = false;
1619 } else {
1620 return;
1621 }
1622 }
1623 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1624 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1625 mNetworkInfoBlockingLogs.log(action + " " + uid);
1626 }
1627
1628 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
1629 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1630 return;
1631 }
1632 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
1633 final int requestId = nri.getActiveRequest() != null
1634 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
1635 mNetworkInfoBlockingLogs.log(String.format(
1636 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
1637 Integer.toHexString(blocked)));
1638 }
1639
1640 /**
1641 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
1642 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1643 * on {@link #isNetworkWithCapabilitiesBlocked}.
1644 */
1645 @NonNull
1646 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1647 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
1648 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1649 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1650 // but only exists if an app asks about them or requests them. Ensure the requesting app
1651 // gets the type it asks for.
1652 filtered.setType(type);
1653 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1654 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1655 null /* extraInfo */);
1656 }
1657 filterForLegacyLockdown(filtered);
1658 return filtered;
1659 }
1660
1661 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1662 boolean ignoreBlocked) {
1663 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1664 nai.networkCapabilities, uid, ignoreBlocked);
1665 }
1666
1667 /**
1668 * Return NetworkInfo for the active (i.e., connected) network interface.
1669 * It is assumed that at most one network is active at a time. If more
1670 * than one is active, it is indeterminate which will be returned.
1671 * @return the info for the active network, or {@code null} if none is
1672 * active
1673 */
1674 @Override
1675 public NetworkInfo getActiveNetworkInfo() {
1676 enforceAccessPermission();
1677 final int uid = mDeps.getCallingUid();
1678 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1679 if (nai == null) return null;
1680 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1681 maybeLogBlockedNetworkInfo(networkInfo, uid);
1682 return networkInfo;
1683 }
1684
1685 @Override
1686 public Network getActiveNetwork() {
1687 enforceAccessPermission();
1688 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
1689 }
1690
1691 @Override
1692 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1693 PermissionUtils.enforceNetworkStackPermission(mContext);
1694 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
1695 }
1696
1697 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
1698 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1699 if (vpnNai != null) {
1700 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1701 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1702 return vpnNai.network;
1703 }
1704 }
1705
1706 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
1707 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1708 ignoreBlocked)) {
1709 return null;
1710 }
1711 return nai.network;
1712 }
1713
1714 @Override
1715 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1716 PermissionUtils.enforceNetworkStackPermission(mContext);
1717 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1718 if (nai == null) return null;
1719 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1720 }
1721
1722 /** Returns a NetworkInfo object for a network that doesn't exist. */
1723 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1724 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1725 getNetworkTypeName(networkType), "" /* subtypeName */);
1726 info.setIsAvailable(true);
1727 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1728 // background data is restricted.
1729 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1730 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1731 ? DetailedState.BLOCKED
1732 : DetailedState.DISCONNECTED;
1733 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1734 filterForLegacyLockdown(info);
1735 return info;
1736 }
1737
1738 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
1739 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1740 return null;
1741 }
1742 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1743 if (nai == null) {
1744 return makeFakeNetworkInfo(networkType, uid);
1745 }
1746 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1747 false);
1748 }
1749
1750 @Override
1751 public NetworkInfo getNetworkInfo(int networkType) {
1752 enforceAccessPermission();
1753 final int uid = mDeps.getCallingUid();
1754 if (getVpnUnderlyingNetworks(uid) != null) {
1755 // A VPN is active, so we may need to return one of its underlying networks. This
1756 // information is not available in LegacyTypeTracker, so we have to get it from
1757 // getNetworkAgentInfoForUid.
1758 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1759 if (nai == null) return null;
1760 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1761 if (networkInfo.getType() == networkType) {
1762 return networkInfo;
1763 }
1764 }
1765 return getFilteredNetworkInfoForType(networkType, uid);
1766 }
1767
1768 @Override
1769 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1770 enforceAccessPermission();
1771 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1772 if (nai == null) return null;
1773 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
1774 }
1775
1776 @Override
1777 public NetworkInfo[] getAllNetworkInfo() {
1778 enforceAccessPermission();
1779 final ArrayList<NetworkInfo> result = new ArrayList<>();
1780 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1781 networkType++) {
1782 NetworkInfo info = getNetworkInfo(networkType);
1783 if (info != null) {
1784 result.add(info);
1785 }
1786 }
1787 return result.toArray(new NetworkInfo[result.size()]);
1788 }
1789
1790 @Override
1791 public Network getNetworkForType(int networkType) {
1792 enforceAccessPermission();
1793 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1794 return null;
1795 }
1796 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1797 if (nai == null) {
1798 return null;
1799 }
1800 final int uid = mDeps.getCallingUid();
1801 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
1802 return null;
1803 }
1804 return nai.network;
1805 }
1806
1807 @Override
1808 public Network[] getAllNetworks() {
1809 enforceAccessPermission();
1810 synchronized (mNetworkForNetId) {
1811 final Network[] result = new Network[mNetworkForNetId.size()];
1812 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1813 result[i] = mNetworkForNetId.valueAt(i).network;
1814 }
1815 return result;
1816 }
1817 }
1818
1819 @Override
1820 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
1821 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
1822 // The basic principle is: if an app's traffic could possibly go over a
1823 // network, without the app doing anything multinetwork-specific,
1824 // (hence, by "default"), then include that network's capabilities in
1825 // the array.
1826 //
1827 // In the normal case, app traffic only goes over the system's default
1828 // network connection, so that's the only network returned.
1829 //
1830 // With a VPN in force, some app traffic may go into the VPN, and thus
1831 // over whatever underlying networks the VPN specifies, while other app
1832 // traffic may go over the system default network (e.g.: a split-tunnel
1833 // VPN, or an app disallowed by the VPN), so the set of networks
1834 // returned includes the VPN's underlying networks and the system
1835 // default.
1836 enforceAccessPermission();
1837
1838 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
1839
1840 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
1841 if (!nri.isBeingSatisfied()) {
1842 continue;
1843 }
1844 final NetworkAgentInfo nai = nri.getSatisfier();
1845 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1846 if (null != nc
1847 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
1848 && !result.containsKey(nai.network)) {
1849 result.put(
1850 nai.network,
1851 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1852 nc, false /* includeLocationSensitiveInfo */,
1853 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1854 callingAttributionTag));
1855 }
1856 }
1857
1858 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
1859 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
1860 if (null != networks) {
1861 for (final Network network : networks) {
1862 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
1863 if (null != nc) {
1864 result.put(
1865 network,
1866 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1867 nc,
1868 false /* includeLocationSensitiveInfo */,
1869 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
1870 callingAttributionTag));
1871 }
1872 }
1873 }
1874
1875 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1876 out = result.values().toArray(out);
1877 return out;
1878 }
1879
1880 @Override
1881 public boolean isNetworkSupported(int networkType) {
1882 enforceAccessPermission();
1883 return mLegacyTypeTracker.isTypeSupported(networkType);
1884 }
1885
1886 /**
1887 * Return LinkProperties for the active (i.e., connected) default
1888 * network interface for the calling uid.
1889 * @return the ip properties for the active network, or {@code null} if
1890 * none is active
1891 */
1892 @Override
1893 public LinkProperties getActiveLinkProperties() {
1894 enforceAccessPermission();
1895 final int uid = mDeps.getCallingUid();
1896 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1897 if (nai == null) return null;
1898 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
1899 Binder.getCallingPid(), uid);
1900 }
1901
1902 @Override
1903 public LinkProperties getLinkPropertiesForType(int networkType) {
1904 enforceAccessPermission();
1905 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1906 final LinkProperties lp = getLinkProperties(nai);
1907 if (lp == null) return null;
1908 return linkPropertiesRestrictedForCallerPermissions(
1909 lp, Binder.getCallingPid(), mDeps.getCallingUid());
1910 }
1911
1912 // TODO - this should be ALL networks
1913 @Override
1914 public LinkProperties getLinkProperties(Network network) {
1915 enforceAccessPermission();
1916 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
1917 if (lp == null) return null;
1918 return linkPropertiesRestrictedForCallerPermissions(
1919 lp, Binder.getCallingPid(), mDeps.getCallingUid());
1920 }
1921
1922 @Nullable
1923 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
1924 if (nai == null) {
1925 return null;
1926 }
1927 synchronized (nai) {
1928 return nai.linkProperties;
1929 }
1930 }
1931
1932 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
1933 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1934 }
1935
1936 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
1937 if (nai == null) return null;
1938 synchronized (nai) {
1939 return networkCapabilitiesRestrictedForCallerPermissions(
1940 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
1941 }
1942 }
1943
1944 @Override
1945 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
1946 @Nullable String callingAttributionTag) {
1947 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
1948 enforceAccessPermission();
1949 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
1950 getNetworkCapabilitiesInternal(network),
1951 false /* includeLocationSensitiveInfo */,
1952 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
1953 }
1954
1955 @VisibleForTesting
1956 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
1957 NetworkCapabilities nc, int callerPid, int callerUid) {
1958 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
1959 if (!checkSettingsPermission(callerPid, callerUid)) {
1960 newNc.setUids(null);
1961 newNc.setSSID(null);
1962 }
1963 if (newNc.getNetworkSpecifier() != null) {
1964 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
1965 }
1966 newNc.setAdministratorUids(new int[0]);
1967 if (!checkAnyPermissionOf(
1968 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
1969 newNc.setSubscriptionIds(Collections.emptySet());
1970 }
1971
1972 return newNc;
1973 }
1974
1975 /**
1976 * Wrapper used to cache the permission check results performed for the corresponding
1977 * app. This avoid performing multiple permission checks for different fields in
1978 * NetworkCapabilities.
1979 * Note: This wrapper does not support any sort of invalidation and thus must not be
1980 * persistent or long-lived. It may only be used for the time necessary to
1981 * compute the redactions required by one particular NetworkCallback or
1982 * synchronous call.
1983 */
1984 private class RedactionPermissionChecker {
1985 private final int mCallingPid;
1986 private final int mCallingUid;
1987 @NonNull private final String mCallingPackageName;
1988 @Nullable private final String mCallingAttributionTag;
1989
1990 private Boolean mHasLocationPermission = null;
1991 private Boolean mHasLocalMacAddressPermission = null;
1992 private Boolean mHasSettingsPermission = null;
1993
1994 RedactionPermissionChecker(int callingPid, int callingUid,
1995 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
1996 mCallingPid = callingPid;
1997 mCallingUid = callingUid;
1998 mCallingPackageName = callingPackageName;
1999 mCallingAttributionTag = callingAttributionTag;
2000 }
2001
2002 private boolean hasLocationPermissionInternal() {
2003 final long token = Binder.clearCallingIdentity();
2004 try {
2005 return mLocationPermissionChecker.checkLocationPermission(
2006 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2007 null /* message */);
2008 } finally {
2009 Binder.restoreCallingIdentity(token);
2010 }
2011 }
2012
2013 /**
2014 * Returns whether the app holds location permission or not (might return cached result
2015 * if the permission was already checked before).
2016 */
2017 public boolean hasLocationPermission() {
2018 if (mHasLocationPermission == null) {
2019 // If there is no cached result, perform the check now.
2020 mHasLocationPermission = hasLocationPermissionInternal();
2021 }
2022 return mHasLocationPermission;
2023 }
2024
2025 /**
2026 * Returns whether the app holds local mac address permission or not (might return cached
2027 * result if the permission was already checked before).
2028 */
2029 public boolean hasLocalMacAddressPermission() {
2030 if (mHasLocalMacAddressPermission == null) {
2031 // If there is no cached result, perform the check now.
2032 mHasLocalMacAddressPermission =
2033 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2034 }
2035 return mHasLocalMacAddressPermission;
2036 }
2037
2038 /**
2039 * Returns whether the app holds settings permission or not (might return cached
2040 * result if the permission was already checked before).
2041 */
2042 public boolean hasSettingsPermission() {
2043 if (mHasSettingsPermission == null) {
2044 // If there is no cached result, perform the check now.
2045 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2046 }
2047 return mHasSettingsPermission;
2048 }
2049 }
2050
2051 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2052 @NetworkCapabilities.NetCapability long redaction) {
2053 return (redactions & redaction) != 0;
2054 }
2055
2056 /**
2057 * Use the provided |applicableRedactions| to check the receiving app's
2058 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2059 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2060 * before being sent to the corresponding app.
2061 */
2062 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2063 @NetworkCapabilities.RedactionType long applicableRedactions,
2064 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2065 boolean includeLocationSensitiveInfo) {
2066 long redactions = applicableRedactions;
2067 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2068 if (includeLocationSensitiveInfo
2069 && redactionPermissionChecker.hasLocationPermission()) {
2070 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2071 }
2072 }
2073 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2074 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2075 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2076 }
2077 }
2078 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2079 if (redactionPermissionChecker.hasSettingsPermission()) {
2080 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2081 }
2082 }
2083 return redactions;
2084 }
2085
2086 @VisibleForTesting
2087 @Nullable
2088 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2089 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
2090 int callingPid, int callingUid, @NonNull String callingPkgName,
2091 @Nullable String callingAttributionTag) {
2092 if (nc == null) {
2093 return null;
2094 }
2095 // Avoid doing location permission check if the transport info has no location sensitive
2096 // data.
2097 final RedactionPermissionChecker redactionPermissionChecker =
2098 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2099 callingAttributionTag);
2100 final long redactions = retrieveRequiredRedactions(
2101 nc.getApplicableRedactions(), redactionPermissionChecker,
2102 includeLocationSensitiveInfo);
2103 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
2104 // Reset owner uid if not destined for the owner app.
2105 if (callingUid != nc.getOwnerUid()) {
2106 newNc.setOwnerUid(INVALID_UID);
2107 return newNc;
2108 }
2109 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2110 if (nc.hasTransport(TRANSPORT_VPN)) {
2111 // Owner UIDs already checked above. No need to re-check.
2112 return newNc;
2113 }
2114 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2115 // Else include the owner UID iff the calling has location permission to provide backwards
2116 // compatibility for older apps.
2117 if (!includeLocationSensitiveInfo
2118 && isTargetSdkAtleast(
2119 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
2120 newNc.setOwnerUid(INVALID_UID);
2121 return newNc;
2122 }
2123 // Reset owner uid if the app has no location permission.
2124 if (!redactionPermissionChecker.hasLocationPermission()) {
2125 newNc.setOwnerUid(INVALID_UID);
2126 }
2127 return newNc;
2128 }
2129
2130 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2131 LinkProperties lp, int callerPid, int callerUid) {
2132 if (lp == null) return new LinkProperties();
2133
2134 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2135 final boolean needsSanitization =
2136 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2137 if (!needsSanitization) {
2138 return new LinkProperties(lp);
2139 }
2140
2141 if (checkSettingsPermission(callerPid, callerUid)) {
2142 return new LinkProperties(lp, true /* parcelSensitiveFields */);
2143 }
2144
2145 final LinkProperties newLp = new LinkProperties(lp);
2146 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2147 // object gets parceled.
2148 newLp.setCaptivePortalApiUrl(null);
2149 newLp.setCaptivePortalData(null);
2150 return newLp;
2151 }
2152
2153 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2154 int callerUid, String callerPackageName) {
2155 if (!checkSettingsPermission()) {
2156 // There is no need to track the effective UID of the request here. If the caller lacks
2157 // the settings permission, the effective UID is the same as the calling ID.
2158 nc.setSingleUid(callerUid);
2159 }
2160 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
2161 nc.setAdministratorUids(new int[0]);
2162
2163 // Clear owner UID; this can never come from an app.
2164 nc.setOwnerUid(INVALID_UID);
2165 }
2166
2167 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
2168 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
2169 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2170 }
2171 }
2172
2173 @Override
2174 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2175 enforceAccessPermission();
2176 final int callerUid = Binder.getCallingUid();
2177 final long token = Binder.clearCallingIdentity();
2178 try {
2179 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2180 } finally {
2181 Binder.restoreCallingIdentity(token);
2182 }
2183 }
2184
2185 // TODO: Consider delete this function or turn it into a no-op method.
2186 @Override
2187 public NetworkState[] getAllNetworkState() {
2188 // This contains IMSI details, so make sure the caller is privileged.
2189 PermissionUtils.enforceNetworkStackPermission(mContext);
2190
2191 final ArrayList<NetworkState> result = new ArrayList<>();
2192 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
2193 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2194 // NetworkAgentInfo.
2195 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
2196 if (nai != null && nai.networkInfo.isConnected()) {
2197 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
2198 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2199 snapshot.getNetwork(), snapshot.getSubscriberId()));
2200 }
2201 }
2202 return result.toArray(new NetworkState[result.size()]);
2203 }
2204
2205 @Override
2206 @NonNull
2207 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
2208 // This contains IMSI details, so make sure the caller is privileged.
2209 PermissionUtils.enforceNetworkStackPermission(mContext);
2210
2211 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2212 for (Network network : getAllNetworks()) {
2213 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2214 // TODO: Consider include SUSPENDED networks, which should be considered as
2215 // temporary shortage of connectivity of a connected network.
2216 if (nai != null && nai.networkInfo.isConnected()) {
2217 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2218 // NetworkCapabilities, which may contain UIDs of apps to which the
2219 // network applies. Should the UIDs be cleared so as not to leak or
2220 // interfere ?
2221 result.add(nai.getNetworkStateSnapshot());
2222 }
2223 }
2224 return result;
2225 }
2226
2227 @Override
2228 public boolean isActiveNetworkMetered() {
2229 enforceAccessPermission();
2230
2231 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
2232 if (caps != null) {
2233 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2234 } else {
2235 // Always return the most conservative value
2236 return true;
2237 }
2238 }
2239
2240 /**
2241 * Ensures that the system cannot call a particular method.
2242 */
2243 private boolean disallowedBecauseSystemCaller() {
2244 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
2245 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2246 // for devices launched with Q and above. However, existing devices upgrading to Q and
2247 // above must continued to be supported for few more releases.
2248 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
2249 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
2250 log("This method exists only for app backwards compatibility"
2251 + " and must not be called by system services.");
2252 return true;
2253 }
2254 return false;
2255 }
2256
2257 /**
2258 * Ensure that a network route exists to deliver traffic to the specified
2259 * host via the specified network interface.
2260 * @param networkType the type of the network over which traffic to the
2261 * specified host is to be routed
2262 * @param hostAddress the IP address of the host to which the route is
2263 * desired
2264 * @return {@code true} on success, {@code false} on failure
2265 */
2266 @Override
2267 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2268 String callingPackageName, String callingAttributionTag) {
2269 if (disallowedBecauseSystemCaller()) {
2270 return false;
2271 }
2272 enforceChangePermission(callingPackageName, callingAttributionTag);
2273 if (mProtectedNetworks.contains(networkType)) {
2274 enforceConnectivityRestrictedNetworksPermission();
2275 }
2276
2277 InetAddress addr;
2278 try {
2279 addr = InetAddress.getByAddress(hostAddress);
2280 } catch (UnknownHostException e) {
2281 if (DBG) log("requestRouteToHostAddress got " + e.toString());
2282 return false;
2283 }
2284
2285 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
2286 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
2287 return false;
2288 }
2289
2290 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2291 if (nai == null) {
2292 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
2293 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2294 } else {
2295 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2296 }
2297 return false;
2298 }
2299
2300 DetailedState netState;
2301 synchronized (nai) {
2302 netState = nai.networkInfo.getDetailedState();
2303 }
2304
2305 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
2306 if (VDBG) {
2307 log("requestRouteToHostAddress on down network "
2308 + "(" + networkType + ") - dropped"
2309 + " netState=" + netState);
2310 }
2311 return false;
2312 }
2313
2314 final int uid = mDeps.getCallingUid();
2315 final long token = Binder.clearCallingIdentity();
2316 try {
2317 LinkProperties lp;
2318 int netId;
2319 synchronized (nai) {
2320 lp = nai.linkProperties;
2321 netId = nai.network.getNetId();
2322 }
2323 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
2324 if (DBG) {
2325 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2326 }
2327 return ok;
2328 } finally {
2329 Binder.restoreCallingIdentity(token);
2330 }
2331 }
2332
2333 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
2334 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
2335 if (bestRoute == null) {
2336 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
2337 } else {
2338 String iface = bestRoute.getInterface();
2339 if (bestRoute.getGateway().equals(addr)) {
2340 // if there is no better route, add the implied hostroute for our gateway
2341 bestRoute = RouteInfo.makeHostRoute(addr, iface);
2342 } else {
2343 // if we will connect to this through another route, add a direct route
2344 // to it's gateway
2345 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
2346 }
2347 }
2348 if (DBG) log("Adding legacy route " + bestRoute +
2349 " for UID/PID " + uid + "/" + Binder.getCallingPid());
2350
2351 final String dst = bestRoute.getDestinationLinkAddress().toString();
2352 final String nextHop = bestRoute.hasGateway()
2353 ? bestRoute.getGateway().getHostAddress() : "";
2354 try {
2355 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2356 } catch (RemoteException | ServiceSpecificException e) {
2357 if (DBG) loge("Exception trying to add a route: " + e);
2358 return false;
2359 }
2360 return true;
2361 }
2362
2363 class DnsResolverUnsolicitedEventCallback extends
2364 IDnsResolverUnsolicitedEventListener.Stub {
2365 @Override
2366 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
2367 try {
2368 mHandler.sendMessage(mHandler.obtainMessage(
2369 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
2370 new PrivateDnsValidationUpdate(event.netId,
2371 InetAddresses.parseNumericAddress(event.ipAddress),
2372 event.hostname, event.validation)));
2373 } catch (IllegalArgumentException e) {
2374 loge("Error parsing ip address in validation event");
2375 }
2376 }
2377
2378 @Override
2379 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2380 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
2381 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2382 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2383 // event callback for certain nai. e.g. cellular. Register here to pass to
2384 // NetworkMonitor instead.
2385 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allow one
2386 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2387 // multiple NetworkMonitor registrants.
2388 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
2389 nai.networkMonitor().notifyDnsResponse(event.healthResult);
2390 }
2391 }
2392
2393 @Override
2394 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2395 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2396 event.prefixAddress, event.prefixLength));
2397 }
2398
2399 @Override
2400 public int getInterfaceVersion() {
2401 return this.VERSION;
2402 }
2403
2404 @Override
2405 public String getInterfaceHash() {
2406 return this.HASH;
2407 }
2408 }
2409
2410 @VisibleForTesting
2411 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2412 new DnsResolverUnsolicitedEventCallback();
2413
2414 private void registerDnsResolverUnsolicitedEventListener() {
2415 try {
2416 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
2417 } catch (Exception e) {
2418 loge("Error registering DnsResolver unsolicited event callback: " + e);
2419 }
2420 }
2421
2422 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
2423 @Override
2424 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2425 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2426 uid, blockedReasons));
2427 }
2428 };
2429
2430 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
2431 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
2432 setUidBlockedReasons(uid, blockedReasons);
2433 }
2434
2435 private boolean checkAnyPermissionOf(String... permissions) {
2436 for (String permission : permissions) {
2437 if (mContext.checkCallingOrSelfPermission(permission) == PERMISSION_GRANTED) {
2438 return true;
2439 }
2440 }
2441 return false;
2442 }
2443
2444 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2445 for (String permission : permissions) {
2446 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2447 return true;
2448 }
2449 }
2450 return false;
2451 }
2452
2453 private void enforceAnyPermissionOf(String... permissions) {
2454 if (!checkAnyPermissionOf(permissions)) {
2455 throw new SecurityException("Requires one of the following permissions: "
2456 + String.join(", ", permissions) + ".");
2457 }
2458 }
2459
2460 private void enforceInternetPermission() {
2461 mContext.enforceCallingOrSelfPermission(
2462 android.Manifest.permission.INTERNET,
2463 "ConnectivityService");
2464 }
2465
2466 private void enforceAccessPermission() {
2467 mContext.enforceCallingOrSelfPermission(
2468 android.Manifest.permission.ACCESS_NETWORK_STATE,
2469 "ConnectivityService");
2470 }
2471
2472 /**
2473 * Performs a strict and comprehensive check of whether a calling package is allowed to
2474 * change the state of network, as the condition differs for pre-M, M+, and
2475 * privileged/preinstalled apps. The caller is expected to have either the
2476 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2477 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2478 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2479 * permission and cannot be revoked. See http://b/23597341
2480 *
2481 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2482 * of this app will be updated to the current time.
2483 */
2484 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
2485 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2486 == PackageManager.PERMISSION_GRANTED) {
2487 return;
2488 }
2489
2490 if (callingPkg == null) {
2491 throw new SecurityException("Calling package name is null.");
2492 }
2493
2494 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2495 final int uid = mDeps.getCallingUid();
2496 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2497 callingPkg, callingAttributionTag, null /* message */);
2498
2499 if (mode == AppOpsManager.MODE_ALLOWED) {
2500 return;
2501 }
2502
2503 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2504 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2505 return;
2506 }
2507
2508 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2509 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2510 + android.Manifest.permission.WRITE_SETTINGS + ".");
2511 }
2512
2513 private void enforceSettingsPermission() {
2514 enforceAnyPermissionOf(
2515 android.Manifest.permission.NETWORK_SETTINGS,
2516 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2517 }
2518
2519 private void enforceNetworkFactoryPermission() {
2520 enforceAnyPermissionOf(
2521 android.Manifest.permission.NETWORK_FACTORY,
2522 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2523 }
2524
2525 private void enforceNetworkFactoryOrSettingsPermission() {
2526 enforceAnyPermissionOf(
2527 android.Manifest.permission.NETWORK_SETTINGS,
2528 android.Manifest.permission.NETWORK_FACTORY,
2529 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2530 }
2531
2532 private void enforceNetworkFactoryOrTestNetworksPermission() {
2533 enforceAnyPermissionOf(
2534 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2535 android.Manifest.permission.NETWORK_FACTORY,
2536 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2537 }
2538
2539 private boolean checkSettingsPermission() {
2540 return checkAnyPermissionOf(
2541 android.Manifest.permission.NETWORK_SETTINGS,
2542 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2543 }
2544
2545 private boolean checkSettingsPermission(int pid, int uid) {
2546 return PERMISSION_GRANTED == mContext.checkPermission(
2547 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2548 || PERMISSION_GRANTED == mContext.checkPermission(
2549 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
2550 }
2551
2552 private void enforceNetworkStackOrSettingsPermission() {
2553 enforceAnyPermissionOf(
2554 android.Manifest.permission.NETWORK_SETTINGS,
2555 android.Manifest.permission.NETWORK_STACK,
2556 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2557 }
2558
2559 private void enforceNetworkStackSettingsOrSetup() {
2560 enforceAnyPermissionOf(
2561 android.Manifest.permission.NETWORK_SETTINGS,
2562 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2563 android.Manifest.permission.NETWORK_STACK,
2564 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2565 }
2566
2567 private void enforceAirplaneModePermission() {
2568 enforceAnyPermissionOf(
2569 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2570 android.Manifest.permission.NETWORK_SETTINGS,
2571 android.Manifest.permission.NETWORK_SETUP_WIZARD,
2572 android.Manifest.permission.NETWORK_STACK,
2573 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2574 }
2575
2576 private void enforceOemNetworkPreferencesPermission() {
2577 mContext.enforceCallingOrSelfPermission(
2578 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2579 "ConnectivityService");
2580 }
2581
2582 private boolean checkNetworkStackPermission() {
2583 return checkAnyPermissionOf(
2584 android.Manifest.permission.NETWORK_STACK,
2585 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2586 }
2587
2588 private boolean checkNetworkStackPermission(int pid, int uid) {
2589 return checkAnyPermissionOf(pid, uid,
2590 android.Manifest.permission.NETWORK_STACK,
2591 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2592 }
2593
2594 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2595 return checkAnyPermissionOf(pid, uid,
2596 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
2597 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2598 android.Manifest.permission.NETWORK_SETTINGS);
2599 }
2600
2601 private void enforceConnectivityRestrictedNetworksPermission() {
2602 try {
2603 mContext.enforceCallingOrSelfPermission(
2604 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
2605 "ConnectivityService");
2606 return;
2607 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
2608 // TODO: Remove this fallback check after all apps have declared
2609 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2610 mContext.enforceCallingOrSelfPermission(
2611 android.Manifest.permission.CONNECTIVITY_INTERNAL,
2612 "ConnectivityService");
2613 }
2614
2615 private void enforceKeepalivePermission() {
2616 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
2617 }
2618
2619 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2620 return PERMISSION_GRANTED == mContext.checkPermission(
2621 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2622 }
2623
2624 private void sendConnectedBroadcast(NetworkInfo info) {
2625 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
2626 }
2627
2628 private void sendInetConditionBroadcast(NetworkInfo info) {
2629 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2630 }
2631
2632 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
2633 Intent intent = new Intent(bcastType);
2634 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
2635 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
2636 if (info.isFailover()) {
2637 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2638 info.setFailover(false);
2639 }
2640 if (info.getReason() != null) {
2641 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2642 }
2643 if (info.getExtraInfo() != null) {
2644 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2645 info.getExtraInfo());
2646 }
2647 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
2648 return intent;
2649 }
2650
2651 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2652 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2653 }
2654
2655 private void sendStickyBroadcast(Intent intent) {
2656 synchronized (this) {
2657 if (!mSystemReady
2658 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
2659 mInitialBroadcast = new Intent(intent);
2660 }
2661 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2662 if (VDBG) {
2663 log("sendStickyBroadcast: action=" + intent.getAction());
2664 }
2665
2666 Bundle options = null;
2667 final long ident = Binder.clearCallingIdentity();
2668 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
2669 final NetworkInfo ni = intent.getParcelableExtra(
2670 ConnectivityManager.EXTRA_NETWORK_INFO);
2671 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2672 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2673 options = opts.toBundle();
2674 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
2675 }
2676 try {
2677 mUserAllContext.sendStickyBroadcast(intent, options);
2678 } finally {
2679 Binder.restoreCallingIdentity(ident);
2680 }
2681 }
2682 }
2683
2684 /**
2685 * Called by SystemServer through ConnectivityManager when the system is ready.
2686 */
2687 @Override
2688 public void systemReady() {
2689 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
2690 throw new SecurityException("Calling Uid is not system uid.");
2691 }
2692 systemReadyInternal();
2693 }
2694
2695 /**
2696 * Called when ConnectivityService can initialize remaining components.
2697 */
2698 @VisibleForTesting
2699 public void systemReadyInternal() {
2700 // Since mApps in PermissionMonitor needs to be populated first to ensure that
2701 // listening network request which is sent by MultipathPolicyTracker won't be added
2702 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
2703 // be called after PermissionMonitor#startMonitoring().
2704 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
2705 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
2706 // to ensure the tracking will be initialized correctly.
2707 mPermissionMonitor.startMonitoring();
2708 mProxyTracker.loadGlobalProxy();
2709 registerDnsResolverUnsolicitedEventListener();
2710
2711 synchronized (this) {
2712 mSystemReady = true;
2713 if (mInitialBroadcast != null) {
2714 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
2715 mInitialBroadcast = null;
2716 }
2717 }
2718
2719 // Create network requests for always-on networks.
2720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
2721 }
2722
2723 /**
2724 * Start listening for default data network activity state changes.
2725 */
2726 @Override
2727 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
2728 mNetworkActivityTracker.registerNetworkActivityListener(l);
2729 }
2730
2731 /**
2732 * Stop listening for default data network activity state changes.
2733 */
2734 @Override
2735 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
2736 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
2737 }
2738
2739 /**
2740 * Check whether the default network radio is currently active.
2741 */
2742 @Override
2743 public boolean isDefaultNetworkActive() {
2744 return mNetworkActivityTracker.isDefaultNetworkActive();
2745 }
2746
2747 /**
2748 * Reads the network specific MTU size from resources.
2749 * and set it on it's iface.
2750 */
2751 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
2752 final String iface = newLp.getInterfaceName();
2753 final int mtu = newLp.getMtu();
2754 if (oldLp == null && mtu == 0) {
2755 // Silently ignore unset MTU value.
2756 return;
2757 }
2758 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
2759 if (VDBG) log("identical MTU - not setting");
2760 return;
2761 }
2762 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
2763 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
2764 return;
2765 }
2766
2767 // Cannot set MTU without interface name
2768 if (TextUtils.isEmpty(iface)) {
2769 loge("Setting MTU size with null iface.");
2770 return;
2771 }
2772
2773 try {
2774 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
2775 mNetd.interfaceSetMtu(iface, mtu);
2776 } catch (RemoteException | ServiceSpecificException e) {
2777 loge("exception in interfaceSetMtu()" + e);
2778 }
2779 }
2780
2781 @VisibleForTesting
2782 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
2783
2784 private void updateTcpBufferSizes(String tcpBufferSizes) {
2785 String[] values = null;
2786 if (tcpBufferSizes != null) {
2787 values = tcpBufferSizes.split(",");
2788 }
2789
2790 if (values == null || values.length != 6) {
2791 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
2792 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
2793 values = tcpBufferSizes.split(",");
2794 }
2795
2796 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
2797
2798 try {
2799 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
2800
2801 String rmemValues = String.join(" ", values[0], values[1], values[2]);
2802 String wmemValues = String.join(" ", values[3], values[4], values[5]);
2803 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
2804 mCurrentTcpBufferSizes = tcpBufferSizes;
2805 } catch (RemoteException | ServiceSpecificException e) {
2806 loge("Can't set TCP buffer sizes:" + e);
2807 }
2808 }
2809
2810 @Override
2811 public int getRestoreDefaultNetworkDelay(int networkType) {
2812 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
2813 NETWORK_RESTORE_DELAY_PROP_NAME);
2814 if(restoreDefaultNetworkDelayStr != null &&
2815 restoreDefaultNetworkDelayStr.length() != 0) {
2816 try {
2817 return Integer.parseInt(restoreDefaultNetworkDelayStr);
2818 } catch (NumberFormatException e) {
2819 }
2820 }
2821 // if the system property isn't set, use the value for the apn type
2822 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
2823
2824 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
2825 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
2826 }
2827 return ret;
2828 }
2829
2830 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
2831 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
2832 final long DIAG_TIME_MS = 5000;
2833 for (NetworkAgentInfo nai : networksSortedById()) {
2834 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
2835 // Start gathering diagnostic information.
2836 netDiags.add(new NetworkDiagnostics(
2837 nai.network,
2838 new LinkProperties(nai.linkProperties), // Must be a copy.
2839 privateDnsCfg,
2840 DIAG_TIME_MS));
2841 }
2842
2843 for (NetworkDiagnostics netDiag : netDiags) {
2844 pw.println();
2845 netDiag.waitForMeasurements();
2846 netDiag.dump(pw);
2847 }
2848 }
2849
2850 @Override
2851 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
2852 @Nullable String[] args) {
2853 if (!checkDumpPermission(mContext, TAG, writer)) return;
2854
2855 mPriorityDumper.dump(fd, writer, args);
2856 }
2857
2858 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
2859 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2860 != PackageManager.PERMISSION_GRANTED) {
2861 pw.println("Permission Denial: can't dump " + tag + " from from pid="
2862 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
2863 + " due to missing android.permission.DUMP permission");
2864 return false;
2865 } else {
2866 return true;
2867 }
2868 }
2869
2870 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
2871 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
2872
2873 if (CollectionUtils.contains(args, DIAG_ARG)) {
2874 dumpNetworkDiagnostics(pw);
2875 return;
2876 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
2877 dumpNetworks(pw);
2878 return;
2879 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
2880 dumpNetworkRequests(pw);
2881 return;
2882 }
2883
2884 pw.print("NetworkProviders for:");
2885 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
2886 pw.print(" " + npi.name);
2887 }
2888 pw.println();
2889 pw.println();
2890
2891 final NetworkAgentInfo defaultNai = getDefaultNetwork();
2892 pw.print("Active default network: ");
2893 if (defaultNai == null) {
2894 pw.println("none");
2895 } else {
2896 pw.println(defaultNai.network.getNetId());
2897 }
2898 pw.println();
2899
2900 pw.print("Current per-app default networks: ");
2901 pw.increaseIndent();
2902 dumpPerAppNetworkPreferences(pw);
2903 pw.decreaseIndent();
2904 pw.println();
2905
2906 pw.println("Current Networks:");
2907 pw.increaseIndent();
2908 dumpNetworks(pw);
2909 pw.decreaseIndent();
2910 pw.println();
2911
2912 pw.println("Status for known UIDs:");
2913 pw.increaseIndent();
2914 final int size = mUidBlockedReasons.size();
2915 for (int i = 0; i < size; i++) {
2916 // Don't crash if the array is modified while dumping in bugreports.
2917 try {
2918 final int uid = mUidBlockedReasons.keyAt(i);
2919 final int blockedReasons = mUidBlockedReasons.valueAt(i);
2920 pw.println("UID=" + uid + " blockedReasons="
2921 + Integer.toHexString(blockedReasons));
2922 } catch (ArrayIndexOutOfBoundsException e) {
2923 pw.println(" ArrayIndexOutOfBoundsException");
2924 } catch (ConcurrentModificationException e) {
2925 pw.println(" ConcurrentModificationException");
2926 }
2927 }
2928 pw.println();
2929 pw.decreaseIndent();
2930
2931 pw.println("Network Requests:");
2932 pw.increaseIndent();
2933 dumpNetworkRequests(pw);
2934 pw.decreaseIndent();
2935 pw.println();
2936
2937 mLegacyTypeTracker.dump(pw);
2938
2939 pw.println();
2940 mKeepaliveTracker.dump(pw);
2941
2942 pw.println();
2943 dumpAvoidBadWifiSettings(pw);
2944
2945 pw.println();
2946
2947 if (!CollectionUtils.contains(args, SHORT_ARG)) {
2948 pw.println();
2949 pw.println("mNetworkRequestInfoLogs (most recent first):");
2950 pw.increaseIndent();
2951 mNetworkRequestInfoLogs.reverseDump(pw);
2952 pw.decreaseIndent();
2953
2954 pw.println();
2955 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2956 pw.increaseIndent();
2957 mNetworkInfoBlockingLogs.reverseDump(pw);
2958 pw.decreaseIndent();
2959
2960 pw.println();
2961 pw.println("NetTransition WakeLock activity (most recent first):");
2962 pw.increaseIndent();
2963 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2964 pw.println("total releases: " + mTotalWakelockReleases);
2965 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2966 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2967 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2968 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2969 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2970 }
2971 mWakelockLogs.reverseDump(pw);
2972
2973 pw.println();
2974 pw.println("bandwidth update requests (by uid):");
2975 pw.increaseIndent();
2976 synchronized (mBandwidthRequests) {
2977 for (int i = 0; i < mBandwidthRequests.size(); i++) {
2978 pw.println("[" + mBandwidthRequests.keyAt(i)
2979 + "]: " + mBandwidthRequests.valueAt(i));
2980 }
2981 }
2982 pw.decreaseIndent();
2983 pw.decreaseIndent();
2984
2985 pw.println();
2986 pw.println("mOemNetworkPreferencesLogs (most recent first):");
2987 pw.increaseIndent();
2988 mOemNetworkPreferencesLogs.reverseDump(pw);
2989 pw.decreaseIndent();
2990 }
2991
2992 pw.println();
2993
2994 pw.println();
2995 pw.println("Permission Monitor:");
2996 pw.increaseIndent();
2997 mPermissionMonitor.dump(pw);
2998 pw.decreaseIndent();
2999
3000 pw.println();
3001 pw.println("Legacy network activity:");
3002 pw.increaseIndent();
3003 mNetworkActivityTracker.dump(pw);
3004 pw.decreaseIndent();
3005 }
3006
3007 private void dumpNetworks(IndentingPrintWriter pw) {
3008 for (NetworkAgentInfo nai : networksSortedById()) {
3009 pw.println(nai.toString());
3010 pw.increaseIndent();
3011 pw.println(String.format(
3012 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3013 nai.numForegroundNetworkRequests(),
3014 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3015 nai.numBackgroundNetworkRequests(),
3016 nai.numNetworkRequests()));
3017 pw.increaseIndent();
3018 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3019 pw.println(nai.requestAt(i).toString());
3020 }
3021 pw.decreaseIndent();
3022 pw.println("Inactivity Timers:");
3023 pw.increaseIndent();
3024 nai.dumpInactivityTimers(pw);
3025 pw.decreaseIndent();
3026 pw.decreaseIndent();
3027 }
3028 }
3029
3030 private void dumpPerAppNetworkPreferences(IndentingPrintWriter pw) {
3031 pw.println("Per-App Network Preference:");
3032 pw.increaseIndent();
3033 if (0 == mOemNetworkPreferences.getNetworkPreferences().size()) {
3034 pw.println("none");
3035 } else {
3036 pw.println(mOemNetworkPreferences.toString());
3037 }
3038 pw.decreaseIndent();
3039
3040 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3041 if (mDefaultRequest == defaultRequest) {
3042 continue;
3043 }
3044
3045 final boolean isActive = null != defaultRequest.getSatisfier();
3046 pw.println("Is per-app network active:");
3047 pw.increaseIndent();
3048 pw.println(isActive);
3049 if (isActive) {
3050 pw.println("Active network: " + defaultRequest.getSatisfier().network.netId);
3051 }
3052 pw.println("Tracked UIDs:");
3053 pw.increaseIndent();
3054 if (0 == defaultRequest.mRequests.size()) {
3055 pw.println("none, this should never occur.");
3056 } else {
3057 pw.println(defaultRequest.mRequests.get(0).networkCapabilities.getUidRanges());
3058 }
3059 pw.decreaseIndent();
3060 pw.decreaseIndent();
3061 }
3062 }
3063
3064 private void dumpNetworkRequests(IndentingPrintWriter pw) {
3065 for (NetworkRequestInfo nri : requestsSortedById()) {
3066 pw.println(nri.toString());
3067 }
3068 }
3069
3070 /**
3071 * Return an array of all current NetworkAgentInfos sorted by network id.
3072 */
3073 private NetworkAgentInfo[] networksSortedById() {
3074 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
3075 networks = mNetworkAgentInfos.toArray(networks);
3076 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
3077 return networks;
3078 }
3079
3080 /**
3081 * Return an array of all current NetworkRequest sorted by request id.
3082 */
3083 @VisibleForTesting
3084 NetworkRequestInfo[] requestsSortedById() {
3085 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
3086 requests = getNrisFromGlobalRequests().toArray(requests);
3087 // Sort the array based off the NRI containing the min requestId in its requests.
3088 Arrays.sort(requests,
3089 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3090 Comparator.comparingInt(req -> req.requestId)).requestId
3091 )
3092 );
3093 return requests;
3094 }
3095
3096 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
3097 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
3098 if (officialNai != null && officialNai.equals(nai)) return true;
3099 if (officialNai != null || VDBG) {
3100 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
3101 " - " + nai);
3102 }
3103 return false;
3104 }
3105
3106 // must be stateless - things change under us.
3107 private class NetworkStateTrackerHandler extends Handler {
3108 public NetworkStateTrackerHandler(Looper looper) {
3109 super(looper);
3110 }
3111
3112 private void maybeHandleNetworkAgentMessage(Message msg) {
3113 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3114 final NetworkAgentInfo nai = arg.first;
3115 if (!mNetworkAgentInfos.contains(nai)) {
3116 if (VDBG) {
3117 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
3118 }
3119 return;
3120 }
3121
3122 switch (msg.what) {
3123 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
3124 NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
3125 if (networkCapabilities.hasConnectivityManagedCapability()) {
3126 Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
3127 }
3128 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
3129 // Make sure the original object is not mutated. NetworkAgent normally
3130 // makes a copy of the capabilities when sending the message through
3131 // the Messenger, but if this ever changes, not making a defensive copy
3132 // here will give attack vectors to clients using this code path.
3133 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3134 networkCapabilities.restrictCapabilitesForTestNetwork(nai.creatorUid);
3135 }
3136 processCapabilitiesFromAgent(nai, networkCapabilities);
3137 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
3138 break;
3139 }
3140 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
3141 LinkProperties newLp = (LinkProperties) arg.second;
3142 processLinkPropertiesFromAgent(nai, newLp);
3143 handleUpdateLinkProperties(nai, newLp);
3144 break;
3145 }
3146 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
3147 NetworkInfo info = (NetworkInfo) arg.second;
3148 updateNetworkInfo(nai, info);
3149 break;
3150 }
3151 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
3152 updateNetworkScore(nai, (NetworkScore) arg.second);
3153 break;
3154 }
3155 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
3156 if (nai.everConnected) {
3157 loge("ERROR: cannot call explicitlySelected on already-connected network");
3158 // Note that if the NAI had been connected, this would affect the
3159 // score, and therefore would require re-mixing the score and performing
3160 // a rematch.
3161 }
3162 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3163 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
3164 // Mark the network as temporarily accepting partial connectivity so that it
3165 // will be validated (and possibly become default) even if it only provides
3166 // partial internet access. Note that if user connects to partial connectivity
3167 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3168 // out of wifi coverage) and if the same wifi is available again, the device
3169 // will auto connect to this wifi even though the wifi has "no internet".
3170 // TODO: Evaluate using a separate setting in IpMemoryStore.
3171 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
3172 break;
3173 }
3174 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
3175 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
3176 break;
3177 }
3178 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
3179 // TODO: prevent loops, e.g., if a network declares itself as underlying.
3180 if (!nai.supportsUnderlyingNetworks()) {
3181 Log.wtf(TAG, "Non-virtual networks cannot have underlying networks");
3182 break;
3183 }
3184
3185 final List<Network> underlying = (List<Network>) arg.second;
3186
3187 if (isLegacyLockdownNai(nai)
3188 && (underlying == null || underlying.size() != 1)) {
3189 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3190 + " must have exactly one underlying network: " + underlying);
3191 }
3192
3193 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3194 nai.declaredUnderlyingNetworks = (underlying != null)
3195 ? underlying.toArray(new Network[0]) : null;
3196
3197 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3198 if (DBG) {
3199 log(nai.toShortString() + " changed underlying networks to "
3200 + Arrays.toString(nai.declaredUnderlyingNetworks));
3201 }
3202 updateCapabilitiesForNetwork(nai);
3203 notifyIfacesChangedForNetworkStats();
3204 }
3205 break;
3206 }
3207 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3208 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3209 nai.teardownDelayMs = msg.arg1;
3210 } else {
3211 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3212 }
3213 break;
3214 }
3215 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3216 nai.setLingerDuration((int) arg.second);
3217 break;
3218 }
3219 }
3220 }
3221
3222 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
3223 switch (msg.what) {
3224 default:
3225 return false;
3226 case EVENT_PROBE_STATUS_CHANGED: {
3227 final Integer netId = (Integer) msg.obj;
3228 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3229 if (nai == null) {
3230 break;
3231 }
3232 final boolean probePrivateDnsCompleted =
3233 ((msg.arg1 & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
3234 final boolean privateDnsBroken =
3235 ((msg.arg2 & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
3236 if (probePrivateDnsCompleted) {
3237 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3238 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
3239 updateCapabilitiesForNetwork(nai);
3240 }
3241 // Only show the notification when the private DNS is broken and the
3242 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
3243 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
3244 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3245 }
3246 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
3247 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3248 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3249 // private DNS is broken, it means this network is being reevaluated.
3250 // Either probing private DNS is not necessary any more or it hasn't been
3251 // done yet. In either case, the networkCapabilities should be updated to
3252 // reflect the new status.
3253 nai.networkCapabilities.setPrivateDnsBroken(false);
3254 updateCapabilitiesForNetwork(nai);
3255 nai.networkAgentConfig.hasShownBroken = false;
3256 }
3257 break;
3258 }
3259 case EVENT_NETWORK_TESTED: {
3260 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3261
3262 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(results.mNetId);
3263 if (nai == null) break;
3264
3265 handleNetworkTested(nai, results.mTestResult,
3266 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
3267 break;
3268 }
3269 case EVENT_PROVISIONING_NOTIFICATION: {
3270 final int netId = msg.arg2;
3271 final boolean visible = toBool(msg.arg1);
3272 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
3273 // If captive portal status has changed, update capabilities or disconnect.
3274 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
3275 nai.lastCaptivePortalDetected = visible;
3276 nai.everCaptivePortalDetected |= visible;
3277 if (nai.lastCaptivePortalDetected &&
3278 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3279 == getCaptivePortalMode()) {
3280 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
3281 nai.onPreventAutomaticReconnect();
3282 teardownUnneededNetwork(nai);
3283 break;
3284 }
3285 updateCapabilitiesForNetwork(nai);
3286 }
3287 if (!visible) {
3288 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
3289 // notifications belong to the same network may be cleared unexpectedly.
3290 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3291 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
3292 } else {
3293 if (nai == null) {
3294 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3295 break;
3296 }
3297 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
3298 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
3299 (PendingIntent) msg.obj,
3300 nai.networkAgentConfig.explicitlySelected);
3301 }
3302 }
3303 break;
3304 }
3305 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
3306 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3307 if (nai == null) break;
3308
3309 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
3310 break;
3311 }
3312 case EVENT_CAPPORT_DATA_CHANGED: {
3313 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
3314 if (nai == null) break;
3315 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
3316 break;
3317 }
3318 }
3319 return true;
3320 }
3321
3322 private void handleNetworkTested(
3323 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
3324 final boolean wasPartial = nai.partialConnectivity;
3325 nai.partialConnectivity = ((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3326 final boolean partialConnectivityChanged =
3327 (wasPartial != nai.partialConnectivity);
3328
3329 final boolean valid = ((testResult & NETWORK_VALIDATION_RESULT_VALID) != 0);
3330 final boolean wasValidated = nai.lastValidated;
3331 final boolean wasDefault = isDefaultNetwork(nai);
3332
3333 if (DBG) {
3334 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3335 ? " with redirect to " + redirectUrl
3336 : "";
3337 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
3338 }
3339 if (valid != nai.lastValidated) {
3340 final int oldScore = nai.getCurrentScore();
3341 nai.lastValidated = valid;
3342 nai.everValidated |= valid;
3343 updateCapabilities(oldScore, nai, nai.networkCapabilities);
3344 if (valid) {
3345 handleFreshlyValidatedNetwork(nai);
3346 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3347 // LOST_INTERNET notifications if network becomes valid.
3348 mNotifier.clearNotification(nai.network.getNetId(),
3349 NotificationType.NO_INTERNET);
3350 mNotifier.clearNotification(nai.network.getNetId(),
3351 NotificationType.LOST_INTERNET);
3352 mNotifier.clearNotification(nai.network.getNetId(),
3353 NotificationType.PARTIAL_CONNECTIVITY);
3354 mNotifier.clearNotification(nai.network.getNetId(),
3355 NotificationType.PRIVATE_DNS_BROKEN);
3356 // If network becomes valid, the hasShownBroken should be reset for
3357 // that network so that the notification will be fired when the private
3358 // DNS is broken again.
3359 nai.networkAgentConfig.hasShownBroken = false;
3360 }
3361 } else if (partialConnectivityChanged) {
3362 updateCapabilitiesForNetwork(nai);
3363 }
3364 updateInetCondition(nai);
3365 // Let the NetworkAgent know the state of its network
3366 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
3367 nai.onValidationStatusChanged(
3368 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3369 redirectUrl);
3370
3371 // If NetworkMonitor detects partial connectivity before
3372 // EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
3373 // immediately. Re-notify partial connectivity silently if no internet
3374 // notification already there.
3375 if (!wasPartial && nai.partialConnectivity) {
3376 // Remove delayed message if there is a pending message.
3377 mHandler.removeMessages(EVENT_PROMPT_UNVALIDATED, nai.network);
3378 handlePromptUnvalidated(nai.network);
3379 }
3380
3381 if (wasValidated && !nai.lastValidated) {
3382 handleNetworkUnvalidated(nai);
3383 }
3384 }
3385
3386 private int getCaptivePortalMode() {
3387 return Settings.Global.getInt(mContext.getContentResolver(),
3388 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3389 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
3390 }
3391
3392 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3393 switch (msg.what) {
3394 default:
3395 return false;
3396 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3397 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3398 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3399 handleLingerComplete(nai);
3400 }
3401 break;
3402 }
3403 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3404 handleNetworkAgentRegistered(msg);
3405 break;
3406 }
3407 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3408 handleNetworkAgentDisconnected(msg);
3409 break;
3410 }
3411 }
3412 return true;
3413 }
3414
3415 @Override
3416 public void handleMessage(Message msg) {
3417 if (!maybeHandleNetworkMonitorMessage(msg)
3418 && !maybeHandleNetworkAgentInfoMessage(msg)) {
3419 maybeHandleNetworkAgentMessage(msg);
3420 }
3421 }
3422 }
3423
3424 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
3425 private final int mNetId;
3426 private final AutodestructReference<NetworkAgentInfo> mNai;
3427
3428 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
3429 mNetId = nai.network.getNetId();
3430 mNai = new AutodestructReference<>(nai);
3431 }
3432
3433 @Override
3434 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3435 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
3436 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
3437 }
3438
3439 @Override
3440 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
3441 // Legacy version of notifyNetworkTestedWithExtras.
3442 // Would only be called if the system has a NetworkStack module older than the
3443 // framework, which does not happen in practice.
3444 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
3445 }
3446
3447 @Override
3448 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
3449 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3450 // the same looper so messages will be processed in sequence.
3451 final Message msg = mTrackerHandler.obtainMessage(
3452 EVENT_NETWORK_TESTED,
3453 new NetworkTestedResults(
3454 mNetId, p.result, p.timestampMillis, p.redirectUrl));
3455 mTrackerHandler.sendMessage(msg);
3456
3457 // Invoke ConnectivityReport generation for this Network test event.
3458 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3459 if (nai == null) return;
3460
3461 final PersistableBundle extras = new PersistableBundle();
3462 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, p.result);
3463 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3464 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3465
3466 ConnectivityReportEvent reportEvent =
3467 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3468 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
3469 ConnectivityDiagnosticsHandler.EVENT_NETWORK_TESTED, reportEvent);
3470 mConnectivityDiagnosticsHandler.sendMessage(m);
3471 }
3472
3473 @Override
3474 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3475 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3476 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
3477 0, mNetId, PrivateDnsConfig.fromParcel(config)));
3478 }
3479
3480 @Override
3481 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3482 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3483 EVENT_PROBE_STATUS_CHANGED,
3484 probesCompleted, probesSucceeded, new Integer(mNetId)));
3485 }
3486
3487 @Override
3488 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3489 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3490 EVENT_CAPPORT_DATA_CHANGED,
3491 0, mNetId, data));
3492 }
3493
3494 @Override
3495 public void showProvisioningNotification(String action, String packageName) {
3496 final Intent intent = new Intent(action);
3497 intent.setPackage(packageName);
3498
3499 final PendingIntent pendingIntent;
3500 // Only the system server can register notifications with package "android"
3501 final long token = Binder.clearCallingIdentity();
3502 try {
3503 pendingIntent = PendingIntent.getBroadcast(
3504 mContext,
3505 0 /* requestCode */,
3506 intent,
3507 PendingIntent.FLAG_IMMUTABLE);
3508 } finally {
3509 Binder.restoreCallingIdentity(token);
3510 }
3511 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3512 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
3513 mNetId, pendingIntent));
3514 }
3515
3516 @Override
3517 public void hideProvisioningNotification() {
3518 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3519 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
3520 }
3521
3522 @Override
3523 public void notifyDataStallSuspected(DataStallReportParcelable p) {
3524 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
3525 }
3526
3527 @Override
3528 public int getInterfaceVersion() {
3529 return this.VERSION;
3530 }
3531
3532 @Override
3533 public String getInterfaceHash() {
3534 return this.HASH;
3535 }
3536 }
3537
3538 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
3539 log("Data stall detected with methods: " + p.detectionMethod);
3540
3541 final PersistableBundle extras = new PersistableBundle();
3542 int detectionMethod = 0;
3543 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
3544 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
3545 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
3546 }
3547 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
3548 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
3549 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
3550 p.tcpMetricsCollectionPeriodMillis);
3551 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
3552 }
3553
3554 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
3555 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
3556 new Pair<>(p.timestampMillis, extras));
3557
3558 // NetworkStateTrackerHandler currently doesn't take any actions based on data
3559 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
3560 // the cost of going through two handlers.
3561 mConnectivityDiagnosticsHandler.sendMessage(msg);
3562 }
3563
3564 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
3565 return (p.detectionMethod & detectionMethod) != 0;
3566 }
3567
3568 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
3569 return isPrivateDnsValidationRequired(nai.networkCapabilities);
3570 }
3571
3572 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
3573 if (nai == null) return;
3574 // If the Private DNS mode is opportunistic, reprogram the DNS servers
3575 // in order to restart a validation pass from within netd.
3576 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3577 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
3578 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3579 }
3580 }
3581
3582 private void handlePrivateDnsSettingsChanged() {
3583 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
3584
3585 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
3586 handlePerNetworkPrivateDnsConfig(nai, cfg);
3587 if (networkRequiresPrivateDnsValidation(nai)) {
3588 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3589 }
3590 }
3591 }
3592
3593 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
3594 // Private DNS only ever applies to networks that might provide
3595 // Internet access and therefore also require validation.
3596 if (!networkRequiresPrivateDnsValidation(nai)) return;
3597
3598 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
3599 // schedule DNS resolutions. If a DNS resolution is required the
3600 // result will be sent back to us.
3601 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
3602
3603 // With Private DNS bypass support, we can proceed to update the
3604 // Private DNS config immediately, even if we're in strict mode
3605 // and have not yet resolved the provider name into a set of IPs.
3606 updatePrivateDns(nai, cfg);
3607 }
3608
3609 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
3610 mDnsManager.updatePrivateDns(nai.network, newCfg);
3611 updateDnses(nai.linkProperties, null, nai.network.getNetId());
3612 }
3613
3614 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
3615 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
3616 if (nai == null) {
3617 return;
3618 }
3619 mDnsManager.updatePrivateDnsValidation(update);
3620 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3621 }
3622
3623 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
3624 int prefixLength) {
3625 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
3626 if (nai == null) return;
3627
3628 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
3629 netId, operation, prefixAddress, prefixLength));
3630
3631 IpPrefix prefix = null;
3632 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
3633 try {
3634 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
3635 prefixLength);
3636 } catch (IllegalArgumentException e) {
3637 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
3638 return;
3639 }
3640 }
3641
3642 nai.clatd.setNat64PrefixFromDns(prefix);
3643 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3644 }
3645
3646 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
3647 @Nullable final CaptivePortalData data) {
3648 nai.capportApiData = data;
3649 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
3650 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
3651 }
3652
3653 /**
3654 * Updates the inactivity state from the network requests inside the NAI.
3655 * @param nai the agent info to update
3656 * @param now the timestamp of the event causing this update
3657 * @return whether the network was inactive as a result of this update
3658 */
3659 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
3660 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
3661 // 2. If the network was inactive and there are now requests, unset inactive.
3662 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
3663 // one lingered request, set inactive.
3664 nai.updateInactivityTimer();
3665 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
3666 if (DBG) log("Unsetting inactive " + nai.toShortString());
3667 nai.unsetInactive();
3668 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
3669 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
3670 if (DBG) {
3671 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
3672 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
3673 }
3674 nai.setInactive();
3675 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
3676 return true;
3677 }
3678 return false;
3679 }
3680
3681 private void handleNetworkAgentRegistered(Message msg) {
3682 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3683 if (!mNetworkAgentInfos.contains(nai)) {
3684 return;
3685 }
3686
3687 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
3688 if (VDBG) log("NetworkAgent registered");
3689 } else {
3690 loge("Error connecting NetworkAgent");
3691 mNetworkAgentInfos.remove(nai);
3692 if (nai != null) {
3693 final boolean wasDefault = isDefaultNetwork(nai);
3694 synchronized (mNetworkForNetId) {
3695 mNetworkForNetId.remove(nai.network.getNetId());
3696 }
3697 mNetIdManager.releaseNetId(nai.network.getNetId());
3698 // Just in case.
3699 mLegacyTypeTracker.remove(nai, wasDefault);
3700 }
3701 }
3702 }
3703
3704 private void handleNetworkAgentDisconnected(Message msg) {
3705 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3706 if (mNetworkAgentInfos.contains(nai)) {
3707 disconnectAndDestroyNetwork(nai);
3708 }
3709 }
3710
3711 // Destroys a network, remove references to it from the internal state managed by
3712 // ConnectivityService, free its interfaces and clean up.
3713 // Must be called on the Handler thread.
3714 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
3715 ensureRunningOnConnectivityServiceThread();
3716 if (DBG) {
3717 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
3718 }
3719 // Clear all notifications of this network.
3720 mNotifier.clearNotification(nai.network.getNetId());
3721 // A network agent has disconnected.
3722 // TODO - if we move the logic to the network agent (have them disconnect
3723 // because they lost all their requests or because their score isn't good)
3724 // then they would disconnect organically, report their new state and then
3725 // disconnect the channel.
3726 if (nai.networkInfo.isConnected()) {
3727 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
3728 null, null);
3729 }
3730 final boolean wasDefault = isDefaultNetwork(nai);
3731 if (wasDefault) {
3732 mDefaultInetConditionPublished = 0;
3733 }
3734 notifyIfacesChangedForNetworkStats();
3735 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
3736 // by other networks that are already connected. Perhaps that can be done by
3737 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
3738 // of rematchAllNetworksAndRequests
3739 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
3740 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
3741
3742 mQosCallbackTracker.handleNetworkReleased(nai.network);
3743 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
3744 // Disable wakeup packet monitoring for each interface.
3745 wakeupModifyInterface(iface, nai.networkCapabilities, false);
3746 }
3747 nai.networkMonitor().notifyNetworkDisconnected();
3748 mNetworkAgentInfos.remove(nai);
3749 nai.clatd.update();
3750 synchronized (mNetworkForNetId) {
3751 // Remove the NetworkAgent, but don't mark the netId as
3752 // available until we've told netd to delete it below.
3753 mNetworkForNetId.remove(nai.network.getNetId());
3754 }
3755 propagateUnderlyingNetworkCapabilities(nai.network);
3756 // Remove all previously satisfied requests.
3757 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3758 final NetworkRequest request = nai.requestAt(i);
3759 final NetworkRequestInfo nri = mNetworkRequests.get(request);
3760 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
3761 if (currentNetwork != null
3762 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
3763 // uid rules for this network will be removed in destroyNativeNetwork(nai).
3764 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
3765 // rematch not to keep disconnected agents instead of setting it here ; this
3766 // will also allow removing updating the offers below.
3767 nri.setSatisfier(null, null);
3768 for (final NetworkOfferInfo noi : mNetworkOffers) {
3769 informOffer(nri, noi.offer, mNetworkRanker);
3770 }
3771
3772 if (mDefaultRequest == nri) {
3773 // TODO : make battery stats aware that since 2013 multiple interfaces may be
3774 // active at the same time. For now keep calling this with the default
3775 // network, because while incorrect this is the closest to the old (also
3776 // incorrect) behavior.
3777 mNetworkActivityTracker.updateDataActivityTracking(
3778 null /* newNetwork */, nai);
3779 ensureNetworkTransitionWakelock(nai.toShortString());
3780 }
3781 }
3782 }
3783 nai.clearInactivityState();
3784 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
3785 // Currently, deleting it breaks tests that check for the default network disconnecting.
3786 // Find out why, fix the rematch code, and delete this.
3787 mLegacyTypeTracker.remove(nai, wasDefault);
3788 rematchAllNetworksAndRequests();
3789 mLingerMonitor.noteDisconnect(nai);
3790
3791 // Immediate teardown.
3792 if (nai.teardownDelayMs == 0) {
3793 destroyNetwork(nai);
3794 return;
3795 }
3796
3797 // Delayed teardown.
3798 try {
3799 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
3800 } catch (RemoteException e) {
3801 Log.d(TAG, "Error marking network restricted during teardown: " + e);
3802 }
3803 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
3804 }
3805
3806 private void destroyNetwork(NetworkAgentInfo nai) {
3807 if (nai.created) {
3808 // Tell netd to clean up the configuration for this network
3809 // (routing rules, DNS, etc).
3810 // This may be slow as it requires a lot of netd shelling out to ip and
3811 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
3812 // after we've rematched networks with requests (which might change the default
3813 // network or service a new request from an app), so network traffic isn't interrupted
3814 // for an unnecessarily long time.
3815 destroyNativeNetwork(nai);
3816 mDnsManager.removeNetwork(nai.network);
3817 }
3818 mNetIdManager.releaseNetId(nai.network.getNetId());
3819 nai.onNetworkDestroyed();
3820 }
3821
3822 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
3823 try {
3824 // This should never fail. Specifying an already in use NetID will cause failure.
3825 final NativeNetworkConfig config;
3826 if (nai.isVPN()) {
3827 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
3828 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
3829 return false;
3830 }
3831 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
3832 INetd.PERMISSION_NONE,
3833 (nai.networkAgentConfig == null || !nai.networkAgentConfig.allowBypass),
3834 getVpnType(nai));
3835 } else {
3836 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
3837 getNetworkPermission(nai.networkCapabilities), /*secure=*/ false,
3838 VpnManager.TYPE_VPN_NONE);
3839 }
3840 mNetd.networkCreate(config);
3841 mDnsResolver.createNetworkCache(nai.network.getNetId());
3842 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
3843 nai.networkCapabilities.getTransportTypes());
3844 return true;
3845 } catch (RemoteException | ServiceSpecificException e) {
3846 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
3847 return false;
3848 }
3849 }
3850
3851 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
3852 try {
3853 mNetd.networkDestroy(nai.network.getNetId());
3854 } catch (RemoteException | ServiceSpecificException e) {
3855 loge("Exception destroying network(networkDestroy): " + e);
3856 }
3857 try {
3858 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
3859 } catch (RemoteException | ServiceSpecificException e) {
3860 loge("Exception destroying network: " + e);
3861 }
3862 }
3863
3864 // If this method proves to be too slow then we can maintain a separate
3865 // pendingIntent => NetworkRequestInfo map.
3866 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
3867 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
3868 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
3869 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
3870 if (existingPendingIntent != null &&
3871 existingPendingIntent.intentFilterEquals(pendingIntent)) {
3872 return entry.getValue();
3873 }
3874 }
3875 return null;
3876 }
3877
3878 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
3879 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
3880 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
3881 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
3882 final NetworkRequestInfo existingRequest =
3883 findExistingNetworkRequestInfo(nri.mPendingIntent);
3884 if (existingRequest != null) { // remove the existing request.
3885 if (DBG) {
3886 log("Replacing " + existingRequest.mRequests.get(0) + " with "
3887 + nri.mRequests.get(0) + " because their intents matched.");
3888 }
3889 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
3890 /* callOnUnavailable */ false);
3891 }
3892 handleRegisterNetworkRequest(nri);
3893 }
3894
3895 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
3896 handleRegisterNetworkRequests(Collections.singleton(nri));
3897 }
3898
3899 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
3900 ensureRunningOnConnectivityServiceThread();
3901 for (final NetworkRequestInfo nri : nris) {
3902 mNetworkRequestInfoLogs.log("REGISTER " + nri);
3903 for (final NetworkRequest req : nri.mRequests) {
3904 mNetworkRequests.put(req, nri);
3905 // TODO: Consider update signal strength for other types.
3906 if (req.isListen()) {
3907 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
3908 if (req.networkCapabilities.hasSignalStrength()
3909 && network.satisfiesImmutableCapabilitiesOf(req)) {
3910 updateSignalStrengthThresholds(network, "REGISTER", req);
3911 }
3912 }
3913 }
3914 }
3915 // If this NRI has a satisfier already, it is replacing an older request that
3916 // has been removed. Track it.
3917 final NetworkRequest activeRequest = nri.getActiveRequest();
3918 if (null != activeRequest) {
3919 // If there is an active request, then for sure there is a satisfier.
3920 nri.getSatisfier().addRequest(activeRequest);
3921 }
3922 }
3923
3924 rematchAllNetworksAndRequests();
3925
3926 // Requests that have not been matched to a network will not have been sent to the
3927 // providers, because the old satisfier and the new satisfier are the same (null in this
3928 // case). Send these requests to the providers.
3929 for (final NetworkRequestInfo nri : nris) {
3930 for (final NetworkOfferInfo noi : mNetworkOffers) {
3931 informOffer(nri, noi.offer, mNetworkRanker);
3932 }
3933 }
3934 }
3935
3936 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
3937 final int callingUid) {
3938 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
3939 if (nri != null) {
3940 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
3941 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
3942 handleReleaseNetworkRequest(
3943 nri.mRequests.get(0),
3944 callingUid,
3945 /* callOnUnavailable */ false);
3946 }
3947 }
3948
3949 // Determines whether the network is the best (or could become the best, if it validated), for
3950 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
3951 // on the value of reason:
3952 //
3953 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
3954 // then it should be torn down.
3955 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
3956 // then it should be lingered.
3957 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
3958 ensureRunningOnConnectivityServiceThread();
3959
3960 if (!nai.everConnected || nai.isVPN() || nai.isInactive()
3961 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
3962 return false;
3963 }
3964
3965 final int numRequests;
3966 switch (reason) {
3967 case TEARDOWN:
3968 numRequests = nai.numRequestNetworkRequests();
3969 break;
3970 case LINGER:
3971 numRequests = nai.numForegroundNetworkRequests();
3972 break;
3973 default:
3974 Log.wtf(TAG, "Invalid reason. Cannot happen.");
3975 return true;
3976 }
3977
3978 if (numRequests > 0) return false;
3979
3980 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3981 if (reason == UnneededFor.LINGER
3982 && !nri.isMultilayerRequest()
3983 && nri.mRequests.get(0).isBackgroundRequest()) {
3984 // Background requests don't affect lingering.
3985 continue;
3986 }
3987
3988 if (isNetworkPotentialSatisfier(nai, nri)) {
3989 return false;
3990 }
3991 }
3992 return true;
3993 }
3994
3995 private boolean isNetworkPotentialSatisfier(
3996 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
3997 // listen requests won't keep up a network satisfying it. If this is not a multilayer
3998 // request, return immediately. For multilayer requests, check to see if any of the
3999 // multilayer requests may have a potential satisfier.
4000 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4001 || nri.mRequests.get(0).isListenForBest())) {
4002 return false;
4003 }
4004 for (final NetworkRequest req : nri.mRequests) {
4005 // This multilayer listen request is satisfied therefore no further requests need to be
4006 // evaluated deeming this network not a potential satisfier.
4007 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
4008 return false;
4009 }
4010 // As non-multilayer listen requests have already returned, the below would only happen
4011 // for a multilayer request therefore continue to the next request if available.
4012 if (req.isListen() || req.isListenForBest()) {
4013 continue;
4014 }
4015 // If this Network is already the highest scoring Network for a request, or if
4016 // there is hope for it to become one if it validated, then it is needed.
4017 if (candidate.satisfies(req)) {
4018 // As soon as a network is found that satisfies a request, return. Specifically for
4019 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4020 // is important so as to not evaluate lower priority requests further in
4021 // nri.mRequests.
4022 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4023 ? nri.getSatisfier() : null;
4024 // Note that this catches two important cases:
4025 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4026 // is currently satisfying the request. This is desirable when
4027 // cellular ends up validating but WiFi does not.
4028 // 2. Unvalidated WiFi will not be reaped when validated cellular
4029 // is currently satisfying the request. This is desirable when
4030 // WiFi ends up validating and out scoring cellular.
4031 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
4032 }
4033 }
4034
4035 return false;
4036 }
4037
4038 private NetworkRequestInfo getNriForAppRequest(
4039 NetworkRequest request, int callingUid, String requestedOperation) {
4040 // Looking up the app passed param request in mRequests isn't possible since it may return
4041 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4042 // do the lookup since that will also find per-app default managed requests.
4043 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4044 // to avoid potential race conditions when validating a package->uid mapping when sending
4045 // the callback on the very low-chance that an application shuts down prior to the callback
4046 // being sent.
4047 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4048 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
4049
4050 if (nri != null) {
4051 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
4052 log(String.format("UID %d attempted to %s for unowned request %s",
4053 callingUid, requestedOperation, nri));
4054 return null;
4055 }
4056 }
4057
4058 return nri;
4059 }
4060
4061 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4062 final String callingMethod) {
4063 if (nri.isMultilayerRequest()) {
4064 throw new IllegalStateException(
4065 callingMethod + " does not support multilayer requests.");
4066 }
4067 }
4068
4069 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4070 ensureRunningOnConnectivityServiceThread();
4071 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4072 // single NetworkRequest and thus does not apply to multilayer requests.
4073 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4074 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
4075 return;
4076 }
4077 if (nri.isBeingSatisfied()) {
4078 return;
4079 }
4080 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4081 log("releasing " + nri.mRequests.get(0) + " (timeout)");
4082 }
4083 handleRemoveNetworkRequest(nri);
4084 callCallbackForRequest(
4085 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4086 }
4087
4088 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4089 final int callingUid,
4090 final boolean callOnUnavailable) {
4091 final NetworkRequestInfo nri =
4092 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4093 if (nri == null) {
4094 return;
4095 }
4096 if (VDBG || (DBG && request.isRequest())) {
4097 log("releasing " + request + " (release request)");
4098 }
4099 handleRemoveNetworkRequest(nri);
4100 if (callOnUnavailable) {
4101 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4102 }
4103 }
4104
4105 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
4106 ensureRunningOnConnectivityServiceThread();
4107 nri.unlinkDeathRecipient();
4108 for (final NetworkRequest req : nri.mRequests) {
4109 mNetworkRequests.remove(req);
4110 if (req.isListen()) {
4111 removeListenRequestFromNetworks(req);
4112 }
4113 }
4114 if (mDefaultNetworkRequests.remove(nri)) {
4115 // If this request was one of the defaults, then the UID rules need to be updated
4116 // WARNING : if the app(s) for which this network request is the default are doing
4117 // traffic, this will kill their connected sockets, even if an equivalent request
4118 // is going to be reinstated right away ; unconnected traffic will go on the default
4119 // until the new default is set, which will happen very soon.
4120 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4121 // remove ranges for those requests that won't have a replacement
4122 final NetworkAgentInfo satisfier = nri.getSatisfier();
4123 if (null != satisfier) {
4124 try {
4125 mNetd.networkRemoveUidRanges(satisfier.network.getNetId(),
4126 toUidRangeStableParcels(nri.getUids()));
4127 } catch (RemoteException e) {
4128 loge("Exception setting network preference default network", e);
4129 }
4130 }
4131 }
4132 nri.decrementRequestCount();
4133 mNetworkRequestInfoLogs.log("RELEASE " + nri);
4134
4135 if (null != nri.getActiveRequest()) {
4136 if (!nri.getActiveRequest().isListen()) {
4137 removeSatisfiedNetworkRequestFromNetwork(nri);
4138 } else {
4139 nri.setSatisfier(null, null);
4140 }
4141 }
4142
4143 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4144 // needed for this offer.
4145 for (final NetworkOfferInfo noi : mNetworkOffers) {
4146 for (final NetworkRequest req : nri.mRequests) {
4147 if (req.isRequest() && noi.offer.neededFor(req)) {
4148 noi.offer.onNetworkUnneeded(req);
4149 }
4150 }
4151 }
4152 }
4153
4154 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4155 for (final NetworkRequestInfo nri : nris) {
4156 if (mDefaultRequest == nri) {
4157 // Make sure we never remove the default request.
4158 continue;
4159 }
4160 handleRemoveNetworkRequest(nri);
4161 }
4162 }
4163
4164 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4165 // listens don't have a singular affected Network. Check all networks to see
4166 // if this listen request applies and remove it.
4167 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4168 nai.removeRequest(req.requestId);
4169 if (req.networkCapabilities.hasSignalStrength()
4170 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4171 updateSignalStrengthThresholds(nai, "RELEASE", req);
4172 }
4173 }
4174 }
4175
4176 /**
4177 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4178 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4179 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4180 */
4181 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4182 boolean wasKept = false;
4183 final NetworkAgentInfo nai = nri.getSatisfier();
4184 if (nai != null) {
4185 final int requestLegacyType = nri.getActiveRequest().legacyType;
4186 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4187 nai.removeRequest(nri.getActiveRequest().requestId);
4188 if (VDBG || DDBG) {
4189 log(" Removing from current network " + nai.toShortString()
4190 + ", leaving " + nai.numNetworkRequests() + " requests.");
4191 }
4192 // If there are still lingered requests on this network, don't tear it down,
4193 // but resume lingering instead.
4194 final long now = SystemClock.elapsedRealtime();
4195 if (updateInactivityState(nai, now)) {
4196 notifyNetworkLosing(nai, now);
4197 }
4198 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4199 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4200 teardownUnneededNetwork(nai);
4201 } else {
4202 wasKept = true;
4203 }
4204 nri.setSatisfier(null, null);
4205 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4206 // Went from foreground to background.
4207 updateCapabilitiesForNetwork(nai);
4208 }
4209
4210 // Maintain the illusion. When this request arrived, we might have pretended
4211 // that a network connected to serve it, even though the network was already
4212 // connected. Now that this request has gone away, we might have to pretend
4213 // that the network disconnected. LegacyTypeTracker will generate that
4214 // phantom disconnect for this type.
4215 if (requestLegacyType != TYPE_NONE) {
4216 boolean doRemove = true;
4217 if (wasKept) {
4218 // check if any of the remaining requests for this network are for the
4219 // same legacy type - if so, don't remove the nai
4220 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4221 NetworkRequest otherRequest = nai.requestAt(i);
4222 if (otherRequest.legacyType == requestLegacyType
4223 && otherRequest.isRequest()) {
4224 if (DBG) log(" still have other legacy request - leaving");
4225 doRemove = false;
4226 }
4227 }
4228 }
4229
4230 if (doRemove) {
4231 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
4232 }
4233 }
4234 }
4235 }
4236
4237 private PerUidCounter getRequestCounter(NetworkRequestInfo nri) {
4238 return checkAnyPermissionOf(
4239 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4240 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4241 }
4242
4243 @Override
4244 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
4245 enforceNetworkStackSettingsOrSetup();
4246 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
4247 encodeBool(accept), encodeBool(always), network));
4248 }
4249
4250 @Override
4251 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4252 enforceNetworkStackSettingsOrSetup();
4253 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4254 encodeBool(accept), encodeBool(always), network));
4255 }
4256
4257 @Override
4258 public void setAvoidUnvalidated(Network network) {
4259 enforceNetworkStackSettingsOrSetup();
4260 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4261 }
4262
4263 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4264 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4265 " accept=" + accept + " always=" + always);
4266
4267 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4268 if (nai == null) {
4269 // Nothing to do.
4270 return;
4271 }
4272
4273 if (nai.everValidated) {
4274 // The network validated while the dialog box was up. Take no action.
4275 return;
4276 }
4277
4278 if (!nai.networkAgentConfig.explicitlySelected) {
4279 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
4280 }
4281
4282 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4283 nai.networkAgentConfig.acceptUnvalidated = accept;
4284 // If network becomes partial connectivity and user already accepted to use this
4285 // network, we should respect the user's option and don't need to popup the
4286 // PARTIAL_CONNECTIVITY notification to user again.
4287 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4288 nai.updateScoreForNetworkAgentUpdate();
4289 rematchAllNetworksAndRequests();
4290 }
4291
4292 if (always) {
4293 nai.onSaveAcceptUnvalidated(accept);
4294 }
4295
4296 if (!accept) {
4297 // Tell the NetworkAgent to not automatically reconnect to the network.
4298 nai.onPreventAutomaticReconnect();
4299 // Teardown the network.
4300 teardownUnneededNetwork(nai);
4301 }
4302
4303 }
4304
4305 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4306 boolean always) {
4307 if (DBG) {
4308 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4309 + " always=" + always);
4310 }
4311
4312 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4313 if (nai == null) {
4314 // Nothing to do.
4315 return;
4316 }
4317
4318 if (nai.lastValidated) {
4319 // The network validated while the dialog box was up. Take no action.
4320 return;
4321 }
4322
4323 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4324 nai.networkAgentConfig.acceptPartialConnectivity = accept;
4325 }
4326
4327 // TODO: Use the current design or save the user choice into IpMemoryStore.
4328 if (always) {
4329 nai.onSaveAcceptUnvalidated(accept);
4330 }
4331
4332 if (!accept) {
4333 // Tell the NetworkAgent to not automatically reconnect to the network.
4334 nai.onPreventAutomaticReconnect();
4335 // Tear down the network.
4336 teardownUnneededNetwork(nai);
4337 } else {
4338 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4339 // result in a partial connectivity result which will be processed by
4340 // maybeHandleNetworkMonitorMessage.
4341 //
4342 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4343 // per network. Therefore, NetworkMonitor may still do https probe.
4344 nai.networkMonitor().setAcceptPartialConnectivity();
4345 }
4346 }
4347
4348 private void handleSetAvoidUnvalidated(Network network) {
4349 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4350 if (nai == null || nai.lastValidated) {
4351 // Nothing to do. The network either disconnected or revalidated.
4352 return;
4353 }
4354 if (!nai.avoidUnvalidated) {
4355 nai.avoidUnvalidated = true;
4356 nai.updateScoreForNetworkAgentUpdate();
4357 rematchAllNetworksAndRequests();
4358 }
4359 }
4360
4361 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
4362 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
4363 mHandler.sendMessageDelayed(
4364 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
4365 PROMPT_UNVALIDATED_DELAY_MS);
4366 }
4367
4368 @Override
4369 public void startCaptivePortalApp(Network network) {
4370 enforceNetworkStackOrSettingsPermission();
4371 mHandler.post(() -> {
4372 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4373 if (nai == null) return;
4374 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
4375 nai.networkMonitor().launchCaptivePortalApp();
4376 });
4377 }
4378
4379 /**
4380 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4381 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
4382 * @param network Network on which the captive portal was detected.
4383 * @param appExtras Bundle to use as intent extras for the captive portal application.
4384 * Must be treated as opaque to avoid preventing the captive portal app to
4385 * update its arguments.
4386 */
4387 @Override
4388 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
4389 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4390 "ConnectivityService");
4391
4392 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4393 appIntent.putExtras(appExtras);
4394 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4395 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
4396 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
4397
4398 final long token = Binder.clearCallingIdentity();
4399 try {
4400 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
4401 } finally {
4402 Binder.restoreCallingIdentity(token);
4403 }
4404 }
4405
4406 private class CaptivePortalImpl extends ICaptivePortal.Stub {
4407 private final Network mNetwork;
4408
4409 private CaptivePortalImpl(Network network) {
4410 mNetwork = network;
4411 }
4412
4413 @Override
4414 public void appResponse(final int response) {
4415 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
4416 enforceSettingsPermission();
4417 }
4418
4419 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4420 if (nm == null) return;
4421 nm.notifyCaptivePortalAppFinished(response);
4422 }
4423
4424 @Override
4425 public void appRequest(final int request) {
4426 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
4427 if (nm == null) return;
4428
4429 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
4430 checkNetworkStackPermission();
4431 nm.forceReevaluation(mDeps.getCallingUid());
4432 }
4433 }
4434
4435 @Nullable
4436 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
4437 // getNetworkAgentInfoForNetwork is thread-safe
4438 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4439 if (nai == null) return null;
4440
4441 // nai.networkMonitor() is thread-safe
4442 return nai.networkMonitor();
4443 }
4444 }
4445
4446 public boolean avoidBadWifi() {
4447 return mMultinetworkPolicyTracker.getAvoidBadWifi();
4448 }
4449
4450 /**
4451 * Return whether the device should maintain continuous, working connectivity by switching away
4452 * from WiFi networks having no connectivity.
4453 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
4454 */
4455 public boolean shouldAvoidBadWifi() {
4456 if (!checkNetworkStackPermission()) {
4457 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
4458 }
4459 return avoidBadWifi();
4460 }
4461
4462 private void updateAvoidBadWifi() {
4463 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4464 nai.updateScoreForNetworkAgentUpdate();
4465 }
4466 rematchAllNetworksAndRequests();
4467 }
4468
4469 // TODO: Evaluate whether this is of interest to other consumers of
4470 // MultinetworkPolicyTracker and worth moving out of here.
4471 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
4472 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
4473 if (!configRestrict) {
4474 pw.println("Bad Wi-Fi avoidance: unrestricted");
4475 return;
4476 }
4477
4478 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
4479 pw.increaseIndent();
4480 pw.println("Config restrict: " + configRestrict);
4481
4482 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
4483 String description;
4484 // Can't use a switch statement because strings are legal case labels, but null is not.
4485 if ("0".equals(value)) {
4486 description = "get stuck";
4487 } else if (value == null) {
4488 description = "prompt";
4489 } else if ("1".equals(value)) {
4490 description = "avoid";
4491 } else {
4492 description = value + " (?)";
4493 }
4494 pw.println("User setting: " + description);
4495 pw.println("Network overrides:");
4496 pw.increaseIndent();
4497 for (NetworkAgentInfo nai : networksSortedById()) {
4498 if (nai.avoidUnvalidated) {
4499 pw.println(nai.toShortString());
4500 }
4501 }
4502 pw.decreaseIndent();
4503 pw.decreaseIndent();
4504 }
4505
4506 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
4507 // unify the method.
4508 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
4509 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
4510 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
4511 return settingsComponent != null
4512 ? settingsComponent.getPackageName() : "com.android.settings";
4513 }
4514
4515 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
4516 final String action;
4517 final boolean highPriority;
4518 switch (type) {
4519 case NO_INTERNET:
4520 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
4521 // High priority because it is only displayed for explicitly selected networks.
4522 highPriority = true;
4523 break;
4524 case PRIVATE_DNS_BROKEN:
4525 action = Settings.ACTION_WIRELESS_SETTINGS;
4526 // High priority because we should let user know why there is no internet.
4527 highPriority = true;
4528 break;
4529 case LOST_INTERNET:
4530 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
4531 // High priority because it could help the user avoid unexpected data usage.
4532 highPriority = true;
4533 break;
4534 case PARTIAL_CONNECTIVITY:
4535 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
4536 // Don't bother the user with a high-priority notification if the network was not
4537 // explicitly selected by the user.
4538 highPriority = nai.networkAgentConfig.explicitlySelected;
4539 break;
4540 default:
4541 Log.wtf(TAG, "Unknown notification type " + type);
4542 return;
4543 }
4544
4545 Intent intent = new Intent(action);
4546 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
4547 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
4548 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4549 // Some OEMs have their own Settings package. Thus, need to get the current using
4550 // Settings package name instead of just use default name "com.android.settings".
4551 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
4552 intent.setClassName(settingsPkgName,
4553 settingsPkgName + ".wifi.WifiNoInternetDialog");
4554 }
4555
4556 PendingIntent pendingIntent = PendingIntent.getActivity(
4557 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
4558 0 /* requestCode */,
4559 intent,
4560 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
4561
4562 mNotifier.showNotification(
4563 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
4564 }
4565
4566 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
4567 // Don't prompt if the network is validated, and don't prompt on captive portals
4568 // because we're already prompting the user to sign in.
4569 if (nai.everValidated || nai.everCaptivePortalDetected) {
4570 return false;
4571 }
4572
4573 // If a network has partial connectivity, always prompt unless the user has already accepted
4574 // partial connectivity and selected don't ask again. This ensures that if the device
4575 // automatically connects to a network that has partial Internet access, the user will
4576 // always be able to use it, either because they've already chosen "don't ask again" or
4577 // because we have prompt them.
4578 if (nai.partialConnectivity && !nai.networkAgentConfig.acceptPartialConnectivity) {
4579 return true;
4580 }
4581
4582 // If a network has no Internet access, only prompt if the network was explicitly selected
4583 // and if the user has not already told us to use the network regardless of whether it
4584 // validated or not.
4585 if (nai.networkAgentConfig.explicitlySelected
4586 && !nai.networkAgentConfig.acceptUnvalidated) {
4587 return true;
4588 }
4589
4590 return false;
4591 }
4592
4593 private void handlePromptUnvalidated(Network network) {
4594 if (VDBG || DDBG) log("handlePromptUnvalidated " + network);
4595 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4596
4597 if (nai == null || !shouldPromptUnvalidated(nai)) {
4598 return;
4599 }
4600
4601 // Stop automatically reconnecting to this network in the future. Automatically connecting
4602 // to a network that provides no or limited connectivity is not useful, because the user
4603 // cannot use that network except through the notification shown by this method, and the
4604 // notification is only shown if the network is explicitly selected by the user.
4605 nai.onPreventAutomaticReconnect();
4606
4607 // TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
4608 // NetworkMonitor detects the network is partial connectivity. Need to change the design to
4609 // popup the notification immediately when the network is partial connectivity.
4610 if (nai.partialConnectivity) {
4611 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
4612 } else {
4613 showNetworkNotification(nai, NotificationType.NO_INTERNET);
4614 }
4615 }
4616
4617 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
4618 NetworkCapabilities nc = nai.networkCapabilities;
4619 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
4620
4621 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4622 return;
4623 }
4624
4625 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
4626 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
4627 }
4628 }
4629
4630 @Override
4631 public int getMultipathPreference(Network network) {
4632 enforceAccessPermission();
4633
4634 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4635 if (nai != null && nai.networkCapabilities
4636 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
4637 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
4638 }
4639
4640 final NetworkPolicyManager netPolicyManager =
4641 mContext.getSystemService(NetworkPolicyManager.class);
4642
4643 final long token = Binder.clearCallingIdentity();
4644 final int networkPreference;
4645 try {
4646 networkPreference = netPolicyManager.getMultipathPreference(network);
4647 } finally {
4648 Binder.restoreCallingIdentity(token);
4649 }
4650 if (networkPreference != 0) {
4651 return networkPreference;
4652 }
4653 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
4654 }
4655
4656 @Override
4657 public NetworkRequest getDefaultRequest() {
4658 return mDefaultRequest.mRequests.get(0);
4659 }
4660
4661 private class InternalHandler extends Handler {
4662 public InternalHandler(Looper looper) {
4663 super(looper);
4664 }
4665
4666 @Override
4667 public void handleMessage(Message msg) {
4668 switch (msg.what) {
4669 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
4670 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
4671 handleReleaseNetworkTransitionWakelock(msg.what);
4672 break;
4673 }
4674 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
4675 mProxyTracker.loadDeprecatedGlobalHttpProxy();
4676 break;
4677 }
4678 case EVENT_PROXY_HAS_CHANGED: {
4679 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
4680 handleApplyDefaultProxy(arg.second);
4681 break;
4682 }
4683 case EVENT_REGISTER_NETWORK_PROVIDER: {
4684 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
4685 break;
4686 }
4687 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
4688 handleUnregisterNetworkProvider((Messenger) msg.obj);
4689 break;
4690 }
4691 case EVENT_REGISTER_NETWORK_OFFER: {
4692 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
4693 break;
4694 }
4695 case EVENT_UNREGISTER_NETWORK_OFFER: {
4696 final NetworkOfferInfo offer =
4697 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
4698 if (null != offer) {
4699 handleUnregisterNetworkOffer(offer);
4700 }
4701 break;
4702 }
4703 case EVENT_REGISTER_NETWORK_AGENT: {
4704 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
4705 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
4706 handleRegisterNetworkAgent(arg.first, arg.second);
4707 break;
4708 }
4709 case EVENT_REGISTER_NETWORK_REQUEST:
4710 case EVENT_REGISTER_NETWORK_LISTENER: {
4711 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
4712 break;
4713 }
4714 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
4715 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
4716 handleRegisterNetworkRequestWithIntent(msg);
4717 break;
4718 }
4719 case EVENT_TIMEOUT_NETWORK_REQUEST: {
4720 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
4721 handleTimedOutNetworkRequest(nri);
4722 break;
4723 }
4724 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
4725 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
4726 break;
4727 }
4728 case EVENT_RELEASE_NETWORK_REQUEST: {
4729 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
4730 /* callOnUnavailable */ false);
4731 break;
4732 }
4733 case EVENT_SET_ACCEPT_UNVALIDATED: {
4734 Network network = (Network) msg.obj;
4735 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
4736 break;
4737 }
4738 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
4739 Network network = (Network) msg.obj;
4740 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
4741 toBool(msg.arg2));
4742 break;
4743 }
4744 case EVENT_SET_AVOID_UNVALIDATED: {
4745 handleSetAvoidUnvalidated((Network) msg.obj);
4746 break;
4747 }
4748 case EVENT_PROMPT_UNVALIDATED: {
4749 handlePromptUnvalidated((Network) msg.obj);
4750 break;
4751 }
4752 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
4753 handleConfigureAlwaysOnNetworks();
4754 break;
4755 }
4756 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4757 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
4758 mKeepaliveTracker.handleStartKeepalive(msg);
4759 break;
4760 }
4761 // Sent by KeepaliveTracker to process an app request on the state machine thread.
4762 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
4763 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
4764 int slot = msg.arg1;
4765 int reason = msg.arg2;
4766 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
4767 break;
4768 }
4769 case EVENT_REVALIDATE_NETWORK: {
4770 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
4771 break;
4772 }
4773 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
4774 handlePrivateDnsSettingsChanged();
4775 break;
4776 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
4777 handlePrivateDnsValidationUpdate(
4778 (PrivateDnsValidationUpdate) msg.obj);
4779 break;
4780 case EVENT_UID_BLOCKED_REASON_CHANGED:
4781 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
4782 break;
4783 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
4784 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
4785 break;
4786 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
4787 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
4788 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
4789 handleSetOemNetworkPreference(arg.first, arg.second);
4790 break;
4791 }
4792 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
4793 final Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener> arg =
4794 (Pair<ProfileNetworkPreferences.Preference, IOnCompleteListener>)
4795 msg.obj;
4796 handleSetProfileNetworkPreference(arg.first, arg.second);
4797 break;
4798 }
4799 case EVENT_REPORT_NETWORK_ACTIVITY:
4800 mNetworkActivityTracker.handleReportNetworkActivity();
4801 break;
4802 }
4803 }
4804 }
4805
4806 @Override
4807 @Deprecated
4808 public int getLastTetherError(String iface) {
4809 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4810 Context.TETHERING_SERVICE);
4811 return tm.getLastTetherError(iface);
4812 }
4813
4814 @Override
4815 @Deprecated
4816 public String[] getTetherableIfaces() {
4817 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4818 Context.TETHERING_SERVICE);
4819 return tm.getTetherableIfaces();
4820 }
4821
4822 @Override
4823 @Deprecated
4824 public String[] getTetheredIfaces() {
4825 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4826 Context.TETHERING_SERVICE);
4827 return tm.getTetheredIfaces();
4828 }
4829
4830
4831 @Override
4832 @Deprecated
4833 public String[] getTetheringErroredIfaces() {
4834 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4835 Context.TETHERING_SERVICE);
4836
4837 return tm.getTetheringErroredIfaces();
4838 }
4839
4840 @Override
4841 @Deprecated
4842 public String[] getTetherableUsbRegexs() {
4843 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4844 Context.TETHERING_SERVICE);
4845
4846 return tm.getTetherableUsbRegexs();
4847 }
4848
4849 @Override
4850 @Deprecated
4851 public String[] getTetherableWifiRegexs() {
4852 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
4853 Context.TETHERING_SERVICE);
4854 return tm.getTetherableWifiRegexs();
4855 }
4856
4857 // Called when we lose the default network and have no replacement yet.
4858 // This will automatically be cleared after X seconds or a new default network
4859 // becomes CONNECTED, whichever happens first. The timer is started by the
4860 // first caller and not restarted by subsequent callers.
4861 private void ensureNetworkTransitionWakelock(String forWhom) {
4862 synchronized (this) {
4863 if (mNetTransitionWakeLock.isHeld()) {
4864 return;
4865 }
4866 mNetTransitionWakeLock.acquire();
4867 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
4868 mTotalWakelockAcquisitions++;
4869 }
4870 mWakelockLogs.log("ACQUIRE for " + forWhom);
4871 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4872 final int lockTimeout = mResources.get().getInteger(
4873 R.integer.config_networkTransitionTimeout);
4874 mHandler.sendMessageDelayed(msg, lockTimeout);
4875 }
4876
4877 // Called when we gain a new default network to release the network transition wakelock in a
4878 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
4879 // message is cancelled.
4880 private void scheduleReleaseNetworkTransitionWakelock() {
4881 synchronized (this) {
4882 if (!mNetTransitionWakeLock.isHeld()) {
4883 return; // expiry message released the lock first.
4884 }
4885 }
4886 // Cancel self timeout on wakelock hold.
4887 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
4888 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
4889 mHandler.sendMessageDelayed(msg, 1000);
4890 }
4891
4892 // Called when either message of ensureNetworkTransitionWakelock or
4893 // scheduleReleaseNetworkTransitionWakelock is processed.
4894 private void handleReleaseNetworkTransitionWakelock(int eventId) {
4895 String event = eventName(eventId);
4896 synchronized (this) {
4897 if (!mNetTransitionWakeLock.isHeld()) {
4898 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
4899 Log.w(TAG, "expected Net Transition WakeLock to be held");
4900 return;
4901 }
4902 mNetTransitionWakeLock.release();
4903 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4904 mTotalWakelockDurationMs += lockDuration;
4905 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
4906 mTotalWakelockReleases++;
4907 }
4908 mWakelockLogs.log(String.format("RELEASE (%s)", event));
4909 }
4910
4911 // 100 percent is full good, 0 is full bad.
4912 @Override
4913 public void reportInetCondition(int networkType, int percentage) {
4914 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
4915 if (nai == null) return;
4916 reportNetworkConnectivity(nai.network, percentage > 50);
4917 }
4918
4919 @Override
4920 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
4921 enforceAccessPermission();
4922 enforceInternetPermission();
4923 final int uid = mDeps.getCallingUid();
4924 final int connectivityInfo = encodeBool(hasConnectivity);
4925
4926 // Handle ConnectivityDiagnostics event before attempting to revalidate the network. This
4927 // forces an ordering of ConnectivityDiagnostics events in the case where hasConnectivity
4928 // does not match the known connectivity of the network - this causes NetworkMonitor to
4929 // revalidate the network and generate a ConnectivityDiagnostics ConnectivityReport event.
4930 final NetworkAgentInfo nai;
4931 if (network == null) {
4932 nai = getDefaultNetwork();
4933 } else {
4934 nai = getNetworkAgentInfoForNetwork(network);
4935 }
4936 if (nai != null) {
4937 mConnectivityDiagnosticsHandler.sendMessage(
4938 mConnectivityDiagnosticsHandler.obtainMessage(
4939 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
4940 connectivityInfo, 0, nai));
4941 }
4942
4943 mHandler.sendMessage(
4944 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
4945 }
4946
4947 private void handleReportNetworkConnectivity(
4948 Network network, int uid, boolean hasConnectivity) {
4949 final NetworkAgentInfo nai;
4950 if (network == null) {
4951 nai = getDefaultNetwork();
4952 } else {
4953 nai = getNetworkAgentInfoForNetwork(network);
4954 }
4955 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
4956 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
4957 return;
4958 }
4959 // Revalidate if the app report does not match our current validated state.
4960 if (hasConnectivity == nai.lastValidated) {
4961 return;
4962 }
4963 if (DBG) {
4964 int netid = nai.network.getNetId();
4965 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
4966 }
4967 // Validating a network that has not yet connected could result in a call to
4968 // rematchNetworkAndRequests() which is not meant to work on such networks.
4969 if (!nai.everConnected) {
4970 return;
4971 }
4972 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
4973 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
4974 return;
4975 }
4976 nai.networkMonitor().forceReevaluation(uid);
4977 }
4978
4979 // TODO: call into netd.
4980 private boolean queryUserAccess(int uid, Network network) {
4981 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4982 if (nai == null) return false;
4983
4984 // Any UID can use its default network.
4985 if (nai == getDefaultNetworkForUid(uid)) return true;
4986
4987 // Privileged apps can use any network.
4988 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
4989 return true;
4990 }
4991
4992 // An unprivileged UID can use a VPN iff the VPN applies to it.
4993 if (nai.isVPN()) {
4994 return nai.networkCapabilities.appliesToUid(uid);
4995 }
4996
4997 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
4998 // sockets, i.e., if it is the owner.
4999 final NetworkAgentInfo vpn = getVpnForUid(uid);
5000 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5001 && uid != vpn.networkCapabilities.getOwnerUid()) {
5002 return false;
5003 }
5004
5005 // The UID's permission must be at least sufficient for the network. Since the restricted
5006 // permission was already checked above, that just leaves background networks.
5007 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5008 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5009 }
5010
5011 // Unrestricted network. Anyone gets to use it.
5012 return true;
5013 }
5014
5015 /**
5016 * Returns information about the proxy a certain network is using. If given a null network, it
5017 * it will return the proxy for the bound network for the caller app or the default proxy if
5018 * none.
5019 *
5020 * @param network the network we want to get the proxy information for.
5021 * @return Proxy information if a network has a proxy configured, or otherwise null.
5022 */
5023 @Override
5024 public ProxyInfo getProxyForNetwork(Network network) {
5025 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
5026 if (globalProxy != null) return globalProxy;
5027 if (network == null) {
5028 // Get the network associated with the calling UID.
5029 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
5030 true);
5031 if (activeNetwork == null) {
5032 return null;
5033 }
5034 return getLinkPropertiesProxyInfo(activeNetwork);
5035 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
5036 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5037 // caller may not have.
5038 return getLinkPropertiesProxyInfo(network);
5039 }
5040 // No proxy info available if the calling UID does not have network access.
5041 return null;
5042 }
5043
5044
5045 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
5046 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5047 if (nai == null) return null;
5048 synchronized (nai) {
5049 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5050 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
5051 }
5052 }
5053
5054 @Override
5055 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
5056 PermissionUtils.enforceNetworkStackPermission(mContext);
5057 mProxyTracker.setGlobalProxy(proxyProperties);
5058 }
5059
5060 @Override
5061 @Nullable
5062 public ProxyInfo getGlobalProxy() {
5063 return mProxyTracker.getGlobalProxy();
5064 }
5065
5066 private void handleApplyDefaultProxy(ProxyInfo proxy) {
5067 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
5068 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
5069 proxy = null;
5070 }
5071 mProxyTracker.setDefaultProxy(proxy);
5072 }
5073
5074 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5075 // when any network changes proxy.
5076 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5077 // multi-network world where an app might be bound to a non-default network.
5078 private void updateProxy(LinkProperties newLp, LinkProperties oldLp) {
5079 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
5080 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5081
5082 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
5083 mProxyTracker.sendProxyBroadcast();
5084 }
5085 }
5086
5087 private static class SettingsObserver extends ContentObserver {
5088 final private HashMap<Uri, Integer> mUriEventMap;
5089 final private Context mContext;
5090 final private Handler mHandler;
5091
5092 SettingsObserver(Context context, Handler handler) {
5093 super(null);
5094 mUriEventMap = new HashMap<>();
5095 mContext = context;
5096 mHandler = handler;
5097 }
5098
5099 void observe(Uri uri, int what) {
5100 mUriEventMap.put(uri, what);
5101 final ContentResolver resolver = mContext.getContentResolver();
5102 resolver.registerContentObserver(uri, false, this);
5103 }
5104
5105 @Override
5106 public void onChange(boolean selfChange) {
5107 Log.wtf(TAG, "Should never be reached.");
5108 }
5109
5110 @Override
5111 public void onChange(boolean selfChange, Uri uri) {
5112 final Integer what = mUriEventMap.get(uri);
5113 if (what != null) {
5114 mHandler.obtainMessage(what).sendToTarget();
5115 } else {
5116 loge("No matching event to send for URI=" + uri);
5117 }
5118 }
5119 }
5120
5121 private static void log(String s) {
5122 Log.d(TAG, s);
5123 }
5124
5125 private static void logw(String s) {
5126 Log.w(TAG, s);
5127 }
5128
5129 private static void logwtf(String s) {
5130 Log.wtf(TAG, s);
5131 }
5132
5133 private static void logwtf(String s, Throwable t) {
5134 Log.wtf(TAG, s, t);
5135 }
5136
5137 private static void loge(String s) {
5138 Log.e(TAG, s);
5139 }
5140
5141 private static void loge(String s, Throwable t) {
5142 Log.e(TAG, s, t);
5143 }
5144
5145 /**
5146 * Return the information of all ongoing VPNs.
5147 *
5148 * <p>This method is used to update NetworkStatsService.
5149 *
5150 * <p>Must be called on the handler thread.
5151 */
5152 private UnderlyingNetworkInfo[] getAllVpnInfo() {
5153 ensureRunningOnConnectivityServiceThread();
5154 if (mLockdownEnabled) {
5155 return new UnderlyingNetworkInfo[0];
5156 }
5157 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
5158 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5159 UnderlyingNetworkInfo info = createVpnInfo(nai);
5160 if (info != null) {
5161 infoList.add(info);
5162 }
5163 }
5164 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
5165 }
5166
5167 /**
5168 * @return VPN information for accounting, or null if we can't retrieve all required
5169 * information, e.g underlying ifaces.
5170 */
5171 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
5172 if (!nai.isVPN()) return null;
5173
5174 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
5175 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5176 // the underlyingNetworks list.
5177 if (underlyingNetworks == null) {
5178 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5179 nai.networkCapabilities.getOwnerUid());
5180 if (defaultNai != null) {
5181 underlyingNetworks = new Network[] { defaultNai.network };
5182 }
5183 }
5184
5185 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
5186
5187 List<String> interfaces = new ArrayList<>();
5188 for (Network network : underlyingNetworks) {
5189 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5190 if (underlyingNai == null) continue;
5191 LinkProperties lp = underlyingNai.linkProperties;
5192 for (String iface : lp.getAllInterfaceNames()) {
5193 if (!TextUtils.isEmpty(iface)) {
5194 interfaces.add(iface);
5195 }
5196 }
5197 }
5198
5199 if (interfaces.isEmpty()) return null;
5200
5201 // Must be non-null or NetworkStatsService will crash.
5202 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5203 // tun or ipsec interface is created.
5204 // TODO: Remove this check.
5205 if (nai.linkProperties.getInterfaceName() == null) return null;
5206
5207 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5208 nai.linkProperties.getInterfaceName(), interfaces);
5209 }
5210
5211 // TODO This needs to be the default network that applies to the NAI.
5212 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5213 Network[] underlyingNetworks) {
5214 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
5215 if (underlyingNetworks == null && defaultNetwork != null) {
5216 // null underlying networks means to track the default.
5217 underlyingNetworks = new Network[] { defaultNetwork };
5218 }
5219 return underlyingNetworks;
5220 }
5221
5222 // Returns true iff |network| is an underlying network of |nai|.
5223 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5224 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5225 // (e.g., 2 levels of underlying networks), or via loop detection, or....
5226 if (!nai.supportsUnderlyingNetworks()) return false;
5227 final Network[] underlying = underlyingNetworksOrDefault(
5228 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
5229 return CollectionUtils.contains(underlying, network);
5230 }
5231
5232 /**
5233 * Recompute the capabilities for any networks that had a specific network as underlying.
5234 *
5235 * When underlying networks change, such networks may have to update capabilities to reflect
5236 * things like the metered bit, their transports, and so on. The capabilities are calculated
5237 * immediately. This method runs on the ConnectivityService thread.
5238 */
5239 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
5240 ensureRunningOnConnectivityServiceThread();
5241 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
5242 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
5243 updateCapabilitiesForNetwork(nai);
5244 }
5245 }
5246 }
5247
5248 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5249 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5250 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5251 // a VPN is not up.
5252 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5253 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5254 for (UidRange range : blockedUidRanges) {
5255 if (range.contains(uid)) return true;
5256 }
5257 return false;
5258 }
5259
5260 @Override
5261 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5262 enforceNetworkStackOrSettingsPermission();
5263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5264 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5265 }
5266
5267 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5268 if (DBG) {
5269 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5270 + Arrays.toString(ranges));
5271 }
5272 // Cannot use a Set since the list of UID ranges might contain duplicates.
5273 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5274 for (int i = 0; i < ranges.length; i++) {
5275 if (requireVpn) {
5276 newVpnBlockedUidRanges.add(ranges[i]);
5277 } else {
5278 newVpnBlockedUidRanges.remove(ranges[i]);
5279 }
5280 }
5281
5282 try {
5283 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5284 } catch (RemoteException | ServiceSpecificException e) {
5285 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5286 + Arrays.toString(ranges) + "): netd command failed: " + e);
5287 }
5288
5289 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5290 final boolean curMetered = nai.networkCapabilities.isMetered();
5291 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5292 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
5293 }
5294
5295 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5296 }
5297
5298 @Override
5299 public void setLegacyLockdownVpnEnabled(boolean enabled) {
5300 enforceNetworkStackOrSettingsPermission();
5301 mHandler.post(() -> mLockdownEnabled = enabled);
5302 }
5303
5304 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5305 return mLockdownEnabled
5306 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5307 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
5308 }
5309
5310 private NetworkAgentInfo getLegacyLockdownNai() {
5311 if (!mLockdownEnabled) {
5312 return null;
5313 }
5314 // The legacy lockdown VPN always only applies to userId 0.
5315 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5316 if (nai == null || !isLegacyLockdownNai(nai)) return null;
5317
5318 // The legacy lockdown VPN must always have exactly one underlying network.
5319 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5320 // a local variable. There is no need to make a copy because its contents cannot change.
5321 final Network[] underlying = nai.declaredUnderlyingNetworks;
5322 if (underlying == null || underlying.length != 1) {
5323 return null;
5324 }
5325
5326 // The legacy lockdown VPN always uses the default network.
5327 // If the VPN's underlying network is no longer the current default network, it means that
5328 // the default network has just switched, and the VPN is about to disconnect.
5329 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5330 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
5331 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5332 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
5333 return null;
5334 }
5335
5336 return nai;
5337 };
5338
5339 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5340 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5341 // just a DetailedState object.
5342 private DetailedState getLegacyLockdownState(DetailedState origState) {
5343 if (origState != DetailedState.CONNECTED) {
5344 return origState;
5345 }
5346 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5347 ? DetailedState.CONNECTING
5348 : DetailedState.CONNECTED;
5349 }
5350
5351 private void filterForLegacyLockdown(NetworkInfo ni) {
5352 if (!mLockdownEnabled || !ni.isConnected()) return;
5353 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5354 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5355 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5356 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5357 // network, this time with a state of CONNECTED.
5358 //
5359 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5360 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5361 // is not too far off the truth, since an always-on VPN, when not connected, is always
5362 // trying to reconnect.
5363 if (getLegacyLockdownNai() == null) {
5364 ni.setDetailedState(DetailedState.CONNECTING, "", null);
5365 }
5366 }
5367
5368 @Override
5369 public void setProvisioningNotificationVisible(boolean visible, int networkType,
5370 String action) {
5371 enforceSettingsPermission();
5372 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
5373 return;
5374 }
5375 final long ident = Binder.clearCallingIdentity();
5376 try {
5377 // Concatenate the range of types onto the range of NetIDs.
5378 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
5379 mNotifier.setProvNotificationVisible(visible, id, action);
5380 } finally {
5381 Binder.restoreCallingIdentity(ident);
5382 }
5383 }
5384
5385 @Override
5386 public void setAirplaneMode(boolean enable) {
5387 enforceAirplaneModePermission();
5388 final long ident = Binder.clearCallingIdentity();
5389 try {
5390 final ContentResolver cr = mContext.getContentResolver();
5391 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
5392 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
5393 intent.putExtra("state", enable);
5394 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
5395 } finally {
5396 Binder.restoreCallingIdentity(ident);
5397 }
5398 }
5399
5400 private void onUserAdded(@NonNull final UserHandle user) {
5401 mPermissionMonitor.onUserAdded(user);
5402 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5403 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5404 }
5405 }
5406
5407 private void onUserRemoved(@NonNull final UserHandle user) {
5408 mPermissionMonitor.onUserRemoved(user);
5409 // If there was a network preference for this user, remove it.
5410 handleSetProfileNetworkPreference(new ProfileNetworkPreferences.Preference(user, null),
5411 null /* listener */);
5412 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
5413 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5414 }
5415 }
5416
5417 private void onPackageChanged(@NonNull final String packageName) {
5418 // This is necessary in case a package is added or removed, but also when it's replaced to
5419 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
5420 // as one in the preferences, then it should follow the same routing as that other package,
5421 // which means updating the rules is never to be needed in this case (whether it joins or
5422 // leaves a UID with a preference).
5423 if (isMappedInOemNetworkPreference(packageName)) {
5424 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
5425 }
5426 }
5427
5428 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
5429 @Override
5430 public void onReceive(Context context, Intent intent) {
5431 ensureRunningOnConnectivityServiceThread();
5432 final String action = intent.getAction();
5433 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
5434
5435 // User should be filled for below intents, check the existence.
5436 if (user == null) {
5437 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
5438 return;
5439 }
5440
5441 if (Intent.ACTION_USER_ADDED.equals(action)) {
5442 onUserAdded(user);
5443 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
5444 onUserRemoved(user);
5445 } else {
5446 Log.wtf(TAG, "received unexpected intent: " + action);
5447 }
5448 }
5449 };
5450
5451 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
5452 @Override
5453 public void onReceive(Context context, Intent intent) {
5454 ensureRunningOnConnectivityServiceThread();
5455 switch (intent.getAction()) {
5456 case Intent.ACTION_PACKAGE_ADDED:
5457 case Intent.ACTION_PACKAGE_REMOVED:
5458 case Intent.ACTION_PACKAGE_REPLACED:
5459 onPackageChanged(intent.getData().getSchemeSpecificPart());
5460 break;
5461 default:
5462 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
5463 }
5464 }
5465 };
5466
5467 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
5468 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
5469
5470 private static class NetworkProviderInfo {
5471 public final String name;
5472 public final Messenger messenger;
5473 private final IBinder.DeathRecipient mDeathRecipient;
5474 public final int providerId;
5475
5476 NetworkProviderInfo(String name, Messenger messenger, int providerId,
5477 @NonNull IBinder.DeathRecipient deathRecipient) {
5478 this.name = name;
5479 this.messenger = messenger;
5480 this.providerId = providerId;
5481 mDeathRecipient = deathRecipient;
5482
5483 if (mDeathRecipient == null) {
5484 throw new AssertionError("Must pass a deathRecipient");
5485 }
5486 }
5487
5488 void connect(Context context, Handler handler) {
5489 try {
5490 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
5491 } catch (RemoteException e) {
5492 mDeathRecipient.binderDied();
5493 }
5494 }
5495 }
5496
5497 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
5498 for (int i = 0; i < requests.size(); i++) {
5499 ensureNetworkRequestHasType(requests.get(i));
5500 }
5501 }
5502
5503 private void ensureNetworkRequestHasType(NetworkRequest request) {
5504 if (request.type == NetworkRequest.Type.NONE) {
5505 throw new IllegalArgumentException(
5506 "All NetworkRequests in ConnectivityService must have a type");
5507 }
5508 }
5509
5510 /**
5511 * Tracks info about the requester.
5512 * Also used to notice when the calling process dies so as to self-expire
5513 */
5514 @VisibleForTesting
5515 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
5516 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
5517 // single NetworkRequest in mRequests.
5518 final List<NetworkRequest> mRequests;
5519
5520 // mSatisfier and mActiveRequest rely on one another therefore set them together.
5521 void setSatisfier(
5522 @Nullable final NetworkAgentInfo satisfier,
5523 @Nullable final NetworkRequest activeRequest) {
5524 mSatisfier = satisfier;
5525 mActiveRequest = activeRequest;
5526 }
5527
5528 // The network currently satisfying this NRI. Only one request in an NRI can have a
5529 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
5530 @Nullable
5531 private NetworkAgentInfo mSatisfier;
5532 NetworkAgentInfo getSatisfier() {
5533 return mSatisfier;
5534 }
5535
5536 // The request in mRequests assigned to a network agent. This is null if none of the
5537 // requests in mRequests can be satisfied. This member has the constraint of only being
5538 // accessible on the handler thread.
5539 @Nullable
5540 private NetworkRequest mActiveRequest;
5541 NetworkRequest getActiveRequest() {
5542 return mActiveRequest;
5543 }
5544
5545 final PendingIntent mPendingIntent;
5546 boolean mPendingIntentSent;
5547 @Nullable
5548 final Messenger mMessenger;
5549
5550 // Information about the caller that caused this object to be created.
5551 @Nullable
5552 private final IBinder mBinder;
5553 final int mPid;
5554 final int mUid;
5555 final @NetworkCallback.Flag int mCallbackFlags;
5556 @Nullable
5557 final String mCallingAttributionTag;
5558
5559 // Counter keeping track of this NRI.
5560 final PerUidCounter mPerUidCounter;
5561
5562 // Effective UID of this request. This is different from mUid when a privileged process
5563 // files a request on behalf of another UID. This UID is used to determine blocked status,
5564 // UID matching, and so on. mUid above is used for permission checks and to enforce the
5565 // maximum limit of registered callbacks per UID.
5566 final int mAsUid;
5567
5568 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
5569 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
5570 // maintained for keying off of. This is only a concern when the original nri
5571 // mNetworkRequests changes which happens currently for apps that register callbacks to
5572 // track the default network. In those cases, the nri is updated to have mNetworkRequests
5573 // that match the per-app default nri that currently tracks the calling app's uid so that
5574 // callbacks are fired at the appropriate time. When the callbacks fire,
5575 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
5576 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
5577 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
5578 @NonNull
5579 private final NetworkRequest mNetworkRequestForCallback;
5580 NetworkRequest getNetworkRequestForCallback() {
5581 return mNetworkRequestForCallback;
5582 }
5583
5584 /**
5585 * Get the list of UIDs this nri applies to.
5586 */
5587 @NonNull
5588 private Set<UidRange> getUids() {
5589 // networkCapabilities.getUids() returns a defensive copy.
5590 // multilayer requests will all have the same uids so return the first one.
5591 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
5592 return (null == uids) ? new ArraySet<>() : uids;
5593 }
5594
5595 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
5596 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
5597 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag);
5598 }
5599
5600 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5601 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
5602 @Nullable String callingAttributionTag) {
5603 ensureAllNetworkRequestsHaveType(r);
5604 mRequests = initializeRequests(r);
5605 mNetworkRequestForCallback = requestForCallback;
5606 mPendingIntent = pi;
5607 mMessenger = null;
5608 mBinder = null;
5609 mPid = getCallingPid();
5610 mUid = mDeps.getCallingUid();
5611 mAsUid = asUid;
5612 mPerUidCounter = getRequestCounter(this);
5613 mPerUidCounter.incrementCountOrThrow(mUid);
5614 /**
5615 * Location sensitive data not included in pending intent. Only included in
5616 * {@link NetworkCallback}.
5617 */
5618 mCallbackFlags = NetworkCallback.FLAG_NONE;
5619 mCallingAttributionTag = callingAttributionTag;
5620 }
5621
5622 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
5623 @Nullable final IBinder binder,
5624 @NetworkCallback.Flag int callbackFlags,
5625 @Nullable String callingAttributionTag) {
5626 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
5627 callingAttributionTag);
5628 }
5629
5630 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
5631 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
5632 @Nullable final IBinder binder,
5633 @NetworkCallback.Flag int callbackFlags,
5634 @Nullable String callingAttributionTag) {
5635 super();
5636 ensureAllNetworkRequestsHaveType(r);
5637 mRequests = initializeRequests(r);
5638 mNetworkRequestForCallback = requestForCallback;
5639 mMessenger = m;
5640 mBinder = binder;
5641 mPid = getCallingPid();
5642 mUid = mDeps.getCallingUid();
5643 mAsUid = asUid;
5644 mPendingIntent = null;
5645 mPerUidCounter = getRequestCounter(this);
5646 mPerUidCounter.incrementCountOrThrow(mUid);
5647 mCallbackFlags = callbackFlags;
5648 mCallingAttributionTag = callingAttributionTag;
5649 linkDeathRecipient();
5650 }
5651
5652 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
5653 @NonNull final List<NetworkRequest> r) {
5654 super();
5655 ensureAllNetworkRequestsHaveType(r);
5656 mRequests = initializeRequests(r);
5657 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
5658 final NetworkAgentInfo satisfier = nri.getSatisfier();
5659 if (null != satisfier) {
5660 // If the old NRI was satisfied by an NAI, then it may have had an active request.
5661 // The active request is necessary to figure out what callbacks to send, in
5662 // particular then a network updates its capabilities.
5663 // As this code creates a new NRI with a new set of requests, figure out which of
5664 // the list of requests should be the active request. It is always the first
5665 // request of the list that can be satisfied by the satisfier since the order of
5666 // requests is a priority order.
5667 // Note even in the presence of a satisfier there may not be an active request,
5668 // when the satisfier is the no-service network.
5669 NetworkRequest activeRequest = null;
5670 for (final NetworkRequest candidate : r) {
5671 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
5672 activeRequest = candidate;
5673 break;
5674 }
5675 }
5676 setSatisfier(satisfier, activeRequest);
5677 }
5678 mMessenger = nri.mMessenger;
5679 mBinder = nri.mBinder;
5680 mPid = nri.mPid;
5681 mUid = nri.mUid;
5682 mAsUid = nri.mAsUid;
5683 mPendingIntent = nri.mPendingIntent;
5684 mPerUidCounter = getRequestCounter(this);
5685 mPerUidCounter.incrementCountOrThrow(mUid);
5686 mCallbackFlags = nri.mCallbackFlags;
5687 mCallingAttributionTag = nri.mCallingAttributionTag;
5688 linkDeathRecipient();
5689 }
5690
5691 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
5692 this(asUid, Collections.singletonList(r));
5693 }
5694
5695 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r) {
5696 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */);
5697 }
5698
5699 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
5700 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
5701 // false.
5702 boolean isBeingSatisfied() {
5703 return (null != mSatisfier && null != mActiveRequest);
5704 }
5705
5706 boolean isMultilayerRequest() {
5707 return mRequests.size() > 1;
5708 }
5709
5710 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
5711 // Creating a defensive copy to prevent the sender from modifying the list being
5712 // reflected in the return value of this method.
5713 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
5714 return Collections.unmodifiableList(tempRequests);
5715 }
5716
5717 void decrementRequestCount() {
5718 mPerUidCounter.decrementCount(mUid);
5719 }
5720
5721 void linkDeathRecipient() {
5722 if (null != mBinder) {
5723 try {
5724 mBinder.linkToDeath(this, 0);
5725 } catch (RemoteException e) {
5726 binderDied();
5727 }
5728 }
5729 }
5730
5731 void unlinkDeathRecipient() {
5732 if (null != mBinder) {
5733 mBinder.unlinkToDeath(this, 0);
5734 }
5735 }
5736
5737 @Override
5738 public void binderDied() {
5739 log("ConnectivityService NetworkRequestInfo binderDied(" +
5740 mRequests + ", " + mBinder + ")");
5741 releaseNetworkRequests(mRequests);
5742 }
5743
5744 @Override
5745 public String toString() {
5746 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
5747 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
5748 + (mActiveRequest == null ? null : mActiveRequest.requestId)
5749 + " callbackRequest: "
5750 + mNetworkRequestForCallback.requestId
5751 + " " + mRequests
5752 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
5753 + " callback flags: " + mCallbackFlags;
5754 }
5755 }
5756
5757 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
5758 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
5759 if (badCapability != null) {
5760 throw new IllegalArgumentException("Cannot request network with " + badCapability);
5761 }
5762 }
5763
5764 // This checks that the passed capabilities either do not request a
5765 // specific SSID/SignalStrength, or the calling app has permission to do so.
5766 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
5767 int callerPid, int callerUid, String callerPackageName) {
5768 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
5769 throw new SecurityException("Insufficient permissions to request a specific SSID");
5770 }
5771
5772 if (nc.hasSignalStrength()
5773 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
5774 throw new SecurityException(
5775 "Insufficient permissions to request a specific signal strength");
5776 }
5777 mAppOpsManager.checkPackage(callerUid, callerPackageName);
5778
5779 if (!nc.getSubscriptionIds().isEmpty()) {
5780 enforceNetworkFactoryPermission();
5781 }
5782 }
5783
5784 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
5785 final SortedSet<Integer> thresholds = new TreeSet<>();
5786 synchronized (nai) {
5787 // mNetworkRequests may contain the same value multiple times in case of
5788 // multilayer requests. It won't matter in this case because the thresholds
5789 // will then be the same and be deduplicated as they enter the `thresholds` set.
5790 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
5791 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
5792 for (final NetworkRequest req : nri.mRequests) {
5793 if (req.networkCapabilities.hasSignalStrength()
5794 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5795 thresholds.add(req.networkCapabilities.getSignalStrength());
5796 }
5797 }
5798 }
5799 }
5800 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
5801 }
5802
5803 private void updateSignalStrengthThresholds(
5804 NetworkAgentInfo nai, String reason, NetworkRequest request) {
5805 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
5806
5807 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
5808 String detail;
5809 if (request != null && request.networkCapabilities.hasSignalStrength()) {
5810 detail = reason + " " + request.networkCapabilities.getSignalStrength();
5811 } else {
5812 detail = reason;
5813 }
5814 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
5815 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
5816 }
5817
5818 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
5819 }
5820
5821 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
5822 if (nc == null) {
5823 return;
5824 }
5825 NetworkSpecifier ns = nc.getNetworkSpecifier();
5826 if (ns == null) {
5827 return;
5828 }
5829 if (ns instanceof MatchAllNetworkSpecifier) {
5830 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
5831 }
5832 }
5833
5834 private void ensureValid(NetworkCapabilities nc) {
5835 ensureValidNetworkSpecifier(nc);
5836 if (nc.isPrivateDnsBroken()) {
5837 throw new IllegalArgumentException("Can't request broken private DNS");
5838 }
5839 }
5840
5841 private boolean isTargetSdkAtleast(int version, int callingUid,
5842 @NonNull String callingPackageName) {
5843 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
5844 final PackageManager pm =
5845 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
5846 try {
5847 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
5848 if (callingVersion < version) return false;
5849 } catch (PackageManager.NameNotFoundException e) { }
5850 return true;
5851 }
5852
5853 @Override
5854 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
5855 int reqTypeInt, Messenger messenger, int timeoutMs, IBinder binder,
5856 int legacyType, int callbackFlags, @NonNull String callingPackageName,
5857 @Nullable String callingAttributionTag) {
5858 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
5859 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
5860 callingPackageName)) {
5861 throw new SecurityException("Insufficient permissions to specify legacy type");
5862 }
5863 }
5864 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
5865 final int callingUid = mDeps.getCallingUid();
5866 // Privileged callers can track the default network of another UID by passing in a UID.
5867 if (asUid != Process.INVALID_UID) {
5868 enforceSettingsPermission();
5869 } else {
5870 asUid = callingUid;
5871 }
5872 final NetworkRequest.Type reqType;
5873 try {
5874 reqType = NetworkRequest.Type.values()[reqTypeInt];
5875 } catch (ArrayIndexOutOfBoundsException e) {
5876 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
5877 }
5878 switch (reqType) {
5879 case TRACK_DEFAULT:
5880 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
5881 // is unused and will be replaced by ones appropriate for the UID (usually, the
5882 // calling app). This allows callers to keep track of the default network.
5883 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
5884 defaultNc, asUid, callingUid, callingPackageName);
5885 enforceAccessPermission();
5886 break;
5887 case TRACK_SYSTEM_DEFAULT:
5888 enforceSettingsPermission();
5889 networkCapabilities = new NetworkCapabilities(defaultNc);
5890 break;
5891 case BACKGROUND_REQUEST:
5892 enforceNetworkStackOrSettingsPermission();
5893 // Fall-through since other checks are the same with normal requests.
5894 case REQUEST:
5895 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5896 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
5897 callingAttributionTag);
5898 // TODO: this is incorrect. We mark the request as metered or not depending on
5899 // the state of the app when the request is filed, but we never change the
5900 // request if the app changes network state. http://b/29964605
5901 enforceMeteredApnPolicy(networkCapabilities);
5902 break;
5903 case LISTEN_FOR_BEST:
5904 enforceAccessPermission();
5905 networkCapabilities = new NetworkCapabilities(networkCapabilities);
5906 break;
5907 default:
5908 throw new IllegalArgumentException("Unsupported request type " + reqType);
5909 }
5910 ensureRequestableCapabilities(networkCapabilities);
5911 ensureSufficientPermissionsForRequest(networkCapabilities,
5912 Binder.getCallingPid(), callingUid, callingPackageName);
5913
5914 // Enforce FOREGROUND if the caller does not have permission to use background network.
5915 if (reqType == LISTEN_FOR_BEST) {
5916 restrictBackgroundRequestForCaller(networkCapabilities);
5917 }
5918
5919 // Set the UID range for this request to the single UID of the requester, unless the
5920 // requester has the permission to specify other UIDs.
5921 // This will overwrite any allowed UIDs in the requested capabilities. Though there
5922 // are no visible methods to set the UIDs, an app could use reflection to try and get
5923 // networks for other apps so it's essential that the UIDs are overwritten.
5924 // Also set the requester UID and package name in the request.
5925 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
5926 callingUid, callingPackageName);
5927
5928 if (timeoutMs < 0) {
5929 throw new IllegalArgumentException("Bad timeout specified");
5930 }
5931 ensureValid(networkCapabilities);
5932
5933 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
5934 nextNetworkRequestId(), reqType);
5935 final NetworkRequestInfo nri = getNriToRegister(
5936 asUid, networkRequest, messenger, binder, callbackFlags,
5937 callingAttributionTag);
5938 if (DBG) log("requestNetwork for " + nri);
5939
5940 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
5941 // copied from the default request above. (This is necessary to ensure, for example, that
5942 // the callback does not leak sensitive information to unprivileged apps.) Check that the
5943 // changes don't alter request matching.
5944 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
5945 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
5946 throw new IllegalStateException(
5947 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
5948 + networkCapabilities + " vs. " + defaultNc);
5949 }
5950
5951 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
5952 if (timeoutMs > 0) {
5953 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
5954 nri), timeoutMs);
5955 }
5956 return networkRequest;
5957 }
5958
5959 /**
5960 * Return the nri to be used when registering a network request. Specifically, this is used with
5961 * requests registered to track the default request. If there is currently a per-app default
5962 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
5963 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
5964 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
5965 * when a privileged caller is tracking the default network for another uid.
5966 * @param nr the network request for the nri.
5967 * @param msgr the messenger for the nri.
5968 * @param binder the binder for the nri.
5969 * @param callingAttributionTag the calling attribution tag for the nri.
5970 * @return the nri to register.
5971 */
5972 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
5973 @Nullable final Messenger msgr, @Nullable final IBinder binder,
5974 @NetworkCallback.Flag int callbackFlags,
5975 @Nullable String callingAttributionTag) {
5976 final List<NetworkRequest> requests;
5977 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
5978 requests = copyDefaultNetworkRequestsForUid(
5979 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
5980 } else {
5981 requests = Collections.singletonList(nr);
5982 }
5983 return new NetworkRequestInfo(
5984 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
5985 }
5986
5987 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
5988 String callingPackageName, String callingAttributionTag) {
5989 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
5990 enforceConnectivityRestrictedNetworksPermission();
5991 } else {
5992 enforceChangePermission(callingPackageName, callingAttributionTag);
5993 }
5994 }
5995
5996 @Override
5997 public boolean requestBandwidthUpdate(Network network) {
5998 enforceAccessPermission();
5999 NetworkAgentInfo nai = null;
6000 if (network == null) {
6001 return false;
6002 }
6003 synchronized (mNetworkForNetId) {
6004 nai = mNetworkForNetId.get(network.getNetId());
6005 }
6006 if (nai != null) {
6007 nai.onBandwidthUpdateRequested();
6008 synchronized (mBandwidthRequests) {
6009 final int uid = mDeps.getCallingUid();
6010 Integer uidReqs = mBandwidthRequests.get(uid);
6011 if (uidReqs == null) {
6012 uidReqs = 0;
6013 }
6014 mBandwidthRequests.put(uid, ++uidReqs);
6015 }
6016 return true;
6017 }
6018 return false;
6019 }
6020
6021 private boolean isSystem(int uid) {
6022 return uid < Process.FIRST_APPLICATION_UID;
6023 }
6024
6025 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
6026 final int uid = mDeps.getCallingUid();
6027 if (isSystem(uid)) {
6028 // Exemption for system uid.
6029 return;
6030 }
6031 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6032 // Policy already enforced.
6033 return;
6034 }
6035 final long ident = Binder.clearCallingIdentity();
6036 try {
6037 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6038 // If UID is restricted, don't allow them to bring up metered APNs.
6039 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6040 }
6041 } finally {
6042 Binder.restoreCallingIdentity(ident);
6043 }
6044 }
6045
6046 @Override
6047 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
6048 PendingIntent operation, @NonNull String callingPackageName,
6049 @Nullable String callingAttributionTag) {
6050 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6051 final int callingUid = mDeps.getCallingUid();
6052 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6053 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
6054 callingAttributionTag);
6055 enforceMeteredApnPolicy(networkCapabilities);
6056 ensureRequestableCapabilities(networkCapabilities);
6057 ensureSufficientPermissionsForRequest(networkCapabilities,
6058 Binder.getCallingPid(), callingUid, callingPackageName);
6059 ensureValidNetworkSpecifier(networkCapabilities);
6060 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6061 callingUid, callingPackageName);
6062
6063 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
6064 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
6065 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6066 callingAttributionTag);
6067 if (DBG) log("pendingRequest for " + nri);
6068 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6069 nri));
6070 return networkRequest;
6071 }
6072
6073 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6074 mHandler.sendMessageDelayed(
6075 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6076 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
6077 }
6078
6079 @Override
6080 public void releasePendingNetworkRequest(PendingIntent operation) {
6081 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6082 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
6083 mDeps.getCallingUid(), 0, operation));
6084 }
6085
6086 // In order to implement the compatibility measure for pre-M apps that call
6087 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6088 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6089 // This ensures it has permission to do so.
6090 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6091 if (nc == null) {
6092 return false;
6093 }
6094 int[] transportTypes = nc.getTransportTypes();
6095 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6096 return false;
6097 }
6098 try {
6099 mContext.enforceCallingOrSelfPermission(
6100 android.Manifest.permission.ACCESS_WIFI_STATE,
6101 "ConnectivityService");
6102 } catch (SecurityException e) {
6103 return false;
6104 }
6105 return true;
6106 }
6107
6108 @Override
6109 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
6110 Messenger messenger, IBinder binder,
6111 @NetworkCallback.Flag int callbackFlags,
6112 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
6113 final int callingUid = mDeps.getCallingUid();
6114 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6115 enforceAccessPermission();
6116 }
6117
6118 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6119 ensureSufficientPermissionsForRequest(networkCapabilities,
6120 Binder.getCallingPid(), callingUid, callingPackageName);
6121 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6122 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6123 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6124 // onLost and onAvailable callbacks when networks move in and out of the background.
6125 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6126 // can't request networks.
6127 restrictBackgroundRequestForCaller(nc);
6128 ensureValid(nc);
6129
6130 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6131 NetworkRequest.Type.LISTEN);
6132 NetworkRequestInfo nri =
6133 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
6134 callingAttributionTag);
6135 if (VDBG) log("listenForNetwork for " + nri);
6136
6137 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6138 return networkRequest;
6139 }
6140
6141 @Override
6142 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
6143 PendingIntent operation, @NonNull String callingPackageName,
6144 @Nullable String callingAttributionTag) {
6145 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
6146 final int callingUid = mDeps.getCallingUid();
6147 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6148 enforceAccessPermission();
6149 }
6150 ensureValid(networkCapabilities);
6151 ensureSufficientPermissionsForRequest(networkCapabilities,
6152 Binder.getCallingPid(), callingUid, callingPackageName);
6153 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6154 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
6155
6156 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
6157 NetworkRequest.Type.LISTEN);
6158 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6159 callingAttributionTag);
6160 if (VDBG) log("pendingListenForNetwork for " + nri);
6161
6162 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6163 }
6164
6165 /** Returns the next Network provider ID. */
6166 public final int nextNetworkProviderId() {
6167 return mNextNetworkProviderId.getAndIncrement();
6168 }
6169
6170 private void releaseNetworkRequests(List<NetworkRequest> networkRequests) {
6171 for (int i = 0; i < networkRequests.size(); i++) {
6172 releaseNetworkRequest(networkRequests.get(i));
6173 }
6174 }
6175
6176 @Override
6177 public void releaseNetworkRequest(NetworkRequest networkRequest) {
6178 ensureNetworkRequestHasType(networkRequest);
6179 mHandler.sendMessage(mHandler.obtainMessage(
6180 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
6181 }
6182
6183 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6184 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
6185 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6186 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6187 // as that will throw if a duplicate provider is registered.
6188 loge("Attempt to register existing NetworkProviderInfo "
6189 + mNetworkProviderInfos.get(npi.messenger).name);
6190 return;
6191 }
6192
6193 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6194 mNetworkProviderInfos.put(npi.messenger, npi);
6195 npi.connect(mContext, mTrackerHandler);
6196 }
6197
6198 @Override
6199 public int registerNetworkProvider(Messenger messenger, String name) {
6200 enforceNetworkFactoryOrSettingsPermission();
6201 Objects.requireNonNull(messenger, "messenger must be non-null");
6202 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
6203 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
6204 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6205 return npi.providerId;
6206 }
6207
6208 @Override
6209 public void unregisterNetworkProvider(Messenger messenger) {
6210 enforceNetworkFactoryOrSettingsPermission();
6211 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
6212 }
6213
6214 @Override
6215 public void offerNetwork(final int providerId,
6216 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6217 @NonNull final INetworkOfferCallback callback) {
6218 Objects.requireNonNull(score);
6219 Objects.requireNonNull(caps);
6220 Objects.requireNonNull(callback);
6221 final NetworkOffer offer = new NetworkOffer(
6222 FullScore.makeProspectiveScore(score, caps), caps, callback, providerId);
6223 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6224 }
6225
6226 @Override
6227 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
6228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6229 }
6230
6231 private void handleUnregisterNetworkProvider(Messenger messenger) {
6232 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6233 if (npi == null) {
6234 loge("Failed to find Messenger in unregisterNetworkProvider");
6235 return;
6236 }
6237 // Unregister all the offers from this provider
6238 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6239 for (final NetworkOfferInfo noi : mNetworkOffers) {
6240 if (noi.offer.providerId == npi.providerId) {
6241 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6242 toRemove.add(noi);
6243 }
6244 }
6245 for (final NetworkOfferInfo noi : toRemove) {
6246 handleUnregisterNetworkOffer(noi);
6247 }
6248 if (DBG) log("unregisterNetworkProvider for " + npi.name);
6249 }
6250
6251 @Override
6252 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
6253 if (request.hasTransport(TRANSPORT_TEST)) {
6254 enforceNetworkFactoryOrTestNetworksPermission();
6255 } else {
6256 enforceNetworkFactoryPermission();
6257 }
6258 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6259 if (nri != null) {
6260 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6261 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6262 mHandler.post(() -> handleReleaseNetworkRequest(
6263 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6264 }
6265 }
6266
6267 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6268 @GuardedBy("mNetworkForNetId")
6269 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
6270 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
6271 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
6272 // there may not be a strict 1:1 correlation between the two.
6273 private final NetIdManager mNetIdManager;
6274
6275 // NetworkAgentInfo keyed off its connecting messenger
6276 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
6277 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
6278 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
6279
6280 // UID ranges for users that are currently blocked by VPNs.
6281 // This array is accessed and iterated on multiple threads without holding locks, so its
6282 // contents must never be mutated. When the ranges change, the array is replaced with a new one
6283 // (on the handler thread).
6284 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
6285
6286 // Must only be accessed on the handler thread
6287 @NonNull
6288 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
6289
6290 @GuardedBy("mBlockedAppUids")
6291 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
6292
6293 // Current OEM network preferences. This object must only be written to on the handler thread.
6294 // Since it is immutable and always non-null, other threads may read it if they only care
6295 // about seeing a consistent object but not that it is current.
6296 @NonNull
6297 private OemNetworkPreferences mOemNetworkPreferences =
6298 new OemNetworkPreferences.Builder().build();
6299 // Current per-profile network preferences. This object follows the same threading rules as
6300 // the OEM network preferences above.
6301 @NonNull
6302 private ProfileNetworkPreferences mProfileNetworkPreferences = new ProfileNetworkPreferences();
6303
6304 // OemNetworkPreferences activity String log entries.
6305 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
6306 @NonNull
6307 private final LocalLog mOemNetworkPreferencesLogs =
6308 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
6309
6310 /**
6311 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
6312 * @param packageName the package name to check existence of a mapping for.
6313 * @return true if a mapping exists, false otherwise
6314 */
6315 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
6316 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
6317 }
6318
6319 // The always-on request for an Internet-capable network that apps without a specific default
6320 // fall back to.
6321 @VisibleForTesting
6322 @NonNull
6323 final NetworkRequestInfo mDefaultRequest;
6324 // Collection of NetworkRequestInfo's used for default networks.
6325 @VisibleForTesting
6326 @NonNull
6327 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
6328
6329 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
6330 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
6331 }
6332
6333 /**
6334 * Return the default network request currently tracking the given uid.
6335 * @param uid the uid to check.
6336 * @return the NetworkRequestInfo tracking the given uid.
6337 */
6338 @NonNull
6339 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
6340 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6341 if (nri == mDefaultRequest) {
6342 continue;
6343 }
6344 // Checking the first request is sufficient as only multilayer requests will have more
6345 // than one request and for multilayer, all requests will track the same uids.
6346 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
6347 return nri;
6348 }
6349 }
6350 return mDefaultRequest;
6351 }
6352
6353 /**
6354 * Get a copy of the network requests of the default request that is currently tracking the
6355 * given uid.
6356 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6357 * when a privileged caller is tracking the default network for another uid.
6358 * @param requestorUid the uid to check the default for.
6359 * @param requestorPackageName the requestor's package name.
6360 * @return a copy of the default's NetworkRequest that is tracking the given uid.
6361 */
6362 @NonNull
6363 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
6364 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
6365 return copyNetworkRequestsForUid(
6366 getDefaultRequestTrackingUid(asUid).mRequests,
6367 asUid, requestorUid, requestorPackageName);
6368 }
6369
6370 /**
6371 * Copy the given nri's NetworkRequest collection.
6372 * @param requestsToCopy the NetworkRequest collection to be copied.
6373 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6374 * when a privileged caller is tracking the default network for another uid.
6375 * @param requestorUid the uid to set on the copied collection.
6376 * @param requestorPackageName the package name to set on the copied collection.
6377 * @return the copied NetworkRequest collection.
6378 */
6379 @NonNull
6380 private List<NetworkRequest> copyNetworkRequestsForUid(
6381 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
6382 final int requestorUid, @NonNull final String requestorPackageName) {
6383 final List<NetworkRequest> requests = new ArrayList<>();
6384 for (final NetworkRequest nr : requestsToCopy) {
6385 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
6386 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
6387 nr.legacyType, nextNetworkRequestId(), nr.type));
6388 }
6389 return requests;
6390 }
6391
6392 @NonNull
6393 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
6394 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
6395 final int requestorUid, @NonNull final String requestorPackageName) {
6396 // These capabilities are for a TRACK_DEFAULT callback, so:
6397 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
6398 // mDefaultRequest and a per-UID default request.
6399 // TODO: stop depending on the fact that these two unrelated things happen to be the same
6400 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
6401 // not do this in the case of a privileged application.
6402 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
6403 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
6404 netCap.setSingleUid(asUid);
6405 restrictRequestUidsForCallerAndSetRequestorInfo(
6406 netCap, requestorUid, requestorPackageName);
6407 return netCap;
6408 }
6409
6410 /**
6411 * Get the nri that is currently being tracked for callbacks by per-app defaults.
6412 * @param nr the network request to check for equality against.
6413 * @return the nri if one exists, null otherwise.
6414 */
6415 @Nullable
6416 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
6417 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6418 if (nri.getNetworkRequestForCallback().equals(nr)) {
6419 return nri;
6420 }
6421 }
6422 return null;
6423 }
6424
6425 /**
6426 * Check if an nri is currently being managed by per-app default networking.
6427 * @param nri the nri to check.
6428 * @return true if this nri is currently being managed by per-app default networking.
6429 */
6430 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
6431 // nri.mRequests.get(0) is only different from the original request filed in
6432 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
6433 // functionality therefore if these two don't match, it means this particular nri is
6434 // currently being managed by a per-app default.
6435 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
6436 }
6437
6438 /**
6439 * Determine if an nri is a managed default request that disallows default networking.
6440 * @param nri the request to evaluate
6441 * @return true if device-default networking is disallowed
6442 */
6443 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
6444 // Check if this nri is a managed default that supports the default network at its
6445 // lowest priority request.
6446 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
6447 final NetworkCapabilities lowestPriorityNetCap =
6448 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
6449 return isPerAppDefaultRequest(nri)
6450 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
6451 lowestPriorityNetCap));
6452 }
6453
6454 // Request used to optionally keep mobile data active even when higher
6455 // priority networks like Wi-Fi are active.
6456 private final NetworkRequest mDefaultMobileDataRequest;
6457
6458 // Request used to optionally keep wifi data active even when higher
6459 // priority networks like ethernet are active.
6460 private final NetworkRequest mDefaultWifiRequest;
6461
6462 // Request used to optionally keep vehicle internal network always active
6463 private final NetworkRequest mDefaultVehicleRequest;
6464
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +00006465 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
6466 // network with no service. This NAI should never be matched against, nor should any public API
6467 // ever return the associated network. For this reason, this NAI is not in the list of available
6468 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
6469 // default requests that don't support using the device default network which will ultimately
6470 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
6471 @VisibleForTesting
6472 final NetworkAgentInfo mNoServiceNetwork;
6473
6474 // The NetworkAgentInfo currently satisfying the default request, if any.
6475 private NetworkAgentInfo getDefaultNetwork() {
6476 return mDefaultRequest.mSatisfier;
6477 }
6478
6479 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
6480 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
6481 // Currently, all network requests will have the same uids therefore checking the first
6482 // one is sufficient. If/when uids are tracked at the nri level, this can change.
6483 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
6484 if (null == uids) {
6485 continue;
6486 }
6487 for (final UidRange range : uids) {
6488 if (range.contains(uid)) {
6489 return nri.getSatisfier();
6490 }
6491 }
6492 }
6493 return getDefaultNetwork();
6494 }
6495
6496 @Nullable
6497 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
6498 return nai != null ? nai.network : null;
6499 }
6500
6501 private void ensureRunningOnConnectivityServiceThread() {
6502 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
6503 throw new IllegalStateException(
6504 "Not running on ConnectivityService thread: "
6505 + Thread.currentThread().getName());
6506 }
6507 }
6508
6509 @VisibleForTesting
6510 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
6511 return nai == getDefaultNetwork();
6512 }
6513
6514 /**
6515 * Register a new agent with ConnectivityService to handle a network.
6516 *
6517 * @param na a reference for ConnectivityService to contact the agent asynchronously.
6518 * @param networkInfo the initial info associated with this network. It can be updated later :
6519 * see {@link #updateNetworkInfo}.
6520 * @param linkProperties the initial link properties of this network. They can be updated
6521 * later : see {@link #updateLinkProperties}.
6522 * @param networkCapabilities the initial capabilites of this network. They can be updated
6523 * later : see {@link #updateCapabilities}.
6524 * @param initialScore the initial score of the network. See
6525 * {@link NetworkAgentInfo#getCurrentScore}.
6526 * @param networkAgentConfig metadata about the network. This is never updated.
6527 * @param providerId the ID of the provider owning this NetworkAgent.
6528 * @return the network created for this agent.
6529 */
6530 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
6531 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6532 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
6533 int providerId) {
6534 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
6535 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
6536 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
6537 Objects.requireNonNull(initialScore, "initialScore must not be null");
6538 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
6539 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6540 enforceAnyPermissionOf(Manifest.permission.MANAGE_TEST_NETWORKS);
6541 } else {
6542 enforceNetworkFactoryPermission();
6543 }
6544
6545 final int uid = mDeps.getCallingUid();
6546 final long token = Binder.clearCallingIdentity();
6547 try {
6548 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
6549 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
6550 } finally {
6551 Binder.restoreCallingIdentity(token);
6552 }
6553 }
6554
6555 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
6556 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
6557 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
6558 int uid) {
6559 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
6560 // Strictly, sanitizing here is unnecessary as the capabilities will be sanitized in
6561 // the call to mixInCapabilities below anyway, but sanitizing here means the NAI never
6562 // sees capabilities that may be malicious, which might prevent mistakes in the future.
6563 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6564 networkCapabilities.restrictCapabilitesForTestNetwork(uid);
6565 }
6566
6567 LinkProperties lp = new LinkProperties(linkProperties);
6568
6569 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
6570 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
6571 new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
6572 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
6573 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
6574 mQosCallbackTracker, mDeps);
6575
6576 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info says.
6577 processCapabilitiesFromAgent(nai, nc);
6578 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai, nc));
6579 processLinkPropertiesFromAgent(nai, nai.linkProperties);
6580
6581 final String extraInfo = networkInfo.getExtraInfo();
6582 final String name = TextUtils.isEmpty(extraInfo)
6583 ? nai.networkCapabilities.getSsid() : extraInfo;
6584 if (DBG) log("registerNetworkAgent " + nai);
6585 mDeps.getNetworkStack().makeNetworkMonitor(
6586 nai.network, name, new NetworkMonitorCallbacks(nai));
6587 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
6588 // If the network disconnects or sends any other event before that, messages are deferred by
6589 // NetworkAgent until nai.connect(), which will be called when finalizing the
6590 // registration.
6591 return nai.network;
6592 }
6593
6594 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
6595 nai.onNetworkMonitorCreated(networkMonitor);
6596 if (VDBG) log("Got NetworkAgent Messenger");
6597 mNetworkAgentInfos.add(nai);
6598 synchronized (mNetworkForNetId) {
6599 mNetworkForNetId.put(nai.network.getNetId(), nai);
6600 }
6601
6602 try {
6603 networkMonitor.start();
6604 } catch (RemoteException e) {
6605 e.rethrowAsRuntimeException();
6606 }
6607 nai.notifyRegistered();
6608 NetworkInfo networkInfo = nai.networkInfo;
6609 updateNetworkInfo(nai, networkInfo);
6610 updateUids(nai, null, nai.networkCapabilities);
6611 }
6612
6613 private class NetworkOfferInfo implements IBinder.DeathRecipient {
6614 @NonNull public final NetworkOffer offer;
6615
6616 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
6617 this.offer = offer;
6618 }
6619
6620 @Override
6621 public void binderDied() {
6622 mHandler.post(() -> handleUnregisterNetworkOffer(this));
6623 }
6624 }
6625
6626 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
6627 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
6628 if (npi.providerId == providerId) return true;
6629 }
6630 return false;
6631 }
6632
6633 /**
6634 * Register or update a network offer.
6635 * @param newOffer The new offer. If the callback member is the same as an existing
6636 * offer, it is an update of that offer.
6637 */
6638 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
6639 ensureRunningOnConnectivityServiceThread();
6640 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
6641 // This may actually happen if a provider updates its score or registers and then
6642 // immediately unregisters. The offer would still be in the handler queue, but the
6643 // provider would have been removed.
6644 if (DBG) log("Received offer from an unregistered provider");
6645 return;
6646 }
6647 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
6648 if (null != existingOffer) {
6649 handleUnregisterNetworkOffer(existingOffer);
6650 newOffer.migrateFrom(existingOffer.offer);
6651 }
6652 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
6653 try {
6654 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
6655 } catch (RemoteException e) {
6656 noi.binderDied();
6657 return;
6658 }
6659 mNetworkOffers.add(noi);
6660 issueNetworkNeeds(noi);
6661 }
6662
6663 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
6664 ensureRunningOnConnectivityServiceThread();
6665 mNetworkOffers.remove(noi);
6666 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
6667 }
6668
6669 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
6670 @NonNull final INetworkOfferCallback callback) {
6671 ensureRunningOnConnectivityServiceThread();
6672 for (final NetworkOfferInfo noi : mNetworkOffers) {
6673 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
6674 }
6675 return null;
6676 }
6677
6678 /**
6679 * Called when receiving LinkProperties directly from a NetworkAgent.
6680 * Stores into |nai| any data coming from the agent that might also be written to the network's
6681 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
6682 * agent is not lost when updateLinkProperties is called.
6683 * This method should never alter the agent's LinkProperties, only store data in |nai|.
6684 */
6685 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
6686 lp.ensureDirectlyConnectedRoutes();
6687 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
6688 nai.networkAgentPortalData = lp.getCaptivePortalData();
6689 }
6690
6691 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
6692 @NonNull LinkProperties oldLp) {
6693 int netId = networkAgent.network.getNetId();
6694
6695 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
6696 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
6697 // the LinkProperties for the network are accurate.
6698 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
6699
6700 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
6701
6702 // update filtering rules, need to happen after the interface update so netd knows about the
6703 // new interface (the interface name -> index map becomes initialized)
6704 updateVpnFiltering(newLp, oldLp, networkAgent);
6705
6706 updateMtu(newLp, oldLp);
6707 // TODO - figure out what to do for clat
6708// for (LinkProperties lp : newLp.getStackedLinks()) {
6709// updateMtu(lp, null);
6710// }
6711 if (isDefaultNetwork(networkAgent)) {
6712 updateTcpBufferSizes(newLp.getTcpBufferSizes());
6713 }
6714
6715 updateRoutes(newLp, oldLp, netId);
6716 updateDnses(newLp, oldLp, netId);
6717 // Make sure LinkProperties represents the latest private DNS status.
6718 // This does not need to be done before updateDnses because the
6719 // LinkProperties are not the source of the private DNS configuration.
6720 // updateDnses will fetch the private DNS configuration from DnsManager.
6721 mDnsManager.updatePrivateDnsStatus(netId, newLp);
6722
6723 if (isDefaultNetwork(networkAgent)) {
6724 handleApplyDefaultProxy(newLp.getHttpProxy());
6725 } else {
6726 updateProxy(newLp, oldLp);
6727 }
6728
6729 updateWakeOnLan(newLp);
6730
6731 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
6732 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
6733 // does, it needs to be merged here.
6734 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
6735 networkAgent.capportApiData));
6736
6737 // TODO - move this check to cover the whole function
6738 if (!Objects.equals(newLp, oldLp)) {
6739 synchronized (networkAgent) {
6740 networkAgent.linkProperties = newLp;
6741 }
6742 // Start or stop DNS64 detection and 464xlat according to network state.
6743 networkAgent.clatd.update();
6744 notifyIfacesChangedForNetworkStats();
6745 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
6746 new LinkProperties(newLp, true /* parcelSensitiveFields */));
6747 if (networkAgent.everConnected) {
6748 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
6749 }
6750 }
6751
6752 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
6753 }
6754
6755 /**
6756 * @param naData captive portal data from NetworkAgent
6757 * @param apiData captive portal data from capport API
6758 */
6759 @Nullable
6760 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
6761 CaptivePortalData apiData) {
6762 if (naData == null || apiData == null) {
6763 return naData == null ? apiData : naData;
6764 }
6765 final CaptivePortalData.Builder captivePortalBuilder =
6766 new CaptivePortalData.Builder(naData);
6767
6768 if (apiData.isCaptive()) {
6769 captivePortalBuilder.setCaptive(true);
6770 }
6771 if (apiData.isSessionExtendable()) {
6772 captivePortalBuilder.setSessionExtendable(true);
6773 }
6774 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
6775 // Expiry time, bytes remaining, refresh time all need to come from the same source,
6776 // otherwise data would be inconsistent. Prefer the capport API info if present,
6777 // as it can generally be refreshed more often.
6778 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
6779 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
6780 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
6781 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
6782 // No source has time / bytes remaining information: surface the newest refresh time
6783 // for other fields
6784 captivePortalBuilder.setRefreshTime(
6785 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
6786 }
6787
6788 // Prioritize the user portal URL from the network agent if the source is authenticated.
6789 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
6790 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6791 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
6792 apiData.getUserPortalUrlSource());
6793 }
6794 // Prioritize the venue information URL from the network agent if the source is
6795 // authenticated.
6796 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
6797 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
6798 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
6799 apiData.getVenueInfoUrlSource());
6800 }
6801 return captivePortalBuilder.build();
6802 }
6803
6804 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
6805 // Marks are only available on WiFi interfaces. Checking for
6806 // marks on unsupported interfaces is harmless.
6807 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6808 return;
6809 }
6810
6811 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
6812 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
6813
6814 // TODO (b/183076074): remove legacy fallback after migrating overlays
6815 final int legacyMark = mContext.getResources().getInteger(mContext.getResources()
6816 .getIdentifier("config_networkWakeupPacketMark", "integer", "android"));
6817 final int legacyMask = mContext.getResources().getInteger(mContext.getResources()
6818 .getIdentifier("config_networkWakeupPacketMask", "integer", "android"));
6819 mark = mark == 0 ? legacyMark : mark;
6820 mask = mask == 0 ? legacyMask : mask;
6821
6822 // Mask/mark of zero will not detect anything interesting.
6823 // Don't install rules unless both values are nonzero.
6824 if (mark == 0 || mask == 0) {
6825 return;
6826 }
6827
6828 final String prefix = "iface:" + iface;
6829 try {
6830 if (add) {
6831 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
6832 } else {
6833 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
6834 }
6835 } catch (Exception e) {
6836 loge("Exception modifying wakeup packet monitoring: " + e);
6837 }
6838
6839 }
6840
6841 private void updateInterfaces(final @Nullable LinkProperties newLp,
6842 final @Nullable LinkProperties oldLp, final int netId,
6843 final @NonNull NetworkCapabilities caps) {
6844 final CompareResult<String> interfaceDiff = new CompareResult<>(
6845 oldLp != null ? oldLp.getAllInterfaceNames() : null,
6846 newLp != null ? newLp.getAllInterfaceNames() : null);
6847 if (!interfaceDiff.added.isEmpty()) {
6848 for (final String iface : interfaceDiff.added) {
6849 try {
6850 if (DBG) log("Adding iface " + iface + " to network " + netId);
6851 mNetd.networkAddInterface(netId, iface);
6852 wakeupModifyInterface(iface, caps, true);
6853 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
6854 caps.getTransportTypes());
6855 } catch (Exception e) {
6856 logw("Exception adding interface: " + e);
6857 }
6858 }
6859 }
6860 for (final String iface : interfaceDiff.removed) {
6861 try {
6862 if (DBG) log("Removing iface " + iface + " from network " + netId);
6863 wakeupModifyInterface(iface, caps, false);
6864 mNetd.networkRemoveInterface(netId, iface);
6865 } catch (Exception e) {
6866 loge("Exception removing interface: " + e);
6867 }
6868 }
6869 }
6870
6871 // TODO: move to frameworks/libs/net.
6872 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
6873 final String nextHop;
6874
6875 switch (route.getType()) {
6876 case RouteInfo.RTN_UNICAST:
6877 if (route.hasGateway()) {
6878 nextHop = route.getGateway().getHostAddress();
6879 } else {
6880 nextHop = INetd.NEXTHOP_NONE;
6881 }
6882 break;
6883 case RouteInfo.RTN_UNREACHABLE:
6884 nextHop = INetd.NEXTHOP_UNREACHABLE;
6885 break;
6886 case RouteInfo.RTN_THROW:
6887 nextHop = INetd.NEXTHOP_THROW;
6888 break;
6889 default:
6890 nextHop = INetd.NEXTHOP_NONE;
6891 break;
6892 }
6893
6894 final RouteInfoParcel rip = new RouteInfoParcel();
6895 rip.ifName = route.getInterface();
6896 rip.destination = route.getDestination().toString();
6897 rip.nextHop = nextHop;
6898 rip.mtu = route.getMtu();
6899
6900 return rip;
6901 }
6902
6903 /**
6904 * Have netd update routes from oldLp to newLp.
6905 * @return true if routes changed between oldLp and newLp
6906 */
6907 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
6908 // compare the route diff to determine which routes have been updated
6909 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
6910 new CompareOrUpdateResult<>(
6911 oldLp != null ? oldLp.getAllRoutes() : null,
6912 newLp != null ? newLp.getAllRoutes() : null,
6913 (r) -> r.getRouteKey());
6914
6915 // add routes before removing old in case it helps with continuous connectivity
6916
6917 // do this twice, adding non-next-hop routes first, then routes they are dependent on
6918 for (RouteInfo route : routeDiff.added) {
6919 if (route.hasGateway()) continue;
6920 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
6921 try {
6922 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
6923 } catch (Exception e) {
6924 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
6925 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
6926 }
6927 }
6928 }
6929 for (RouteInfo route : routeDiff.added) {
6930 if (!route.hasGateway()) continue;
6931 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
6932 try {
6933 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
6934 } catch (Exception e) {
6935 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
6936 loge("Exception in networkAddRouteParcel for gateway: " + e);
6937 }
6938 }
6939 }
6940
6941 for (RouteInfo route : routeDiff.removed) {
6942 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
6943 try {
6944 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
6945 } catch (Exception e) {
6946 loge("Exception in networkRemoveRouteParcel: " + e);
6947 }
6948 }
6949
6950 for (RouteInfo route : routeDiff.updated) {
6951 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
6952 try {
6953 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
6954 } catch (Exception e) {
6955 loge("Exception in networkUpdateRouteParcel: " + e);
6956 }
6957 }
6958 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
6959 || !routeDiff.updated.isEmpty();
6960 }
6961
6962 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
6963 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
6964 return; // no updating necessary
6965 }
6966
6967 if (DBG) {
6968 final Collection<InetAddress> dnses = newLp.getDnsServers();
6969 log("Setting DNS servers for network " + netId + " to " + dnses);
6970 }
6971 try {
6972 mDnsManager.noteDnsServersForNetwork(netId, newLp);
6973 mDnsManager.flushVmDnsCache();
6974 } catch (Exception e) {
6975 loge("Exception in setDnsConfigurationForNetwork: " + e);
6976 }
6977 }
6978
6979 private void updateVpnFiltering(LinkProperties newLp, LinkProperties oldLp,
6980 NetworkAgentInfo nai) {
6981 final String oldIface = oldLp != null ? oldLp.getInterfaceName() : null;
6982 final String newIface = newLp != null ? newLp.getInterfaceName() : null;
6983 final boolean wasFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, oldLp);
6984 final boolean needsFiltering = requiresVpnIsolation(nai, nai.networkCapabilities, newLp);
6985
6986 if (!wasFiltering && !needsFiltering) {
6987 // Nothing to do.
6988 return;
6989 }
6990
6991 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
6992 // Nothing changed.
6993 return;
6994 }
6995
6996 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
6997 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
6998 // TODO: this create a window of opportunity for apps to receive traffic between the time
6999 // when the old rules are removed and the time when new rules are added. To fix this,
7000 // make eBPF support two allowlisted interfaces so here new rules can be added before the
7001 // old rules are being removed.
7002 if (wasFiltering) {
7003 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7004 }
7005 if (needsFiltering) {
7006 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7007 }
7008 }
7009
7010 private void updateWakeOnLan(@NonNull LinkProperties lp) {
7011 if (mWolSupportedInterfaces == null) {
7012 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
7013 R.array.config_wakeonlan_supported_interfaces));
7014 }
7015 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7016 }
7017
7018 private int getNetworkPermission(NetworkCapabilities nc) {
7019 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7020 return INetd.PERMISSION_SYSTEM;
7021 }
7022 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
7023 return INetd.PERMISSION_NETWORK;
7024 }
7025 return INetd.PERMISSION_NONE;
7026 }
7027
7028 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7029 @NonNull final NetworkCapabilities newNc) {
7030 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7031 final int newPermission = getNetworkPermission(newNc);
7032 if (oldPermission != newPermission && nai.created && !nai.isVPN()) {
7033 try {
7034 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
7035 } catch (RemoteException | ServiceSpecificException e) {
7036 loge("Exception in networkSetPermissionForNetwork: " + e);
7037 }
7038 }
7039 }
7040
7041 /**
7042 * Called when receiving NetworkCapabilities directly from a NetworkAgent.
7043 * Stores into |nai| any data coming from the agent that might also be written to the network's
7044 * NetworkCapabilities by ConnectivityService itself. This ensures that the data provided by the
7045 * agent is not lost when updateCapabilities is called.
7046 * This method should never alter the agent's NetworkCapabilities, only store data in |nai|.
7047 */
7048 private void processCapabilitiesFromAgent(NetworkAgentInfo nai, NetworkCapabilities nc) {
7049 // Note: resetting the owner UID before storing the agent capabilities in NAI means that if
7050 // the agent attempts to change the owner UID, then nai.declaredCapabilities will not
7051 // actually be the same as the capabilities sent by the agent. Still, it is safer to reset
7052 // the owner UID here and behave as if the agent had never tried to change it.
7053 if (nai.networkCapabilities.getOwnerUid() != nc.getOwnerUid()) {
7054 Log.e(TAG, nai.toShortString() + ": ignoring attempt to change owner from "
7055 + nai.networkCapabilities.getOwnerUid() + " to " + nc.getOwnerUid());
7056 nc.setOwnerUid(nai.networkCapabilities.getOwnerUid());
7057 }
7058 nai.declaredCapabilities = new NetworkCapabilities(nc);
7059 }
7060
7061 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
7062 @VisibleForTesting
7063 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
7064 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
7065 underlyingNetworks = underlyingNetworksOrDefault(
7066 agentCaps.getOwnerUid(), underlyingNetworks);
7067 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
7068 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7069 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7070 // metered if any underlying is metered, or originally declared metered by the agent.
7071 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7072 boolean roaming = false; // roaming if any underlying is roaming
7073 boolean congested = false; // congested if any underlying is congested
7074 boolean suspended = true; // suspended if all underlying are suspended
7075
7076 boolean hadUnderlyingNetworks = false;
7077 if (null != underlyingNetworks) {
7078 for (Network underlyingNetwork : underlyingNetworks) {
7079 final NetworkAgentInfo underlying =
7080 getNetworkAgentInfoForNetwork(underlyingNetwork);
7081 if (underlying == null) continue;
7082
7083 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7084 hadUnderlyingNetworks = true;
7085 for (int underlyingType : underlyingCaps.getTransportTypes()) {
7086 transportTypes |= 1L << underlyingType;
7087 }
7088
7089 // Merge capabilities of this underlying network. For bandwidth, assume the
7090 // worst case.
7091 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7092 underlyingCaps.getLinkDownstreamBandwidthKbps());
7093 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7094 underlyingCaps.getLinkUpstreamBandwidthKbps());
7095 // If this underlying network is metered, the VPN is metered (it may cost money
7096 // to send packets on this network).
7097 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7098 // If this underlying network is roaming, the VPN is roaming (the billing structure
7099 // is different than the usual, local one).
7100 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7101 // If this underlying network is congested, the VPN is congested (the current
7102 // condition of the network affects the performance of this network).
7103 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7104 // If this network is not suspended, the VPN is not suspended (the VPN
7105 // is able to transfer some data).
7106 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7107 }
7108 }
7109 if (!hadUnderlyingNetworks) {
7110 // No idea what the underlying networks are; assume reasonable defaults
7111 metered = true;
7112 roaming = false;
7113 congested = false;
7114 suspended = false;
7115 }
7116
7117 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
7118 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7119 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7120 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7121 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7122 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7123 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
7124 }
7125
7126 /**
7127 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7128 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7129 * and foreground status).
7130 */
7131 @NonNull
7132 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
7133 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
7134 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7135 // causing a connect/teardown loop.
7136 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
7137 // avoid connect/teardown loops.
7138 if (nai.everConnected &&
7139 !nai.isVPN() &&
7140 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
7141 // TODO: consider not complaining when a network agent degrades its capabilities if this
7142 // does not cause any request (that is not a listen) currently matching that agent to
7143 // stop being matched by the updated agent.
7144 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
7145 if (!TextUtils.isEmpty(diff)) {
7146 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
7147 }
7148 }
7149
7150 // Don't modify caller's NetworkCapabilities.
7151 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
7152 if (nai.lastValidated) {
7153 newNc.addCapability(NET_CAPABILITY_VALIDATED);
7154 } else {
7155 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
7156 }
7157 if (nai.lastCaptivePortalDetected) {
7158 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7159 } else {
7160 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
7161 }
7162 if (nai.isBackgroundNetwork()) {
7163 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
7164 } else {
7165 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
7166 }
7167 if (nai.partialConnectivity) {
7168 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7169 } else {
7170 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7171 }
7172 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
7173
7174 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
7175 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7176 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
7177 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
7178 }
7179
7180 if (nai.supportsUnderlyingNetworks()) {
7181 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks, nai.declaredCapabilities,
7182 newNc);
7183 }
7184
7185 return newNc;
7186 }
7187
7188 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7189 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7190 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7191 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7192 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7193 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7194 if (prevSuspended != suspended) {
7195 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7196 // onResumed have been removed.
7197 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7198 : ConnectivityManager.CALLBACK_RESUMED);
7199 }
7200 if (prevSuspended != suspended || prevRoaming != roaming) {
7201 // updateNetworkInfo will mix in the suspended info from the capabilities and
7202 // take appropriate action for the network having possibly changed state.
7203 updateNetworkInfo(nai, nai.networkInfo);
7204 }
7205 }
7206
7207 /**
7208 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7209 *
7210 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7211 * capabilities we manage and store in {@code nai}, such as validated status and captive
7212 * portal status)
7213 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7214 * potentially triggers rematches.
7215 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7216 * change.)
7217 *
7218 * @param oldScore score of the network before any of the changes that prompted us
7219 * to call this function.
7220 * @param nai the network having its capabilities updated.
7221 * @param nc the new network capabilities.
7222 */
7223 private void updateCapabilities(final int oldScore, @NonNull final NetworkAgentInfo nai,
7224 @NonNull final NetworkCapabilities nc) {
7225 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
7226 if (Objects.equals(nai.networkCapabilities, newNc)) return;
7227 updateNetworkPermissions(nai, newNc);
7228 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
7229
7230 updateUids(nai, prevNc, newNc);
7231 nai.updateScoreForNetworkAgentUpdate();
7232
7233 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
7234 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7235 // the change we're processing can't affect any requests, it can only affect the listens
7236 // on this network. We might have been called by rematchNetworkAndRequests when a
7237 // network changed foreground state.
7238 processListenRequests(nai);
7239 } else {
7240 // If the requestable capabilities have changed or the score changed, we can't have been
7241 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
7242 rematchAllNetworksAndRequests();
7243 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7244 }
7245 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
7246
7247 final boolean oldMetered = prevNc.isMetered();
7248 final boolean newMetered = newNc.isMetered();
7249 final boolean meteredChanged = oldMetered != newMetered;
7250
7251 if (meteredChanged) {
7252 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7253 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
7254 }
7255
7256 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7257 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7258
7259 // Report changes that are interesting for network statistics tracking.
7260 if (meteredChanged || roamingChanged) {
7261 notifyIfacesChangedForNetworkStats();
7262 }
7263
7264 // This network might have been underlying another network. Propagate its capabilities.
7265 propagateUnderlyingNetworkCapabilities(nai.network);
7266
7267 if (!newNc.equalsTransportTypes(prevNc)) {
7268 mDnsManager.updateTransportsForNetwork(
7269 nai.network.getNetId(), newNc.getTransportTypes());
7270 }
7271 }
7272
7273 /** Convenience method to update the capabilities for a given network. */
7274 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
7275 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
7276 }
7277
7278 /**
7279 * Returns whether VPN isolation (ingress interface filtering) should be applied on the given
7280 * network.
7281 *
7282 * Ingress interface filtering enforces that all apps under the given network can only receive
7283 * packets from the network's interface (and loopback). This is important for VPNs because
7284 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
7285 * non-VPN interfaces.
7286 *
7287 * As a result, this method should return true iff
7288 * 1. the network is an app VPN (not legacy VPN)
7289 * 2. the VPN does not allow bypass
7290 * 3. the VPN is fully-routed
7291 * 4. the VPN interface is non-null
7292 *
7293 * @see INetd#firewallAddUidInterfaceRules
7294 * @see INetd#firewallRemoveUidInterfaceRules
7295 */
7296 private boolean requiresVpnIsolation(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
7297 LinkProperties lp) {
7298 if (nc == null || lp == null) return false;
7299 return nai.isVPN()
7300 && !nai.networkAgentConfig.allowBypass
7301 && nc.getOwnerUid() != Process.SYSTEM_UID
7302 && lp.getInterfaceName() != null
7303 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
7304 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute());
7305 }
7306
7307 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
7308 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
7309 int index = 0;
7310 for (UidRange range : ranges) {
7311 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
7312 index++;
7313 }
7314 return stableRanges;
7315 }
7316
7317 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
7318 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
7319 for (int i = 0; i < ranges.length; i++) {
7320 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
7321 }
7322 return stableRanges;
7323 }
7324
7325 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
7326 int[] exemptUids) {
7327 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
7328 try {
7329 mNetd.socketDestroy(ranges, exemptUids);
7330 } catch (Exception e) {
7331 loge("Exception in socket destroy: ", e);
7332 }
7333 }
7334 }
7335
7336 private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
7337 int[] exemptUids = new int[2];
7338 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
7339 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
7340 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
7341 exemptUids[0] = VPN_UID;
7342 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
7343 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
7344
7345 maybeCloseSockets(nai, ranges, exemptUids);
7346 try {
7347 if (add) {
7348 mNetd.networkAddUidRanges(nai.network.netId, ranges);
7349 } else {
7350 mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
7351 }
7352 } catch (Exception e) {
7353 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
7354 " on netId " + nai.network.netId + ". " + e);
7355 }
7356 maybeCloseSockets(nai, ranges, exemptUids);
7357 }
7358
7359 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
7360 NetworkCapabilities newNc) {
7361 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
7362 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
7363 if (null == prevRanges) prevRanges = new ArraySet<>();
7364 if (null == newRanges) newRanges = new ArraySet<>();
7365 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
7366
7367 prevRanges.removeAll(newRanges);
7368 newRanges.removeAll(prevRangesCopy);
7369
7370 try {
7371 // When updating the VPN uid routing rules, add the new range first then remove the old
7372 // range. If old range were removed first, there would be a window between the old
7373 // range being removed and the new range being added, during which UIDs contained
7374 // in both ranges are not subject to any VPN routing rules. Adding new range before
7375 // removing old range works because, unlike the filtering rules below, it's possible to
7376 // add duplicate UID routing rules.
7377 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
7378 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
7379 // [1-5] & [1-2],[4-5] == [3]
7380 // Then we can do:
7381 // maybeCloseSockets([3])
7382 // mNetd.networkAddUidRanges([1-2],[4-5])
7383 // mNetd.networkRemoveUidRanges([1-5])
7384 // maybeCloseSockets([3])
7385 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
7386 // number of binder calls from 6 to 4.
7387 if (!newRanges.isEmpty()) {
7388 updateUidRanges(true, nai, newRanges);
7389 }
7390 if (!prevRanges.isEmpty()) {
7391 updateUidRanges(false, nai, prevRanges);
7392 }
7393 final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
7394 final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
7395 final String iface = nai.linkProperties.getInterfaceName();
7396 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
7397 // be added, due to the range being expanded and stored as individual UIDs. For example
7398 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
7399 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
7400 // were added first and then newRanges got removed later, there would be only one uid
7401 // 10013 left. A consequence of removing old ranges before adding new ranges is that
7402 // there is now a window of opportunity when the UIDs are not subject to any filtering.
7403 // Note that this is in contrast with the (more robust) update of VPN routing rules
7404 // above, where the addition of new ranges happens before the removal of old ranges.
7405 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
7406 // to be removed will never overlap with the new range to be added.
7407 if (wasFiltering && !prevRanges.isEmpty()) {
7408 mPermissionMonitor.onVpnUidRangesRemoved(iface, prevRanges, prevNc.getOwnerUid());
7409 }
7410 if (shouldFilter && !newRanges.isEmpty()) {
7411 mPermissionMonitor.onVpnUidRangesAdded(iface, newRanges, newNc.getOwnerUid());
7412 }
7413 } catch (Exception e) {
7414 // Never crash!
7415 loge("Exception in updateUids: ", e);
7416 }
7417 }
7418
7419 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
7420 ensureRunningOnConnectivityServiceThread();
7421
7422 if (getNetworkAgentInfoForNetId(nai.network.getNetId()) != nai) {
7423 // Ignore updates for disconnected networks
7424 return;
7425 }
7426 if (VDBG || DDBG) {
7427 log("Update of LinkProperties for " + nai.toShortString()
7428 + "; created=" + nai.created
7429 + "; everConnected=" + nai.everConnected);
7430 }
7431 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
7432 // modify its oldLp parameter.
7433 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
7434 }
7435
7436 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
7437 int notificationType) {
7438 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
7439 Intent intent = new Intent();
7440 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
7441 // If apps could file multi-layer requests with PendingIntents, they'd need to know
7442 // which of the layer is satisfied alongside with some ID for the request. Hence, if
7443 // such an API is ever implemented, there is no doubt the right request to send in
7444 // EXTRA_NETWORK_REQUEST is mActiveRequest, and whatever ID would be added would need to
7445 // be sent as a separate extra.
7446 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.getActiveRequest());
7447 nri.mPendingIntentSent = true;
7448 sendIntent(nri.mPendingIntent, intent);
7449 }
7450 // else not handled
7451 }
7452
7453 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
7454 mPendingIntentWakeLock.acquire();
7455 try {
7456 if (DBG) log("Sending " + pendingIntent);
7457 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
7458 } catch (PendingIntent.CanceledException e) {
7459 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
7460 mPendingIntentWakeLock.release();
7461 releasePendingNetworkRequest(pendingIntent);
7462 }
7463 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
7464 }
7465
7466 @Override
7467 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
7468 String resultData, Bundle resultExtras) {
7469 if (DBG) log("Finished sending " + pendingIntent);
7470 mPendingIntentWakeLock.release();
7471 // Release with a delay so the receiving client has an opportunity to put in its
7472 // own request.
7473 releasePendingNetworkRequestWithDelay(pendingIntent);
7474 }
7475
7476 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
7477 @NonNull final NetworkAgentInfo networkAgent, final int notificationType,
7478 final int arg1) {
7479 if (nri.mMessenger == null) {
7480 // Default request has no msgr. Also prevents callbacks from being invoked for
7481 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
7482 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
7483 return;
7484 }
7485 Bundle bundle = new Bundle();
7486 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7487 // TODO: check if defensive copies of data is needed.
7488 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
7489 putParcelable(bundle, nrForCallback);
7490 Message msg = Message.obtain();
7491 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
7492 putParcelable(bundle, networkAgent.network);
7493 }
7494 final boolean includeLocationSensitiveInfo =
7495 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
7496 switch (notificationType) {
7497 case ConnectivityManager.CALLBACK_AVAILABLE: {
7498 final NetworkCapabilities nc =
7499 networkCapabilitiesRestrictedForCallerPermissions(
7500 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7501 putParcelable(
7502 bundle,
7503 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7504 nc, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7505 nrForCallback.getRequestorPackageName(),
7506 nri.mCallingAttributionTag));
7507 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7508 networkAgent.linkProperties, nri.mPid, nri.mUid));
7509 // For this notification, arg1 contains the blocked status.
7510 msg.arg1 = arg1;
7511 break;
7512 }
7513 case ConnectivityManager.CALLBACK_LOSING: {
7514 msg.arg1 = arg1;
7515 break;
7516 }
7517 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
7518 // networkAgent can't be null as it has been accessed a few lines above.
7519 final NetworkCapabilities netCap =
7520 networkCapabilitiesRestrictedForCallerPermissions(
7521 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
7522 putParcelable(
7523 bundle,
7524 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
7525 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
7526 nrForCallback.getRequestorPackageName(),
7527 nri.mCallingAttributionTag));
7528 break;
7529 }
7530 case ConnectivityManager.CALLBACK_IP_CHANGED: {
7531 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
7532 networkAgent.linkProperties, nri.mPid, nri.mUid));
7533 break;
7534 }
7535 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
7536 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
7537 msg.arg1 = arg1;
7538 break;
7539 }
7540 }
7541 msg.what = notificationType;
7542 msg.setData(bundle);
7543 try {
7544 if (VDBG) {
7545 String notification = ConnectivityManager.getCallbackName(notificationType);
7546 log("sending notification " + notification + " for " + nrForCallback);
7547 }
7548 nri.mMessenger.send(msg);
7549 } catch (RemoteException e) {
7550 // may occur naturally in the race of binder death.
7551 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
7552 }
7553 }
7554
7555 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
7556 bundle.putParcelable(t.getClass().getSimpleName(), t);
7557 }
7558
7559 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
7560 if (nai.numRequestNetworkRequests() != 0) {
7561 for (int i = 0; i < nai.numNetworkRequests(); i++) {
7562 NetworkRequest nr = nai.requestAt(i);
7563 // Ignore listening and track default requests.
7564 if (!nr.isRequest()) continue;
7565 loge("Dead network still had at least " + nr);
7566 break;
7567 }
7568 }
7569 nai.disconnect();
7570 }
7571
7572 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
7573 if (oldNetwork == null) {
7574 loge("Unknown NetworkAgentInfo in handleLingerComplete");
7575 return;
7576 }
7577 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
7578
7579 // If we get here it means that the last linger timeout for this network expired. So there
7580 // must be no other active linger timers, and we must stop lingering.
7581 oldNetwork.clearInactivityState();
7582
7583 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
7584 // Tear the network down.
7585 teardownUnneededNetwork(oldNetwork);
7586 } else {
7587 // Put the network in the background if it doesn't satisfy any foreground request.
7588 updateCapabilitiesForNetwork(oldNetwork);
7589 }
7590 }
7591
7592 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
7593 boolean isDefaultChanged = false;
7594 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
7595 final NetworkReassignment.RequestReassignment reassignment =
7596 changes.getReassignment(defaultRequestInfo);
7597 if (null == reassignment) {
7598 continue;
7599 }
7600 // reassignment only contains those instances where the satisfying network changed.
7601 isDefaultChanged = true;
7602 // Notify system services of the new default.
7603 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
7604 }
7605
7606 if (isDefaultChanged) {
7607 // Hold a wakelock for a short time to help apps in migrating to a new default.
7608 scheduleReleaseNetworkTransitionWakelock();
7609 }
7610 }
7611
7612 private void makeDefault(@NonNull final NetworkRequestInfo nri,
7613 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7614 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7615 if (DBG) {
7616 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
7617 }
7618
7619 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
7620 if (newDefaultNetwork != null) {
7621 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
7622 }
7623
7624 // Set an app level managed default and return since further processing only applies to the
7625 // default network.
7626 if (mDefaultRequest != nri) {
7627 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
7628 return;
7629 }
7630
7631 makeDefaultNetwork(newDefaultNetwork);
7632
7633 if (oldDefaultNetwork != null) {
7634 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
7635 }
7636 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
7637 handleApplyDefaultProxy(null != newDefaultNetwork
7638 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
7639 updateTcpBufferSizes(null != newDefaultNetwork
7640 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
7641 notifyIfacesChangedForNetworkStats();
7642 }
7643
7644 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
7645 @Nullable final NetworkAgentInfo oldDefaultNetwork,
7646 @Nullable final NetworkAgentInfo newDefaultNetwork) {
7647 try {
7648 if (VDBG) {
7649 log("Setting default network for " + nri
7650 + " using UIDs " + nri.getUids()
7651 + " with old network " + (oldDefaultNetwork != null
7652 ? oldDefaultNetwork.network().getNetId() : "null")
7653 + " and new network " + (newDefaultNetwork != null
7654 ? newDefaultNetwork.network().getNetId() : "null"));
7655 }
7656 if (nri.getUids().isEmpty()) {
7657 throw new IllegalStateException("makeDefaultForApps called without specifying"
7658 + " any applications to set as the default." + nri);
7659 }
7660 if (null != newDefaultNetwork) {
7661 mNetd.networkAddUidRanges(
7662 newDefaultNetwork.network.getNetId(),
7663 toUidRangeStableParcels(nri.getUids()));
7664 }
7665 if (null != oldDefaultNetwork) {
7666 mNetd.networkRemoveUidRanges(
7667 oldDefaultNetwork.network.getNetId(),
7668 toUidRangeStableParcels(nri.getUids()));
7669 }
7670 } catch (RemoteException | ServiceSpecificException e) {
7671 loge("Exception setting app default network", e);
7672 }
7673 }
7674
7675 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
7676 try {
7677 if (null != newDefaultNetwork) {
7678 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
7679 } else {
7680 mNetd.networkClearDefault();
7681 }
7682 } catch (RemoteException | ServiceSpecificException e) {
7683 loge("Exception setting default network :" + e);
7684 }
7685 }
7686
7687 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
7688 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
7689 processNewlyLostListenRequests(nai);
7690 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
7691 processNewlySatisfiedListenRequests(nai);
7692 }
7693
7694 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
7695 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7696 if (nri.isMultilayerRequest()) {
7697 continue;
7698 }
7699 final NetworkRequest nr = nri.mRequests.get(0);
7700 if (!nr.isListen()) continue;
7701 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
7702 nai.removeRequest(nr.requestId);
7703 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
7704 }
7705 }
7706 }
7707
7708 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
7709 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7710 if (nri.isMultilayerRequest()) {
7711 continue;
7712 }
7713 final NetworkRequest nr = nri.mRequests.get(0);
7714 if (!nr.isListen()) continue;
7715 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
7716 nai.addRequest(nr);
7717 notifyNetworkAvailable(nai, nri);
7718 }
7719 }
7720 }
7721
7722 // An accumulator class to gather the list of changes that result from a rematch.
7723 private static class NetworkReassignment {
7724 static class RequestReassignment {
7725 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
7726 @Nullable public final NetworkRequest mOldNetworkRequest;
7727 @Nullable public final NetworkRequest mNewNetworkRequest;
7728 @Nullable public final NetworkAgentInfo mOldNetwork;
7729 @Nullable public final NetworkAgentInfo mNewNetwork;
7730 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
7731 @Nullable final NetworkRequest oldNetworkRequest,
7732 @Nullable final NetworkRequest newNetworkRequest,
7733 @Nullable final NetworkAgentInfo oldNetwork,
7734 @Nullable final NetworkAgentInfo newNetwork) {
7735 mNetworkRequestInfo = networkRequestInfo;
7736 mOldNetworkRequest = oldNetworkRequest;
7737 mNewNetworkRequest = newNetworkRequest;
7738 mOldNetwork = oldNetwork;
7739 mNewNetwork = newNetwork;
7740 }
7741
7742 public String toString() {
7743 final NetworkRequest requestToShow = null != mNewNetworkRequest
7744 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
7745 return requestToShow.requestId + " : "
7746 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
7747 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
7748 }
7749 }
7750
7751 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
7752
7753 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
7754 return mReassignments;
7755 }
7756
7757 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
7758 if (Build.isDebuggable()) {
7759 // The code is never supposed to add two reassignments of the same request. Make
7760 // sure this stays true, but without imposing this expensive check on all
7761 // reassignments on all user devices.
7762 for (final RequestReassignment existing : mReassignments) {
7763 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
7764 throw new IllegalStateException("Trying to reassign ["
7765 + reassignment + "] but already have ["
7766 + existing + "]");
7767 }
7768 }
7769 }
7770 mReassignments.add(reassignment);
7771 }
7772
7773 // Will return null if this reassignment does not change the network assigned to
7774 // the passed request.
7775 @Nullable
7776 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
7777 for (final RequestReassignment event : getRequestReassignments()) {
7778 if (nri == event.mNetworkRequestInfo) return event;
7779 }
7780 return null;
7781 }
7782
7783 public String toString() {
7784 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
7785 "NetReassign [" /* prefix */, "]" /* suffix */);
7786 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
7787 for (final RequestReassignment rr : getRequestReassignments()) {
7788 sj.add(rr.toString());
7789 }
7790 return sj.toString();
7791 }
7792
7793 public String debugString() {
7794 final StringBuilder sb = new StringBuilder();
7795 sb.append("NetworkReassignment :");
7796 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
7797 for (final RequestReassignment rr : getRequestReassignments()) {
7798 sb.append("\n ").append(rr);
7799 }
7800 return sb.append("\n").toString();
7801 }
7802 }
7803
7804 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
7805 @Nullable final NetworkRequest previousRequest,
7806 @Nullable final NetworkRequest newRequest,
7807 @Nullable final NetworkAgentInfo previousSatisfier,
7808 @Nullable final NetworkAgentInfo newSatisfier,
7809 final long now) {
7810 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
7811 if (VDBG) log("rematch for " + newSatisfier.toShortString());
7812 if (null != previousRequest && null != previousSatisfier) {
7813 if (VDBG || DDBG) {
7814 log(" accepting network in place of " + previousSatisfier.toShortString());
7815 }
7816 previousSatisfier.removeRequest(previousRequest.requestId);
7817 previousSatisfier.lingerRequest(previousRequest.requestId, now);
7818 } else {
7819 if (VDBG || DDBG) log(" accepting network in place of null");
7820 }
7821
7822 // To prevent constantly CPU wake up for nascent timer, if a network comes up
7823 // and immediately satisfies a request then remove the timer. This will happen for
7824 // all networks except in the case of an underlying network for a VCN.
7825 if (newSatisfier.isNascent()) {
7826 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
7827 newSatisfier.unsetInactive();
7828 }
7829
7830 // if newSatisfier is not null, then newRequest may not be null.
7831 newSatisfier.unlingerRequest(newRequest.requestId);
7832 if (!newSatisfier.addRequest(newRequest)) {
7833 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
7834 + newRequest);
7835 }
7836 } else if (null != previousRequest && null != previousSatisfier) {
7837 if (DBG) {
7838 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
7839 + " request " + previousRequest.requestId);
7840 }
7841 previousSatisfier.removeRequest(previousRequest.requestId);
7842 }
7843 nri.setSatisfier(newSatisfier, newRequest);
7844 }
7845
7846 /**
7847 * This function is triggered when something can affect what network should satisfy what
7848 * request, and it computes the network reassignment from the passed collection of requests to
7849 * network match to the one that the system should now have. That data is encoded in an
7850 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
7851 * satisfier.
7852 *
7853 * After the reassignment is computed, it is applied to the state objects.
7854 *
7855 * @param networkRequests the nri objects to evaluate for possible network reassignment
7856 * @return NetworkReassignment listing of proposed network assignment changes
7857 */
7858 @NonNull
7859 private NetworkReassignment computeNetworkReassignment(
7860 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
7861 final NetworkReassignment changes = new NetworkReassignment();
7862
7863 // Gather the list of all relevant agents.
7864 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
7865 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
7866 if (!nai.everConnected) {
7867 continue;
7868 }
7869 nais.add(nai);
7870 }
7871
7872 for (final NetworkRequestInfo nri : networkRequests) {
7873 // Non-multilayer listen requests can be ignored.
7874 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
7875 continue;
7876 }
7877 NetworkAgentInfo bestNetwork = null;
7878 NetworkRequest bestRequest = null;
7879 for (final NetworkRequest req : nri.mRequests) {
7880 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
7881 // Stop evaluating as the highest possible priority request is satisfied.
7882 if (null != bestNetwork) {
7883 bestRequest = req;
7884 break;
7885 }
7886 }
7887 if (null == bestNetwork && isDefaultBlocked(nri)) {
7888 // Remove default networking if disallowed for managed default requests.
7889 bestNetwork = mNoServiceNetwork;
7890 }
7891 if (nri.getSatisfier() != bestNetwork) {
7892 // bestNetwork may be null if no network can satisfy this request.
7893 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
7894 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
7895 }
7896 }
7897 return changes;
7898 }
7899
7900 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
7901 return new HashSet<>(mNetworkRequests.values());
7902 }
7903
7904 /**
7905 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
7906 * being disconnected.
7907 */
7908 private void rematchAllNetworksAndRequests() {
7909 rematchNetworksAndRequests(getNrisFromGlobalRequests());
7910 }
7911
7912 /**
7913 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
7914 * being disconnected.
7915 */
7916 private void rematchNetworksAndRequests(
7917 @NonNull final Set<NetworkRequestInfo> networkRequests) {
7918 ensureRunningOnConnectivityServiceThread();
7919 // TODO: This may be slow, and should be optimized.
7920 final long now = SystemClock.elapsedRealtime();
7921 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
7922 if (VDBG || DDBG) {
7923 log(changes.debugString());
7924 } else if (DBG) {
7925 log(changes.toString()); // Shorter form, only one line of log
7926 }
7927 applyNetworkReassignment(changes, now);
7928 issueNetworkNeeds();
7929 }
7930
7931 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
7932 final long now) {
7933 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
7934
7935 // Since most of the time there are only 0 or 1 background networks, it would probably
7936 // be more efficient to just use an ArrayList here. TODO : measure performance
7937 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
7938 for (final NetworkAgentInfo nai : nais) {
7939 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
7940 }
7941
7942 // First, update the lists of satisfied requests in the network agents. This is necessary
7943 // because some code later depends on this state to be correct, most prominently computing
7944 // the linger status.
7945 for (final NetworkReassignment.RequestReassignment event :
7946 changes.getRequestReassignments()) {
7947 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
7948 event.mOldNetworkRequest, event.mNewNetworkRequest,
7949 event.mOldNetwork, event.mNewNetwork,
7950 now);
7951 }
7952
7953 // Process default network changes if applicable.
7954 processDefaultNetworkChanges(changes);
7955
7956 // Notify requested networks are available after the default net is switched, but
7957 // before LegacyTypeTracker sends legacy broadcasts
7958 for (final NetworkReassignment.RequestReassignment event :
7959 changes.getRequestReassignments()) {
7960 if (null != event.mNewNetwork) {
7961 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
7962 } else {
7963 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
7964 ConnectivityManager.CALLBACK_LOST, 0);
7965 }
7966 }
7967
7968 // Update the inactivity state before processing listen callbacks, because the background
7969 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
7970 // just yet though, because they have to be sent after the listens are processed to keep
7971 // backward compatibility.
7972 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
7973 for (final NetworkAgentInfo nai : nais) {
7974 // Rematching may have altered the inactivity state of some networks, so update all
7975 // inactivity timers. updateInactivityState reads the state from the network agent
7976 // and does nothing if the state has not changed : the source of truth is controlled
7977 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
7978 // have been called while rematching the individual networks above.
7979 if (updateInactivityState(nai, now)) {
7980 inactiveNetworks.add(nai);
7981 }
7982 }
7983
7984 for (final NetworkAgentInfo nai : nais) {
7985 if (!nai.everConnected) continue;
7986 final boolean oldBackground = oldBgNetworks.contains(nai);
7987 // Process listen requests and update capabilities if the background state has
7988 // changed for this network. For consistency with previous behavior, send onLost
7989 // callbacks before onAvailable.
7990 processNewlyLostListenRequests(nai);
7991 if (oldBackground != nai.isBackgroundNetwork()) {
7992 applyBackgroundChangeForRematch(nai);
7993 }
7994 processNewlySatisfiedListenRequests(nai);
7995 }
7996
7997 for (final NetworkAgentInfo nai : inactiveNetworks) {
7998 // For nascent networks, if connecting with no foreground request, skip broadcasting
7999 // LOSING for backward compatibility. This is typical when mobile data connected while
8000 // wifi connected with mobile data always-on enabled.
8001 if (nai.isNascent()) continue;
8002 notifyNetworkLosing(nai, now);
8003 }
8004
8005 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
8006
8007 // Tear down all unneeded networks.
8008 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8009 if (unneeded(nai, UnneededFor.TEARDOWN)) {
8010 if (nai.getInactivityExpiry() > 0) {
8011 // This network has active linger timers and no requests, but is not
8012 // lingering. Linger it.
8013 //
8014 // One way (the only way?) this can happen if this network is unvalidated
8015 // and became unneeded due to another network improving its score to the
8016 // point where this network will no longer be able to satisfy any requests
8017 // even if it validates.
8018 if (updateInactivityState(nai, now)) {
8019 notifyNetworkLosing(nai, now);
8020 }
8021 } else {
8022 if (DBG) log("Reaping " + nai.toShortString());
8023 teardownUnneededNetwork(nai);
8024 }
8025 }
8026 }
8027 }
8028
8029 /**
8030 * Apply a change in background state resulting from rematching networks with requests.
8031 *
8032 * During rematch, a network may change background states by starting to satisfy or stopping
8033 * to satisfy a foreground request. Listens don't count for this. When a network changes
8034 * background states, its capabilities need to be updated and callbacks fired for the
8035 * capability change.
8036 *
8037 * @param nai The network that changed background states
8038 */
8039 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8040 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8041 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8042 updateNetworkPermissions(nai, newNc);
8043 nai.getAndSetNetworkCapabilities(newNc);
8044 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8045 }
8046
8047 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
8048 @NonNull final NetworkReassignment changes,
8049 @NonNull final Collection<NetworkAgentInfo> nais) {
8050 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8051 changes.getReassignment(mDefaultRequest);
8052 final NetworkAgentInfo oldDefaultNetwork =
8053 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8054 final NetworkAgentInfo newDefaultNetwork =
8055 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
8056
8057 if (oldDefaultNetwork != newDefaultNetwork) {
8058 // Maintain the illusion : since the legacy API only understands one network at a time,
8059 // if the default network changed, apps should see a disconnected broadcast for the
8060 // old default network before they see a connected broadcast for the new one.
8061 if (oldDefaultNetwork != null) {
8062 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8063 oldDefaultNetwork, true);
8064 }
8065 if (newDefaultNetwork != null) {
8066 // The new default network can be newly null if and only if the old default
8067 // network doesn't satisfy the default request any more because it lost a
8068 // capability.
8069 mDefaultInetConditionPublished = newDefaultNetwork.lastValidated ? 100 : 0;
8070 mLegacyTypeTracker.add(
8071 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
8072 }
8073 }
8074
8075 // Now that all the callbacks have been sent, send the legacy network broadcasts
8076 // as needed. This is necessary so that legacy requests correctly bind dns
8077 // requests to this network. The legacy users are listening for this broadcast
8078 // and will generally do a dns request so they can ensureRouteToHost and if
8079 // they do that before the callbacks happen they'll use the default network.
8080 //
8081 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8082 // callbacks, but if apps can receive the broadcast before the callback, they still might
8083 // have an inconsistent view of networking.
8084 //
8085 // This *does* introduce a race where if the user uses the new api
8086 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8087 // they may get old info. Reverse this after the old startUsing api is removed.
8088 // This is on top of the multiple intent sequencing referenced in the todo above.
8089 for (NetworkAgentInfo nai : nais) {
8090 if (nai.everConnected) {
8091 addNetworkToLegacyTypeTracker(nai);
8092 }
8093 }
8094 }
8095
8096 private void issueNetworkNeeds() {
8097 ensureRunningOnConnectivityServiceThread();
8098 for (final NetworkOfferInfo noi : mNetworkOffers) {
8099 issueNetworkNeeds(noi);
8100 }
8101 }
8102
8103 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
8104 ensureRunningOnConnectivityServiceThread();
8105 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8106 informOffer(nri, noi.offer, mNetworkRanker);
8107 }
8108 }
8109
8110 /**
8111 * Inform a NetworkOffer about any new situation of a request.
8112 *
8113 * This function handles updates to offers. A number of events may happen that require
8114 * updating the registrant for this offer about the situation :
8115 * • The offer itself was updated. This may lead the offer to no longer being able
8116 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
8117 * or conversely being strengthened enough to beat the satisfier (and therefore
8118 * start being needed)
8119 * • The network satisfying a request changed (including cases where the request
8120 * starts or stops being satisfied). The new network may be a stronger or weaker
8121 * match than the old one, possibly affecting whether the offer is needed.
8122 * • The network satisfying a request updated their score. This may lead the offer
8123 * to no longer be able to beat it if the current satisfier got better, or
8124 * conversely start being a good choice if the current satisfier got weaker.
8125 *
8126 * @param nri The request
8127 * @param offer The offer. This may be an updated offer.
8128 */
8129 private static void informOffer(@NonNull NetworkRequestInfo nri,
8130 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
8131 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
8132 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
8133
8134 // Multi-layer requests have a currently active request, the one being satisfied.
8135 // Since the system will try to bring up a better network than is currently satisfying
8136 // the request, NetworkProviders need to be told the offers matching the requests *above*
8137 // the currently satisfied one are needed, that the ones *below* the satisfied one are
8138 // not needed, and the offer is needed for the active request iff the offer can beat
8139 // the satisfier.
8140 // For non-multilayer requests, the logic above gracefully degenerates to only the
8141 // last case.
8142 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
8143 // providers that the offer is needed for this request, until the active request is found.
8144 // In a second phase, deal with the currently active request. In a third phase, inform
8145 // the providers that offer is unneeded for the remaining requests.
8146
8147 // First phase : inform providers of all requests above the active request.
8148 int i;
8149 for (i = 0; nri.mRequests.size() > i; ++i) {
8150 final NetworkRequest request = nri.mRequests.get(i);
8151 if (activeRequest == request) break; // Found the active request : go to phase 2
8152 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8153 // Since this request is higher-priority than the one currently satisfied, if the
8154 // offer can satisfy it, the provider should try and bring up the network for sure ;
8155 // no need to even ask the ranker – an offer that can satisfy is always better than
8156 // no network. Hence tell the provider so unless it already knew.
8157 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
8158 offer.onNetworkNeeded(request);
8159 }
8160 }
8161
8162 // Second phase : deal with the active request (if any)
8163 if (null != activeRequest && activeRequest.isRequest()) {
8164 final boolean oldNeeded = offer.neededFor(activeRequest);
8165 // An offer is needed if it is currently served by this provider or if this offer
8166 // can beat the current satisfier.
8167 final boolean currentlyServing = satisfier != null
8168 && satisfier.factorySerialNumber == offer.providerId;
8169 final boolean newNeeded = (currentlyServing
8170 || (activeRequest.canBeSatisfiedBy(offer.caps)
8171 && networkRanker.mightBeat(activeRequest, satisfier, offer)));
8172 if (newNeeded != oldNeeded) {
8173 if (newNeeded) {
8174 offer.onNetworkNeeded(activeRequest);
8175 } else {
8176 // The offer used to be able to beat the satisfier. Now it can't.
8177 offer.onNetworkUnneeded(activeRequest);
8178 }
8179 }
8180 }
8181
8182 // Third phase : inform the providers that the offer isn't needed for any request
8183 // below the active one.
8184 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
8185 final NetworkRequest request = nri.mRequests.get(i);
8186 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
8187 // Since this request is lower-priority than the one currently satisfied, if the
8188 // offer can satisfy it, the provider should not try and bring up the network.
8189 // Hence tell the provider so unless it already knew.
8190 if (offer.neededFor(request)) {
8191 offer.onNetworkUnneeded(request);
8192 }
8193 }
8194 }
8195
8196 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
8197 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8198 NetworkRequest nr = nai.requestAt(i);
8199 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
8200 // legacy type tracker filters out repeat adds
8201 mLegacyTypeTracker.add(nr.legacyType, nai);
8202 }
8203 }
8204
8205 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
8206 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
8207 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
8208 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
8209 if (nai.isVPN()) {
8210 mLegacyTypeTracker.add(TYPE_VPN, nai);
8211 }
8212 }
8213
8214 private void updateInetCondition(NetworkAgentInfo nai) {
8215 // Don't bother updating until we've graduated to validated at least once.
8216 if (!nai.everValidated) return;
8217 // For now only update icons for the default connection.
8218 // TODO: Update WiFi and cellular icons separately. b/17237507
8219 if (!isDefaultNetwork(nai)) return;
8220
8221 int newInetCondition = nai.lastValidated ? 100 : 0;
8222 // Don't repeat publish.
8223 if (newInetCondition == mDefaultInetConditionPublished) return;
8224
8225 mDefaultInetConditionPublished = newInetCondition;
8226 sendInetConditionBroadcast(nai.networkInfo);
8227 }
8228
8229 @NonNull
8230 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
8231 final NetworkInfo newInfo = new NetworkInfo(info);
8232 // The suspended and roaming bits are managed in NetworkCapabilities.
8233 final boolean suspended =
8234 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8235 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
8236 // Only override the state with SUSPENDED if the network is currently in CONNECTED
8237 // state. This is because the network could have been suspended before connecting,
8238 // or it could be disconnecting while being suspended, and in both these cases
8239 // the state should not be overridden. Note that the only detailed state that
8240 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
8241 // worry about multiple different substates of CONNECTED.
8242 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
8243 info.getExtraInfo());
8244 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
8245 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
8246 // network agent is created, then goes to suspended, then goes out of suspended without
8247 // ever setting connected. Check if network agent is ever connected to update the state.
8248 newInfo.setDetailedState(nai.everConnected
8249 ? NetworkInfo.DetailedState.CONNECTED
8250 : NetworkInfo.DetailedState.CONNECTING,
8251 info.getReason(),
8252 info.getExtraInfo());
8253 }
8254 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
8255 return newInfo;
8256 }
8257
8258 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
8259 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
8260
8261 final NetworkInfo.State state = newInfo.getState();
8262 NetworkInfo oldInfo = null;
8263 synchronized (networkAgent) {
8264 oldInfo = networkAgent.networkInfo;
8265 networkAgent.networkInfo = newInfo;
8266 }
8267
8268 if (DBG) {
8269 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
8270 + oldInfo.getState() + " to " + state);
8271 }
8272
8273 if (!networkAgent.created
8274 && (state == NetworkInfo.State.CONNECTED
8275 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
8276
8277 // A network that has just connected has zero requests and is thus a foreground network.
8278 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
8279
8280 if (!createNativeNetwork(networkAgent)) return;
8281 if (networkAgent.supportsUnderlyingNetworks()) {
8282 // Initialize the network's capabilities to their starting values according to the
8283 // underlying networks. This ensures that the capabilities are correct before
8284 // anything happens to the network.
8285 updateCapabilitiesForNetwork(networkAgent);
8286 }
8287 networkAgent.created = true;
8288 networkAgent.onNetworkCreated();
8289 }
8290
8291 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
8292 networkAgent.everConnected = true;
8293
8294 // NetworkCapabilities need to be set before sending the private DNS config to
8295 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
8296 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
8297
8298 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
8299 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
8300 null);
8301
8302 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
8303 // command must be sent after updating LinkProperties to maximize chances of
8304 // NetworkMonitor seeing the correct LinkProperties when starting.
8305 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
8306 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
8307 networkAgent.networkMonitor().setAcceptPartialConnectivity();
8308 }
8309 networkAgent.networkMonitor().notifyNetworkConnected(
8310 new LinkProperties(networkAgent.linkProperties,
8311 true /* parcelSensitiveFields */),
8312 networkAgent.networkCapabilities);
8313 scheduleUnvalidatedPrompt(networkAgent);
8314
8315 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
8316 // be communicated to a particular NetworkAgent depends only on the network's immutable,
8317 // capabilities, so it only needs to be done once on initial connect, not every time the
8318 // network's capabilities change. Note that we do this before rematching the network,
8319 // so we could decide to tear it down immediately afterwards. That's fine though - on
8320 // disconnection NetworkAgents should stop any signal strength monitoring they have been
8321 // doing.
8322 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
8323
8324 // Before first rematching networks, put an inactivity timer without any request, this
8325 // allows {@code updateInactivityState} to update the state accordingly and prevent
8326 // tearing down for any {@code unneeded} evaluation in this period.
8327 // Note that the timer will not be rescheduled since the expiry time is
8328 // fixed after connection regardless of the network satisfying other requests or not.
8329 // But it will be removed as soon as the network satisfies a request for the first time.
8330 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
8331 SystemClock.elapsedRealtime(), mNascentDelayMs);
8332 networkAgent.setInactive();
8333
8334 // Consider network even though it is not yet validated.
8335 rematchAllNetworksAndRequests();
8336
8337 // This has to happen after matching the requests, because callbacks are just requests.
8338 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
8339 } else if (state == NetworkInfo.State.DISCONNECTED) {
8340 networkAgent.disconnect();
8341 if (networkAgent.isVPN()) {
8342 updateUids(networkAgent, networkAgent.networkCapabilities, null);
8343 }
8344 disconnectAndDestroyNetwork(networkAgent);
8345 if (networkAgent.isVPN()) {
8346 // As the active or bound network changes for apps, broadcast the default proxy, as
8347 // apps may need to update their proxy data. This is called after disconnecting from
8348 // VPN to make sure we do not broadcast the old proxy data.
8349 // TODO(b/122649188): send the broadcast only to VPN users.
8350 mProxyTracker.sendProxyBroadcast();
8351 }
8352 } else if (networkAgent.created && (oldInfo.getState() == NetworkInfo.State.SUSPENDED ||
8353 state == NetworkInfo.State.SUSPENDED)) {
8354 mLegacyTypeTracker.update(networkAgent);
8355 }
8356 }
8357
8358 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
8359 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
8360 nai.setScore(score);
8361 rematchAllNetworksAndRequests();
8362 }
8363
8364 // Notify only this one new request of the current state. Transfer all the
8365 // current state by calling NetworkCapabilities and LinkProperties callbacks
8366 // so that callers can be guaranteed to have as close to atomicity in state
8367 // transfer as can be supported by this current API.
8368 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
8369 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
8370 if (nri.mPendingIntent != null) {
8371 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
8372 // Attempt no subsequent state pushes where intents are involved.
8373 return;
8374 }
8375
8376 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8377 final boolean metered = nai.networkCapabilities.isMetered();
8378 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
8379 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
8380 getBlockedState(blockedReasons, metered, vpnBlocked));
8381 }
8382
8383 // Notify the requests on this NAI that the network is now lingered.
8384 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
8385 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
8386 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
8387 }
8388
8389 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
8390 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
8391 return vpnBlocked
8392 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
8393 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
8394 }
8395
8396 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
8397 if (blockedReasons == BLOCKED_REASON_NONE) {
8398 mUidBlockedReasons.delete(uid);
8399 } else {
8400 mUidBlockedReasons.put(uid, blockedReasons);
8401 }
8402 }
8403
8404 /**
8405 * Notify of the blocked state apps with a registered callback matching a given NAI.
8406 *
8407 * Unlike other callbacks, blocked status is different between each individual uid. So for
8408 * any given nai, all requests need to be considered according to the uid who filed it.
8409 *
8410 * @param nai The target NetworkAgentInfo.
8411 * @param oldMetered True if the previous network capabilities were metered.
8412 * @param newMetered True if the current network capabilities are metered.
8413 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
8414 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
8415 */
8416 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
8417 boolean newMetered, List<UidRange> oldBlockedUidRanges,
8418 List<UidRange> newBlockedUidRanges) {
8419
8420 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8421 NetworkRequest nr = nai.requestAt(i);
8422 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8423
8424 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
8425 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
8426 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
8427 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
8428 : oldVpnBlocked;
8429
8430 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
8431 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
8432 if (oldBlockedState != newBlockedState) {
8433 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8434 newBlockedState);
8435 }
8436 }
8437 }
8438
8439 /**
8440 * Notify apps with a given UID of the new blocked state according to new uid state.
8441 * @param uid The uid for which the rules changed.
8442 * @param blockedReasons The reasons for why an uid is blocked.
8443 */
8444 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
8445 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8446 final boolean metered = nai.networkCapabilities.isMetered();
8447 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
8448
8449 final int oldBlockedState = getBlockedState(
8450 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
8451 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
8452 if (oldBlockedState == newBlockedState) {
8453 continue;
8454 }
8455 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8456 NetworkRequest nr = nai.requestAt(i);
8457 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8458 if (nri != null && nri.mAsUid == uid) {
8459 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
8460 newBlockedState);
8461 }
8462 }
8463 }
8464 }
8465
8466 @VisibleForTesting
8467 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
8468 // The NetworkInfo we actually send out has no bearing on the real
8469 // state of affairs. For example, if the default connection is mobile,
8470 // and a request for HIPRI has just gone away, we need to pretend that
8471 // HIPRI has just disconnected. So we need to set the type to HIPRI and
8472 // the state to DISCONNECTED, even though the network is of type MOBILE
8473 // and is still connected.
8474 NetworkInfo info = new NetworkInfo(nai.networkInfo);
8475 info.setType(type);
8476 filterForLegacyLockdown(info);
8477 if (state != DetailedState.DISCONNECTED) {
8478 info.setDetailedState(state, null, info.getExtraInfo());
8479 sendConnectedBroadcast(info);
8480 } else {
8481 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
8482 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
8483 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
8484 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
8485 if (info.isFailover()) {
8486 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
8487 nai.networkInfo.setFailover(false);
8488 }
8489 if (info.getReason() != null) {
8490 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
8491 }
8492 if (info.getExtraInfo() != null) {
8493 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
8494 }
8495 NetworkAgentInfo newDefaultAgent = null;
8496 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
8497 newDefaultAgent = mDefaultRequest.getSatisfier();
8498 if (newDefaultAgent != null) {
8499 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
8500 newDefaultAgent.networkInfo);
8501 } else {
8502 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
8503 }
8504 }
8505 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
8506 mDefaultInetConditionPublished);
8507 sendStickyBroadcast(intent);
8508 if (newDefaultAgent != null) {
8509 sendConnectedBroadcast(newDefaultAgent.networkInfo);
8510 }
8511 }
8512 }
8513
8514 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
8515 if (VDBG || DDBG) {
8516 String notification = ConnectivityManager.getCallbackName(notifyType);
8517 log("notifyType " + notification + " for " + networkAgent.toShortString());
8518 }
8519 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
8520 NetworkRequest nr = networkAgent.requestAt(i);
8521 NetworkRequestInfo nri = mNetworkRequests.get(nr);
8522 if (VDBG) log(" sending notification for " + nr);
8523 if (nri.mPendingIntent == null) {
8524 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
8525 } else {
8526 sendPendingIntentForRequest(nri, networkAgent, notifyType);
8527 }
8528 }
8529 }
8530
8531 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
8532 notifyNetworkCallbacks(networkAgent, notifyType, 0);
8533 }
8534
8535 /**
8536 * Returns the list of all interfaces that could be used by network traffic that does not
8537 * explicitly specify a network. This includes the default network, but also all VPNs that are
8538 * currently connected.
8539 *
8540 * Must be called on the handler thread.
8541 */
8542 @NonNull
8543 private ArrayList<Network> getDefaultNetworks() {
8544 ensureRunningOnConnectivityServiceThread();
8545 final ArrayList<Network> defaultNetworks = new ArrayList<>();
8546 final Set<Integer> activeNetIds = new ArraySet<>();
8547 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8548 if (nri.isBeingSatisfied()) {
8549 activeNetIds.add(nri.getSatisfier().network().netId);
8550 }
8551 }
8552 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
8553 if (nai.everConnected && (activeNetIds.contains(nai.network().netId) || nai.isVPN())) {
8554 defaultNetworks.add(nai.network);
8555 }
8556 }
8557 return defaultNetworks;
8558 }
8559
8560 /**
8561 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
8562 * active iface's tracked properties has changed.
8563 */
8564 private void notifyIfacesChangedForNetworkStats() {
8565 ensureRunningOnConnectivityServiceThread();
8566 String activeIface = null;
8567 LinkProperties activeLinkProperties = getActiveLinkProperties();
8568 if (activeLinkProperties != null) {
8569 activeIface = activeLinkProperties.getInterfaceName();
8570 }
8571
8572 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
8573 try {
8574 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
8575 // TODO: Directly use NetworkStateSnapshot when feasible.
8576 for (final NetworkState state : getAllNetworkState()) {
8577 final NetworkStateSnapshot snapshot = new NetworkStateSnapshot(state.network,
8578 state.networkCapabilities, state.linkProperties, state.subscriberId,
8579 state.legacyNetworkType);
8580 snapshots.add(snapshot);
8581 }
8582 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
8583 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
8584 } catch (Exception ignored) {
8585 }
8586 }
8587
8588 @Override
8589 public String getCaptivePortalServerUrl() {
8590 enforceNetworkStackOrSettingsPermission();
8591 String settingUrl = mResources.get().getString(
8592 R.string.config_networkCaptivePortalServerUrl);
8593
8594 if (!TextUtils.isEmpty(settingUrl)) {
8595 return settingUrl;
8596 }
8597
8598 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
8599 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
8600 if (!TextUtils.isEmpty(settingUrl)) {
8601 return settingUrl;
8602 }
8603
8604 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
8605 }
8606
8607 @Override
8608 public void startNattKeepalive(Network network, int intervalSeconds,
8609 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
8610 enforceKeepalivePermission();
8611 mKeepaliveTracker.startNattKeepalive(
8612 getNetworkAgentInfoForNetwork(network), null /* fd */,
8613 intervalSeconds, cb,
8614 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
8615 }
8616
8617 @Override
8618 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
8619 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
8620 String dstAddr) {
8621 try {
8622 final FileDescriptor fd = pfd.getFileDescriptor();
8623 mKeepaliveTracker.startNattKeepalive(
8624 getNetworkAgentInfoForNetwork(network), fd, resourceId,
8625 intervalSeconds, cb,
8626 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
8627 } finally {
8628 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8629 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8630 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8631 IoUtils.closeQuietly(pfd);
8632 }
8633 }
8634 }
8635
8636 @Override
8637 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
8638 ISocketKeepaliveCallback cb) {
8639 try {
8640 enforceKeepalivePermission();
8641 final FileDescriptor fd = pfd.getFileDescriptor();
8642 mKeepaliveTracker.startTcpKeepalive(
8643 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
8644 } finally {
8645 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
8646 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
8647 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
8648 IoUtils.closeQuietly(pfd);
8649 }
8650 }
8651 }
8652
8653 @Override
8654 public void stopKeepalive(Network network, int slot) {
8655 mHandler.sendMessage(mHandler.obtainMessage(
8656 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
8657 }
8658
8659 @Override
8660 public void factoryReset() {
8661 enforceSettingsPermission();
8662
8663 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
8664 return;
8665 }
8666
8667 final long token = Binder.clearCallingIdentity();
8668 try {
8669 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
8670 ipMemoryStore.factoryReset();
8671 } finally {
8672 Binder.restoreCallingIdentity(token);
8673 }
8674
8675 // Turn airplane mode off
8676 setAirplaneMode(false);
8677
8678 // restore private DNS settings to default mode (opportunistic)
8679 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_PRIVATE_DNS)) {
8680 ConnectivitySettingsManager.setPrivateDnsMode(mContext, PRIVATE_DNS_MODE_OPPORTUNISTIC);
8681 }
8682
8683 Settings.Global.putString(mContext.getContentResolver(),
8684 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
8685 }
8686
8687 @Override
8688 public byte[] getNetworkWatchlistConfigHash() {
8689 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
8690 if (nwm == null) {
8691 loge("Unable to get NetworkWatchlistManager");
8692 return null;
8693 }
8694 // Redirect it to network watchlist service to access watchlist file and calculate hash.
8695 return nwm.getWatchlistConfigHash();
8696 }
8697
8698 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
8699 int[] transports = nai.networkCapabilities.getTransportTypes();
8700 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
8701 }
8702
8703 private static boolean toBool(int encodedBoolean) {
8704 return encodedBoolean != 0; // Only 0 means false.
8705 }
8706
8707 private static int encodeBool(boolean b) {
8708 return b ? 1 : 0;
8709 }
8710
8711 @Override
8712 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
8713 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
8714 @NonNull String[] args) {
8715 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
8716 err.getFileDescriptor(), args);
8717 }
8718
8719 private class ShellCmd extends BasicShellCommandHandler {
8720 @Override
8721 public int onCommand(String cmd) {
8722 if (cmd == null) {
8723 return handleDefaultCommands(cmd);
8724 }
8725 final PrintWriter pw = getOutPrintWriter();
8726 try {
8727 switch (cmd) {
8728 case "airplane-mode":
8729 final String action = getNextArg();
8730 if ("enable".equals(action)) {
8731 setAirplaneMode(true);
8732 return 0;
8733 } else if ("disable".equals(action)) {
8734 setAirplaneMode(false);
8735 return 0;
8736 } else if (action == null) {
8737 final ContentResolver cr = mContext.getContentResolver();
8738 final int enabled = Settings.Global.getInt(cr,
8739 Settings.Global.AIRPLANE_MODE_ON);
8740 pw.println(enabled == 0 ? "disabled" : "enabled");
8741 return 0;
8742 } else {
8743 onHelp();
8744 return -1;
8745 }
8746 default:
8747 return handleDefaultCommands(cmd);
8748 }
8749 } catch (Exception e) {
8750 pw.println(e);
8751 }
8752 return -1;
8753 }
8754
8755 @Override
8756 public void onHelp() {
8757 PrintWriter pw = getOutPrintWriter();
8758 pw.println("Connectivity service commands:");
8759 pw.println(" help");
8760 pw.println(" Print this help text.");
8761 pw.println(" airplane-mode [enable|disable]");
8762 pw.println(" Turn airplane mode on or off.");
8763 pw.println(" airplane-mode");
8764 pw.println(" Get airplane mode.");
8765 }
8766 }
8767
8768 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
8769 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
8770 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
8771 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
8772 return ((VpnTransportInfo) ti).getType();
8773 }
8774
8775 /**
8776 * @param connectionInfo the connection to resolve.
8777 * @return {@code uid} if the connection is found and the app has permission to observe it
8778 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
8779 * connection is not found.
8780 */
8781 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
8782 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
8783 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
8784 }
8785
8786 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
8787 connectionInfo.local, connectionInfo.remote);
8788
8789 if (uid == INVALID_UID) return uid; // Not found.
8790
8791 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
8792 // VPN, if any, that applies to the UID that owns the connection.
8793 if (checkNetworkStackPermission()) return uid;
8794
8795 final NetworkAgentInfo vpn = getVpnForUid(uid);
8796 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
8797 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
8798 return INVALID_UID;
8799 }
8800
8801 return uid;
8802 }
8803
8804 /**
8805 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
8806 *
8807 * <p>The TestNetworkService must be run in the system server due to TUN creation.
8808 */
8809 @Override
8810 public IBinder startOrGetTestNetworkService() {
8811 synchronized (mTNSLock) {
8812 TestNetworkService.enforceTestNetworkPermissions(mContext);
8813
8814 if (mTNS == null) {
8815 mTNS = new TestNetworkService(mContext);
8816 }
8817
8818 return mTNS;
8819 }
8820 }
8821
8822 /**
8823 * Handler used for managing all Connectivity Diagnostics related functions.
8824 *
8825 * @see android.net.ConnectivityDiagnosticsManager
8826 *
8827 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
8828 */
8829 @VisibleForTesting
8830 class ConnectivityDiagnosticsHandler extends Handler {
8831 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
8832
8833 /**
8834 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
8835 * android.net.ConnectivityDiagnosticsManager}.
8836 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
8837 * NetworkRequestInfo to be registered
8838 */
8839 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
8840
8841 /**
8842 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
8843 * android.net.ConnectivityDiagnosticsManager}.
8844 * obj = the IConnectivityDiagnosticsCallback to be unregistered
8845 * arg1 = the uid of the caller
8846 */
8847 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
8848
8849 /**
8850 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
8851 * after processing {@link #EVENT_NETWORK_TESTED} events.
8852 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
8853 * NetworkMonitor.
8854 * data = PersistableBundle of extras passed from NetworkMonitor.
8855 *
8856 * <p>See {@link ConnectivityService#EVENT_NETWORK_TESTED}.
8857 */
8858 private static final int EVENT_NETWORK_TESTED = ConnectivityService.EVENT_NETWORK_TESTED;
8859
8860 /**
8861 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
8862 * been detected on the network.
8863 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
8864 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
8865 * arg2 = NetID.
8866 * data = PersistableBundle of extras passed from NetworkMonitor.
8867 */
8868 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
8869
8870 /**
8871 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
8872 * the platform. This event will invoke {@link
8873 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
8874 * callbacks.
8875 * obj = Network that was reported on
8876 * arg1 = boolint for the quality reported
8877 */
8878 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
8879
8880 private ConnectivityDiagnosticsHandler(Looper looper) {
8881 super(looper);
8882 }
8883
8884 @Override
8885 public void handleMessage(Message msg) {
8886 switch (msg.what) {
8887 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8888 handleRegisterConnectivityDiagnosticsCallback(
8889 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
8890 break;
8891 }
8892 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
8893 handleUnregisterConnectivityDiagnosticsCallback(
8894 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
8895 break;
8896 }
8897 case EVENT_NETWORK_TESTED: {
8898 final ConnectivityReportEvent reportEvent =
8899 (ConnectivityReportEvent) msg.obj;
8900
8901 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
8902 break;
8903 }
8904 case EVENT_DATA_STALL_SUSPECTED: {
8905 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
8906 final Pair<Long, PersistableBundle> arg =
8907 (Pair<Long, PersistableBundle>) msg.obj;
8908 if (nai == null) break;
8909
8910 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
8911 break;
8912 }
8913 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
8914 handleNetworkConnectivityReported((NetworkAgentInfo) msg.obj, toBool(msg.arg1));
8915 break;
8916 }
8917 default: {
8918 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
8919 }
8920 }
8921 }
8922 }
8923
8924 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
8925 @VisibleForTesting
8926 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
8927 @NonNull private final IConnectivityDiagnosticsCallback mCb;
8928 @NonNull private final NetworkRequestInfo mRequestInfo;
8929 @NonNull private final String mCallingPackageName;
8930
8931 @VisibleForTesting
8932 ConnectivityDiagnosticsCallbackInfo(
8933 @NonNull IConnectivityDiagnosticsCallback cb,
8934 @NonNull NetworkRequestInfo nri,
8935 @NonNull String callingPackageName) {
8936 mCb = cb;
8937 mRequestInfo = nri;
8938 mCallingPackageName = callingPackageName;
8939 }
8940
8941 @Override
8942 public void binderDied() {
8943 log("ConnectivityDiagnosticsCallback IBinder died.");
8944 unregisterConnectivityDiagnosticsCallback(mCb);
8945 }
8946 }
8947
8948 /**
8949 * Class used for sending information from {@link
8950 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
8951 */
8952 private static class NetworkTestedResults {
8953 private final int mNetId;
8954 private final int mTestResult;
8955 private final long mTimestampMillis;
8956 @Nullable private final String mRedirectUrl;
8957
8958 private NetworkTestedResults(
8959 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
8960 mNetId = netId;
8961 mTestResult = testResult;
8962 mTimestampMillis = timestampMillis;
8963 mRedirectUrl = redirectUrl;
8964 }
8965 }
8966
8967 /**
8968 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
8969 * ConnectivityDiagnosticsHandler}.
8970 */
8971 private static class ConnectivityReportEvent {
8972 private final long mTimestampMillis;
8973 @NonNull private final NetworkAgentInfo mNai;
8974 private final PersistableBundle mExtras;
8975
8976 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
8977 PersistableBundle p) {
8978 mTimestampMillis = timestampMillis;
8979 mNai = nai;
8980 mExtras = p;
8981 }
8982 }
8983
8984 private void handleRegisterConnectivityDiagnosticsCallback(
8985 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
8986 ensureRunningOnConnectivityServiceThread();
8987
8988 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
8989 final IBinder iCb = cb.asBinder();
8990 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
8991
8992 // Connectivity Diagnostics are meant to be used with a single network request. It would be
8993 // confusing for these networks to change when an NRI is satisfied in another layer.
8994 if (nri.isMultilayerRequest()) {
8995 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
8996 + "network requests.");
8997 }
8998
8999 // This means that the client registered the same callback multiple times. Do
9000 // not override the previous entry, and exit silently.
9001 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
9002 if (VDBG) log("Diagnostics callback is already registered");
9003
9004 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9005 // incremented when the NetworkRequestInfo is created as part of
9006 // enforceRequestCountLimit().
9007 nri.decrementRequestCount();
9008 return;
9009 }
9010
9011 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
9012
9013 try {
9014 iCb.linkToDeath(cbInfo, 0);
9015 } catch (RemoteException e) {
9016 cbInfo.binderDied();
9017 return;
9018 }
9019
9020 // Once registered, provide ConnectivityReports for matching Networks
9021 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9022 synchronized (mNetworkForNetId) {
9023 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9024 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
9025 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9026 if (nai.satisfies(nri.mRequests.get(0))) {
9027 matchingNetworks.add(nai);
9028 }
9029 }
9030 }
9031 for (final NetworkAgentInfo nai : matchingNetworks) {
9032 final ConnectivityReport report = nai.getConnectivityReport();
9033 if (report == null) {
9034 continue;
9035 }
9036 if (!checkConnectivityDiagnosticsPermissions(
9037 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9038 continue;
9039 }
9040
9041 try {
9042 cb.onConnectivityReportAvailable(report);
9043 } catch (RemoteException e) {
9044 // Exception while sending the ConnectivityReport. Move on to the next network.
9045 }
9046 }
9047 }
9048
9049 private void handleUnregisterConnectivityDiagnosticsCallback(
9050 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
9051 ensureRunningOnConnectivityServiceThread();
9052 final IBinder iCb = cb.asBinder();
9053
9054 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9055 mConnectivityDiagnosticsCallbacks.remove(iCb);
9056 if (cbInfo == null) {
9057 if (VDBG) log("Removing diagnostics callback that is not currently registered");
9058 return;
9059 }
9060
9061 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9062
9063 // Caller's UID must either be the registrants (if they are unregistering) or the System's
9064 // (if the Binder died)
9065 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
9066 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
9067 return;
9068 }
9069
9070 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9071 // incremented when the NetworkRequestInfo is created as part of
9072 // enforceRequestCountLimit().
9073 nri.decrementRequestCount();
9074
9075 iCb.unlinkToDeath(cbInfo, 0);
9076 }
9077
9078 private void handleNetworkTestedWithExtras(
9079 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
9080 final NetworkAgentInfo nai = reportEvent.mNai;
9081 final NetworkCapabilities networkCapabilities =
9082 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9083 final ConnectivityReport report =
9084 new ConnectivityReport(
9085 reportEvent.mNai.network,
9086 reportEvent.mTimestampMillis,
9087 nai.linkProperties,
9088 networkCapabilities,
9089 extras);
9090 nai.setConnectivityReport(report);
9091 final List<IConnectivityDiagnosticsCallback> results =
9092 getMatchingPermissionedCallbacks(nai);
9093 for (final IConnectivityDiagnosticsCallback cb : results) {
9094 try {
9095 cb.onConnectivityReportAvailable(report);
9096 } catch (RemoteException ex) {
9097 loge("Error invoking onConnectivityReport", ex);
9098 }
9099 }
9100 }
9101
9102 private void handleDataStallSuspected(
9103 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
9104 @NonNull PersistableBundle extras) {
9105 final NetworkCapabilities networkCapabilities =
9106 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
9107 final DataStallReport report =
9108 new DataStallReport(
9109 nai.network,
9110 timestampMillis,
9111 detectionMethod,
9112 nai.linkProperties,
9113 networkCapabilities,
9114 extras);
9115 final List<IConnectivityDiagnosticsCallback> results =
9116 getMatchingPermissionedCallbacks(nai);
9117 for (final IConnectivityDiagnosticsCallback cb : results) {
9118 try {
9119 cb.onDataStallSuspected(report);
9120 } catch (RemoteException ex) {
9121 loge("Error invoking onDataStallSuspected", ex);
9122 }
9123 }
9124 }
9125
9126 private void handleNetworkConnectivityReported(
9127 @NonNull NetworkAgentInfo nai, boolean connectivity) {
9128 final List<IConnectivityDiagnosticsCallback> results =
9129 getMatchingPermissionedCallbacks(nai);
9130 for (final IConnectivityDiagnosticsCallback cb : results) {
9131 try {
9132 cb.onNetworkConnectivityReported(nai.network, connectivity);
9133 } catch (RemoteException ex) {
9134 loge("Error invoking onNetworkConnectivityReported", ex);
9135 }
9136 }
9137 }
9138
9139 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
9140 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
9141 NetworkCapabilities.REDACT_ALL);
9142 sanitized.setUids(null);
9143 sanitized.setAdministratorUids(new int[0]);
9144 sanitized.setOwnerUid(Process.INVALID_UID);
9145 return sanitized;
9146 }
9147
9148 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
9149 @NonNull NetworkAgentInfo nai) {
9150 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
9151 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
9152 mConnectivityDiagnosticsCallbacks.entrySet()) {
9153 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
9154 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9155 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
9156 if (nai.satisfies(nri.mRequests.get(0))) {
9157 if (checkConnectivityDiagnosticsPermissions(
9158 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
9159 results.add(entry.getValue().mCb);
9160 }
9161 }
9162 }
9163 return results;
9164 }
9165
9166 @VisibleForTesting
9167 boolean checkConnectivityDiagnosticsPermissions(
9168 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
9169 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
9170 return true;
9171 }
9172
9173 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
9174 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
9175 // call in a try-catch.
9176 try {
9177 if (!mLocationPermissionChecker.checkLocationPermission(
9178 callbackPackageName, null /* featureId */, callbackUid, null /* message */)) {
9179 return false;
9180 }
9181 } catch (SecurityException e) {
9182 return false;
9183 }
9184
9185 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
9186 if (virtual.supportsUnderlyingNetworks()
9187 && virtual.networkCapabilities.getOwnerUid() == callbackUid
9188 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, nai.network)) {
9189 return true;
9190 }
9191 }
9192
9193 // Administrator UIDs also contains the Owner UID
9194 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
9195 return CollectionUtils.contains(administratorUids, callbackUid);
9196 }
9197
9198 @Override
9199 public void registerConnectivityDiagnosticsCallback(
9200 @NonNull IConnectivityDiagnosticsCallback callback,
9201 @NonNull NetworkRequest request,
9202 @NonNull String callingPackageName) {
9203 if (request.legacyType != TYPE_NONE) {
9204 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
9205 + " Please use NetworkCapabilities instead.");
9206 }
9207 final int callingUid = mDeps.getCallingUid();
9208 mAppOpsManager.checkPackage(callingUid, callingPackageName);
9209
9210 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
9211 // and administrator uids to be safe.
9212 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
9213 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
9214
9215 final NetworkRequest requestWithId =
9216 new NetworkRequest(
9217 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
9218
9219 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
9220 //
9221 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
9222 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
9223 // callback's binder death.
9224 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
9225 final ConnectivityDiagnosticsCallbackInfo cbInfo =
9226 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
9227
9228 mConnectivityDiagnosticsHandler.sendMessage(
9229 mConnectivityDiagnosticsHandler.obtainMessage(
9230 ConnectivityDiagnosticsHandler
9231 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9232 cbInfo));
9233 }
9234
9235 @Override
9236 public void unregisterConnectivityDiagnosticsCallback(
9237 @NonNull IConnectivityDiagnosticsCallback callback) {
9238 Objects.requireNonNull(callback, "callback must be non-null");
9239 mConnectivityDiagnosticsHandler.sendMessage(
9240 mConnectivityDiagnosticsHandler.obtainMessage(
9241 ConnectivityDiagnosticsHandler
9242 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
9243 mDeps.getCallingUid(),
9244 0,
9245 callback));
9246 }
9247
9248 @Override
9249 public void simulateDataStall(int detectionMethod, long timestampMillis,
9250 @NonNull Network network, @NonNull PersistableBundle extras) {
9251 enforceAnyPermissionOf(android.Manifest.permission.MANAGE_TEST_NETWORKS,
9252 android.Manifest.permission.NETWORK_STACK);
9253 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
9254 if (!nc.hasTransport(TRANSPORT_TEST)) {
9255 throw new SecurityException("Data Stall simluation is only possible for test networks");
9256 }
9257
9258 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
9259 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
9260 throw new SecurityException("Data Stall simulation is only possible for network "
9261 + "creators");
9262 }
9263
9264 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
9265 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
9266 // Data Stall information as a DataStallReportParcelable and passing to
9267 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
9268 // still passed to ConnectivityDiagnostics (with new detection methods masked).
9269 final DataStallReportParcelable p = new DataStallReportParcelable();
9270 p.timestampMillis = timestampMillis;
9271 p.detectionMethod = detectionMethod;
9272
9273 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
9274 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
9275 }
9276 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
9277 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
9278 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
9279 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
9280 }
9281
9282 notifyDataStallSuspected(p, network.getNetId());
9283 }
9284
9285 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
9286 @Override
9287 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
9288 long timestampNs, int uid) {
9289 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
9290 }
9291
9292 @Override
9293 public void onInterfaceLinkStateChanged(String iface, boolean up) {
9294 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9295 nai.clatd.interfaceLinkStateChanged(iface, up);
9296 }
9297 }
9298
9299 @Override
9300 public void onInterfaceRemoved(String iface) {
9301 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
9302 nai.clatd.interfaceRemoved(iface);
9303 }
9304 }
9305 }
9306
9307 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
9308
9309 /**
9310 * Class used for updating network activity tracking with netd and notify network activity
9311 * changes.
9312 */
9313 private static final class LegacyNetworkActivityTracker {
9314 private static final int NO_UID = -1;
9315 private final Context mContext;
9316 private final INetd mNetd;
9317 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
9318 new RemoteCallbackList<>();
9319 // Indicate the current system default network activity is active or not.
9320 @GuardedBy("mActiveIdleTimers")
9321 private boolean mNetworkActive;
9322 @GuardedBy("mActiveIdleTimers")
9323 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap();
9324 private final Handler mHandler;
9325
9326 private class IdleTimerParams {
9327 public final int timeout;
9328 public final int transportType;
9329
9330 IdleTimerParams(int timeout, int transport) {
9331 this.timeout = timeout;
9332 this.transportType = transport;
9333 }
9334 }
9335
9336 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
9337 @NonNull INetd netd) {
9338 mContext = context;
9339 mNetd = netd;
9340 mHandler = handler;
9341 }
9342
9343 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
9344 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
9345 synchronized (mActiveIdleTimers) {
9346 mNetworkActive = active;
9347 // If there are no idle timers, it means that system is not monitoring
9348 // activity, so the system default network for those default network
9349 // unspecified apps is always considered active.
9350 //
9351 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
9352 // any network activity change event. Whenever this event is received,
9353 // the mActiveIdleTimers should be always not empty. The legacy behavior
9354 // is no-op. Remove to refer to mNetworkActive only.
9355 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
9356 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
9357 }
9358 }
9359 }
9360
9361 // The network activity should only be updated from ConnectivityService handler thread
9362 // when mActiveIdleTimers lock is held.
9363 @GuardedBy("mActiveIdleTimers")
9364 private void reportNetworkActive() {
9365 final int length = mNetworkActivityListeners.beginBroadcast();
9366 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
9367 try {
9368 for (int i = 0; i < length; i++) {
9369 try {
9370 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
9371 } catch (RemoteException | RuntimeException e) {
9372 loge("Fail to send network activie to listener " + e);
9373 }
9374 }
9375 } finally {
9376 mNetworkActivityListeners.finishBroadcast();
9377 }
9378 }
9379
9380 @GuardedBy("mActiveIdleTimers")
9381 public void handleReportNetworkActivity() {
9382 synchronized (mActiveIdleTimers) {
9383 reportNetworkActive();
9384 }
9385 }
9386
9387 // This is deprecated and only to support legacy use cases.
9388 private int transportTypeToLegacyType(int type) {
9389 switch (type) {
9390 case NetworkCapabilities.TRANSPORT_CELLULAR:
9391 return TYPE_MOBILE;
9392 case NetworkCapabilities.TRANSPORT_WIFI:
9393 return TYPE_WIFI;
9394 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
9395 return TYPE_BLUETOOTH;
9396 case NetworkCapabilities.TRANSPORT_ETHERNET:
9397 return TYPE_ETHERNET;
9398 default:
9399 loge("Unexpected transport in transportTypeToLegacyType: " + type);
9400 }
9401 return ConnectivityManager.TYPE_NONE;
9402 }
9403
9404 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
9405 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
9406 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
9407 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
9408 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
9409 final long ident = Binder.clearCallingIdentity();
9410 try {
9411 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
9412 RECEIVE_DATA_ACTIVITY_CHANGE,
9413 null /* resultReceiver */,
9414 null /* scheduler */,
9415 0 /* initialCode */,
9416 null /* initialData */,
9417 null /* initialExtra */);
9418 } finally {
9419 Binder.restoreCallingIdentity(ident);
9420 }
9421 }
9422
9423 /**
9424 * Setup data activity tracking for the given network.
9425 *
9426 * Every {@code setupDataActivityTracking} should be paired with a
9427 * {@link #removeDataActivityTracking} for cleanup.
9428 */
9429 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
9430 final String iface = networkAgent.linkProperties.getInterfaceName();
9431
9432 final int timeout;
9433 final int type;
9434
9435 if (networkAgent.networkCapabilities.hasTransport(
9436 NetworkCapabilities.TRANSPORT_CELLULAR)) {
9437 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9438 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
9439 10);
9440 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9441 } else if (networkAgent.networkCapabilities.hasTransport(
9442 NetworkCapabilities.TRANSPORT_WIFI)) {
9443 timeout = Settings.Global.getInt(mContext.getContentResolver(),
9444 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
9445 15);
9446 type = NetworkCapabilities.TRANSPORT_WIFI;
9447 } else {
9448 return; // do not track any other networks
9449 }
9450
9451 updateRadioPowerState(true /* isActive */, type);
9452
9453 if (timeout > 0 && iface != null) {
9454 try {
9455 synchronized (mActiveIdleTimers) {
9456 // Networks start up.
9457 mNetworkActive = true;
9458 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
9459 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
9460 reportNetworkActive();
9461 }
9462 } catch (Exception e) {
9463 // You shall not crash!
9464 loge("Exception in setupDataActivityTracking " + e);
9465 }
9466 }
9467 }
9468
9469 /**
9470 * Remove data activity tracking when network disconnects.
9471 */
9472 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
9473 final String iface = networkAgent.linkProperties.getInterfaceName();
9474 final NetworkCapabilities caps = networkAgent.networkCapabilities;
9475
9476 if (iface == null) return;
9477
9478 final int type;
9479 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
9480 type = NetworkCapabilities.TRANSPORT_CELLULAR;
9481 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
9482 type = NetworkCapabilities.TRANSPORT_WIFI;
9483 } else {
9484 return; // do not track any other networks
9485 }
9486
9487 try {
9488 updateRadioPowerState(false /* isActive */, type);
9489 synchronized (mActiveIdleTimers) {
9490 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
9491 // The call fails silently if no idle timer setup for this interface
9492 mNetd.idletimerRemoveInterface(iface, params.timeout,
9493 Integer.toString(params.transportType));
9494 }
9495 } catch (Exception e) {
9496 // You shall not crash!
9497 loge("Exception in removeDataActivityTracking " + e);
9498 }
9499 }
9500
9501 /**
9502 * Update data activity tracking when network state is updated.
9503 */
9504 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
9505 NetworkAgentInfo oldNetwork) {
9506 if (newNetwork != null) {
9507 setupDataActivityTracking(newNetwork);
9508 }
9509 if (oldNetwork != null) {
9510 removeDataActivityTracking(oldNetwork);
9511 }
9512 }
9513
9514 private void updateRadioPowerState(boolean isActive, int transportType) {
9515 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
9516 switch (transportType) {
9517 case NetworkCapabilities.TRANSPORT_CELLULAR:
9518 bs.reportMobileRadioPowerState(isActive, NO_UID);
9519 break;
9520 case NetworkCapabilities.TRANSPORT_WIFI:
9521 bs.reportWifiRadioPowerState(isActive, NO_UID);
9522 break;
9523 default:
9524 logw("Untracked transport type:" + transportType);
9525 }
9526 }
9527
9528 public boolean isDefaultNetworkActive() {
9529 synchronized (mActiveIdleTimers) {
9530 // If there are no idle timers, it means that system is not monitoring activity,
9531 // so the default network is always considered active.
9532 //
9533 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
9534 // tracking is disabled (negative idle timer value configured), or no active default
9535 // network. In the latter case, this reports active but it should report inactive.
9536 return mNetworkActive || mActiveIdleTimers.isEmpty();
9537 }
9538 }
9539
9540 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
9541 mNetworkActivityListeners.register(l);
9542 }
9543
9544 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
9545 mNetworkActivityListeners.unregister(l);
9546 }
9547
9548 public void dump(IndentingPrintWriter pw) {
9549 synchronized (mActiveIdleTimers) {
9550 pw.print("mNetworkActive="); pw.println(mNetworkActive);
9551 pw.println("Idle timers:");
9552 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
9553 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
9554 final IdleTimerParams params = ent.getValue();
9555 pw.print(" timeout="); pw.print(params.timeout);
9556 pw.print(" type="); pw.println(params.transportType);
9557 }
9558 }
9559 }
9560 }
9561
9562 /**
9563 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
9564 *
9565 * @param socketInfo the socket information
9566 * @param callback the callback to register
9567 */
9568 @Override
9569 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
9570 @NonNull final IQosCallback callback) {
9571 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
9572 if (nai == null || nai.networkCapabilities == null) {
9573 try {
9574 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
9575 } catch (final RemoteException ex) {
9576 loge("registerQosCallbackInternal: RemoteException", ex);
9577 }
9578 return;
9579 }
9580 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
9581 }
9582
9583 /**
9584 * Register a {@link IQosCallback} with base {@link QosFilter}.
9585 *
9586 * @param filter the filter to register
9587 * @param callback the callback to register
9588 * @param nai the agent information related to the filter's network
9589 */
9590 @VisibleForTesting
9591 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
9592 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
9593 if (filter == null) throw new IllegalArgumentException("filter must be non-null");
9594 if (callback == null) throw new IllegalArgumentException("callback must be non-null");
9595
9596 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
9597 enforceConnectivityRestrictedNetworksPermission();
9598 }
9599 mQosCallbackTracker.registerCallback(callback, filter, nai);
9600 }
9601
9602 /**
9603 * Unregisters the given callback.
9604 *
9605 * @param callback the callback to unregister
9606 */
9607 @Override
9608 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
9609 Objects.requireNonNull(callback, "callback must be non-null");
9610 mQosCallbackTracker.unregisterCallback(callback);
9611 }
9612
9613 // Network preference per-profile and OEM network preferences can't be set at the same
9614 // time, because it is unclear what should happen if both preferences are active for
9615 // one given UID. To make it possible, the stack would have to clarify what would happen
9616 // in case both are active at the same time. The implementation may have to be adjusted
9617 // to implement the resulting rules. For example, a priority could be defined between them,
9618 // where the OEM preference would be considered less or more important than the enterprise
9619 // preference ; this would entail implementing the priorities somehow, e.g. by doing
9620 // UID arithmetic with UID ranges or passing a priority to netd so that the routing rules
9621 // are set at the right level. Other solutions are possible, e.g. merging of the
9622 // preferences for the relevant UIDs.
9623 private static void throwConcurrentPreferenceException() {
9624 throw new IllegalStateException("Can't set NetworkPreferenceForUser and "
9625 + "set OemNetworkPreference at the same time");
9626 }
9627
9628 /**
9629 * Request that a user profile is put by default on a network matching a given preference.
9630 *
9631 * See the documentation for the individual preferences for a description of the supported
9632 * behaviors.
9633 *
9634 * @param profile the profile concerned.
9635 * @param preference the preference for this profile, as one of the PROFILE_NETWORK_PREFERENCE_*
9636 * constants.
9637 * @param listener an optional listener to listen for completion of the operation.
9638 */
9639 @Override
9640 public void setProfileNetworkPreference(@NonNull final UserHandle profile,
9641 @ConnectivityManager.ProfileNetworkPreference final int preference,
9642 @Nullable final IOnCompleteListener listener) {
9643 Objects.requireNonNull(profile);
9644 PermissionUtils.enforceNetworkStackPermission(mContext);
9645 if (DBG) {
9646 log("setProfileNetworkPreference " + profile + " to " + preference);
9647 }
9648 if (profile.getIdentifier() < 0) {
9649 throw new IllegalArgumentException("Must explicitly specify a user handle ("
9650 + "UserHandle.CURRENT not supported)");
9651 }
9652 final UserManager um = mContext.getSystemService(UserManager.class);
9653 if (!um.isManagedProfile(profile.getIdentifier())) {
9654 throw new IllegalArgumentException("Profile must be a managed profile");
9655 }
9656 // Strictly speaking, mOemNetworkPreferences should only be touched on the
9657 // handler thread. However it is an immutable object, so reading the reference is
9658 // safe - it's just possible the value is slightly outdated. For the final check,
9659 // see #handleSetProfileNetworkPreference. But if this can be caught here it is a
9660 // lot easier to understand, so opportunistically check it.
9661 if (!mOemNetworkPreferences.isEmpty()) {
9662 throwConcurrentPreferenceException();
9663 }
9664 final NetworkCapabilities nc;
9665 switch (preference) {
9666 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
9667 nc = null;
9668 break;
9669 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
9670 final UidRange uids = UidRange.createForUser(profile);
9671 nc = createDefaultNetworkCapabilitiesForUidRange(uids);
9672 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
9673 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
9674 break;
9675 default:
9676 throw new IllegalArgumentException(
9677 "Invalid preference in setProfileNetworkPreference");
9678 }
9679 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
9680 new Pair<>(new ProfileNetworkPreferences.Preference(profile, nc), listener)));
9681 }
9682
9683 private void validateNetworkCapabilitiesOfProfileNetworkPreference(
9684 @Nullable final NetworkCapabilities nc) {
9685 if (null == nc) return; // Null caps are always allowed. It means to remove the setting.
9686 ensureRequestableCapabilities(nc);
9687 }
9688
9689 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
9690 @NonNull final ProfileNetworkPreferences prefs) {
9691 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
9692 for (final ProfileNetworkPreferences.Preference pref : prefs.preferences) {
9693 // The NRI for a user should be comprised of two layers:
9694 // - The request for the capabilities
9695 // - The request for the default network, for fallback. Create an image of it to
9696 // have the correct UIDs in it (also a request can only be part of one NRI, because
9697 // of lookups in 1:1 associations like mNetworkRequests).
9698 // Note that denying a fallback can be implemented simply by not adding the second
9699 // request.
9700 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
9701 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
9702 nrs.add(createDefaultInternetRequestForTransport(
9703 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
9704 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
9705 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs);
9706 result.add(nri);
9707 }
9708 return result;
9709 }
9710
9711 private void handleSetProfileNetworkPreference(
9712 @NonNull final ProfileNetworkPreferences.Preference preference,
9713 @Nullable final IOnCompleteListener listener) {
9714 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9715 // particular because it's not clear what preference should win in case both apply
9716 // to the same app.
9717 // The binder call has already checked this, but as mOemNetworkPreferences is only
9718 // touched on the handler thread, it's theoretically not impossible that it has changed
9719 // since.
9720 if (!mOemNetworkPreferences.isEmpty()) {
9721 // This may happen on a device with an OEM preference set when a user is removed.
9722 // In this case, it's safe to ignore. In particular this happens in the tests.
9723 loge("handleSetProfileNetworkPreference, but OEM network preferences not empty");
9724 return;
9725 }
9726
9727 validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
9728
9729 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
9730 mSystemNetworkRequestCounter.transact(
9731 mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
9732 () -> {
9733 final ArraySet<NetworkRequestInfo> nris =
9734 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
9735 replaceDefaultNetworkRequestsForPreference(nris);
9736 });
9737 // Finally, rematch.
9738 rematchAllNetworksAndRequests();
9739
9740 if (null != listener) {
9741 try {
9742 listener.onComplete();
9743 } catch (RemoteException e) {
9744 loge("Listener for setProfileNetworkPreference has died");
9745 }
9746 }
9747 }
9748
9749 private void enforceAutomotiveDevice() {
9750 final boolean isAutomotiveDevice =
9751 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
9752 if (!isAutomotiveDevice) {
9753 throw new UnsupportedOperationException(
9754 "setOemNetworkPreference() is only available on automotive devices.");
9755 }
9756 }
9757
9758 /**
9759 * Used by automotive devices to set the network preferences used to direct traffic at an
9760 * application level as per the given OemNetworkPreferences. An example use-case would be an
9761 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
9762 * vehicle via a particular network.
9763 *
9764 * Calling this will overwrite the existing preference.
9765 *
9766 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
9767 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
9768 * to communicate completion of setOemNetworkPreference();
9769 */
9770 @Override
9771 public void setOemNetworkPreference(
9772 @NonNull final OemNetworkPreferences preference,
9773 @Nullable final IOnCompleteListener listener) {
9774
9775 enforceAutomotiveDevice();
9776 enforceOemNetworkPreferencesPermission();
9777
9778 if (!mProfileNetworkPreferences.isEmpty()) {
9779 // Strictly speaking, mProfileNetworkPreferences should only be touched on the
9780 // handler thread. However it is an immutable object, so reading the reference is
9781 // safe - it's just possible the value is slightly outdated. For the final check,
9782 // see #handleSetOemPreference. But if this can be caught here it is a
9783 // lot easier to understand, so opportunistically check it.
9784 throwConcurrentPreferenceException();
9785 }
9786
9787 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9788 validateOemNetworkPreferences(preference);
9789 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
9790 new Pair<>(preference, listener)));
9791 }
9792
9793 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
9794 for (@OemNetworkPreferences.OemNetworkPreference final int pref
9795 : preference.getNetworkPreferences().values()) {
9796 if (OemNetworkPreferences.OEM_NETWORK_PREFERENCE_UNINITIALIZED == pref) {
9797 final String msg = "OEM_NETWORK_PREFERENCE_UNINITIALIZED is an invalid value.";
9798 throw new IllegalArgumentException(msg);
9799 }
9800 }
9801 }
9802
9803 private void handleSetOemNetworkPreference(
9804 @NonNull final OemNetworkPreferences preference,
9805 @Nullable final IOnCompleteListener listener) {
9806 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
9807 if (DBG) {
9808 log("set OEM network preferences :" + preference.toString());
9809 }
9810 // setProfileNetworkPreference and setOemNetworkPreference are mutually exclusive, in
9811 // particular because it's not clear what preference should win in case both apply
9812 // to the same app.
9813 // The binder call has already checked this, but as mOemNetworkPreferences is only
9814 // touched on the handler thread, it's theoretically not impossible that it has changed
9815 // since.
9816 if (!mProfileNetworkPreferences.isEmpty()) {
9817 logwtf("handleSetOemPreference, but per-profile network preferences not empty");
9818 return;
9819 }
9820
9821 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
9822 final int uniquePreferenceCount = new ArraySet<>(
9823 preference.getNetworkPreferences().values()).size();
9824 mSystemNetworkRequestCounter.transact(
9825 mDeps.getCallingUid(), uniquePreferenceCount,
9826 () -> {
9827 final ArraySet<NetworkRequestInfo> nris =
9828 new OemNetworkRequestFactory()
9829 .createNrisFromOemNetworkPreferences(preference);
9830 replaceDefaultNetworkRequestsForPreference(nris);
9831 });
9832 mOemNetworkPreferences = preference;
9833
9834 if (null != listener) {
9835 try {
9836 listener.onComplete();
9837 } catch (RemoteException e) {
9838 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
9839 }
9840 }
9841 }
9842
9843 private void replaceDefaultNetworkRequestsForPreference(
9844 @NonNull final Set<NetworkRequestInfo> nris) {
9845 // Pass in a defensive copy as this collection will be updated on remove.
9846 handleRemoveNetworkRequests(new ArraySet<>(mDefaultNetworkRequests));
9847 addPerAppDefaultNetworkRequests(nris);
9848 }
9849
9850 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
9851 ensureRunningOnConnectivityServiceThread();
9852 mDefaultNetworkRequests.addAll(nris);
9853 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
9854 getPerAppCallbackRequestsToUpdate();
9855 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
9856 mSystemNetworkRequestCounter.transact(
9857 mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
9858 () -> {
9859 nrisToRegister.addAll(
9860 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
9861 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
9862 handleRegisterNetworkRequests(nrisToRegister);
9863 });
9864 }
9865
9866 /**
9867 * All current requests that are tracking the default network need to be assessed as to whether
9868 * or not the current set of per-application default requests will be changing their default
9869 * network. If so, those requests will need to be updated so that they will send callbacks for
9870 * default network changes at the appropriate time. Additionally, those requests tracking the
9871 * default that were previously updated by this flow will need to be reassessed.
9872 * @return the nris which will need to be updated.
9873 */
9874 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
9875 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
9876 // Get the distinct nris to check since for multilayer requests, it is possible to have the
9877 // same nri in the map's values for each of its NetworkRequest objects.
9878 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
9879 for (final NetworkRequestInfo nri : nris) {
9880 // Include this nri if it is currently being tracked.
9881 if (isPerAppTrackedNri(nri)) {
9882 defaultCallbackRequests.add(nri);
9883 continue;
9884 }
9885 // We only track callbacks for requests tracking the default.
9886 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
9887 continue;
9888 }
9889 // Include this nri if it will be tracked by the new per-app default requests.
9890 final boolean isNriGoingToBeTracked =
9891 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
9892 if (isNriGoingToBeTracked) {
9893 defaultCallbackRequests.add(nri);
9894 }
9895 }
9896 return defaultCallbackRequests;
9897 }
9898
9899 /**
9900 * Create nris for those network requests that are currently tracking the default network that
9901 * are being controlled by a per-application default.
9902 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
9903 * foundation when creating the nri. Important items include the calling uid's original
9904 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
9905 * requests are assumed to have already been validated as needing to be updated.
9906 * @return the Set of nris to use when registering network requests.
9907 */
9908 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
9909 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
9910 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
9911 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
9912 final NetworkRequestInfo trackingNri =
9913 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
9914
9915 // If this nri is not being tracked, the change it back to an untracked nri.
9916 if (trackingNri == mDefaultRequest) {
9917 callbackRequestsToRegister.add(new NetworkRequestInfo(
9918 callbackRequest,
9919 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
9920 continue;
9921 }
9922
9923 final NetworkRequest request = callbackRequest.mRequests.get(0);
9924 callbackRequestsToRegister.add(new NetworkRequestInfo(
9925 callbackRequest,
9926 copyNetworkRequestsForUid(
9927 trackingNri.mRequests, callbackRequest.mAsUid,
9928 callbackRequest.mUid, request.getRequestorPackageName())));
9929 }
9930 return callbackRequestsToRegister;
9931 }
9932
9933 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
9934 @NonNull final Set<UidRange> uids) {
9935 for (final NetworkRequest req : requests) {
9936 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
9937 }
9938 }
9939
9940 /**
9941 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
9942 */
9943 @VisibleForTesting
9944 final class OemNetworkRequestFactory {
9945 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
9946 @NonNull final OemNetworkPreferences preference) {
9947 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
9948 final SparseArray<Set<Integer>> uids =
9949 createUidsFromOemNetworkPreferences(preference);
9950 for (int i = 0; i < uids.size(); i++) {
9951 final int key = uids.keyAt(i);
9952 final Set<Integer> value = uids.valueAt(i);
9953 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
9954 // No need to add an nri without any requests.
9955 if (0 == nri.mRequests.size()) {
9956 continue;
9957 }
9958 nris.add(nri);
9959 }
9960
9961 return nris;
9962 }
9963
9964 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
9965 @NonNull final OemNetworkPreferences preference) {
9966 final SparseArray<Set<Integer>> uids = new SparseArray<>();
9967 final PackageManager pm = mContext.getPackageManager();
9968 final List<UserHandle> users =
9969 mContext.getSystemService(UserManager.class).getUserHandles(true);
9970 if (null == users || users.size() == 0) {
9971 if (VDBG || DDBG) {
9972 log("No users currently available for setting the OEM network preference.");
9973 }
9974 return uids;
9975 }
9976 for (final Map.Entry<String, Integer> entry :
9977 preference.getNetworkPreferences().entrySet()) {
9978 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
9979 try {
9980 final int uid = pm.getApplicationInfo(entry.getKey(), 0).uid;
9981 if (!uids.contains(pref)) {
9982 uids.put(pref, new ArraySet<>());
9983 }
9984 for (final UserHandle ui : users) {
9985 // Add the rules for all users as this policy is device wide.
9986 uids.get(pref).add(ui.getUid(uid));
9987 }
9988 } catch (PackageManager.NameNotFoundException e) {
9989 // Although this may seem like an error scenario, it is ok that uninstalled
9990 // packages are sent on a network preference as the system will watch for
9991 // package installations associated with this network preference and update
9992 // accordingly. This is done so as to minimize race conditions on app install.
9993 continue;
9994 }
9995 }
9996 return uids;
9997 }
9998
9999 private NetworkRequestInfo createNriFromOemNetworkPreferences(
10000 @OemNetworkPreferences.OemNetworkPreference final int preference,
10001 @NonNull final Set<Integer> uids) {
10002 final List<NetworkRequest> requests = new ArrayList<>();
10003 // Requests will ultimately be evaluated by order of insertion therefore it matters.
10004 switch (preference) {
10005 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
10006 requests.add(createUnmeteredNetworkRequest());
10007 requests.add(createOemPaidNetworkRequest());
10008 requests.add(createDefaultInternetRequestForTransport(
10009 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10010 break;
10011 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
10012 requests.add(createUnmeteredNetworkRequest());
10013 requests.add(createOemPaidNetworkRequest());
10014 break;
10015 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
10016 requests.add(createOemPaidNetworkRequest());
10017 break;
10018 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
10019 requests.add(createOemPrivateNetworkRequest());
10020 break;
10021 default:
10022 // This should never happen.
10023 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
10024 + " called with invalid preference of " + preference);
10025 }
10026
10027 final ArraySet ranges = new ArraySet<Integer>();
10028 for (final int uid : uids) {
10029 ranges.add(new UidRange(uid, uid));
10030 }
10031 setNetworkRequestUids(requests, ranges);
10032 return new NetworkRequestInfo(Process.myUid(), requests);
10033 }
10034
10035 private NetworkRequest createUnmeteredNetworkRequest() {
10036 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10037 .addCapability(NET_CAPABILITY_NOT_METERED)
10038 .addCapability(NET_CAPABILITY_VALIDATED);
10039 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
10040 }
10041
10042 private NetworkRequest createOemPaidNetworkRequest() {
10043 // NET_CAPABILITY_OEM_PAID is a restricted capability.
10044 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10045 .addCapability(NET_CAPABILITY_OEM_PAID)
10046 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10047 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10048 }
10049
10050 private NetworkRequest createOemPrivateNetworkRequest() {
10051 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
10052 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
10053 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
10054 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10055 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
10056 }
10057
10058 private NetworkCapabilities createDefaultPerAppNetCap() {
10059 final NetworkCapabilities netCap = new NetworkCapabilities();
10060 netCap.addCapability(NET_CAPABILITY_INTERNET);
10061 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
10062 return netCap;
10063 }
10064 }
10065}